<commit_before>/*

Edtended handling of  oolor type fields.

Has optional support for using https://github.com/Sphinxxxx/vanilla-picker.

*/
import { StringEditor } from './string'
import { $extend } from '../utilities'

export var ColorEditor = StringEditor.extend({

  build: function () {
    this._super()
    if (!this.input) return
    if (window.Picker) { // do when vanilla-picker loaded
      this.input.type = 'text'
      const self = this
      const defaultValue = this.schema.default || '#000000'
      const pickerOptions = $extend({
        editor: false, // default no editor
        alpha: false, // default no alpha
        popup: 'bottom' // show in the bottom
      }, (this.options || {}).Picker || {}, {
        parent: this.container,
        color: defaultValue,
        onChange: function (color) {
          const format = this.settings.editorFormat
          const isAlpha = this.settings.alpha
          self.setValue(format === 'hex' ? (isAlpha ? color.hex : color.hex.slice(0, 7)) : color[format + (isAlpha ? 'a' : '') + 'String'])
        }
      })
      this.picker = new window.Picker(pickerOptions)
      this.picker.openHandler()
      if (!pickerOptions.popup) { // use inline colorPicker
        this.input.style.display = 'none'
      } else {
        this.addEventListener(false)
      }
    }
  },
  destroy: function () {
    this.picker.closeHandler()
    this.picker = null
    this.picker.destroy()
    this.addEventListener(true)
    this._super()
  },
  // helper functions
  addEventListener: function (off) {
    var action = off ? 'removeEventListener' : 'addEventListener'
    var self = this
    function onfocus (e) {
      self.picker.setColor(self.input.value, true)
      self.picker.show()
    }
    this.input[action]('focus', onfocus)
  }
})
<commit_msg>fix the destroy member of colorpicker editor<commit_after>/*

Edtended handling of  oolor type fields.

Has optional support for using https://github.com/Sphinxxxx/vanilla-picker.

*/
import { StringEditor } from './string'
import { $extend } from '../utilities'

export var ColorEditor = StringEditor.extend({

  build: function () {
    this._super()
    if (!this.input) return
    if (window.Picker) { // do when vanilla-picker loaded
      this.input.type = 'text'
      const self = this
      const defaultValue = this.schema.default || '#000000'
      const pickerOptions = $extend({
        editor: false, // default no editor
        alpha: false, // default no alpha
        popup: 'bottom' // show in the bottom
      }, (this.options || {}).Picker || {}, {
        parent: this.container,
        color: defaultValue,
        onChange: function (color) {
          const format = this.settings.editorFormat
          const isAlpha = this.settings.alpha
          self.setValue(format === 'hex' ? (isAlpha ? color.hex : color.hex.slice(0, 7)) : color[format + (isAlpha ? 'a' : '') + 'String'])
        }
      })
      this.picker = new window.Picker(pickerOptions)
      this.picker.openHandler()
      if (!pickerOptions.popup) { // use inline colorPicker
        this.input.style.display = 'none'
      } else {
        this.addEventListener(false)
      }
    }
  },
  destroy: function () {
    this.picker.closeHandler()
    this.picker.destroy()
    this.picker = null
    this.addEventListener(true)
    this._super()
  },
  // helper functions
  addEventListener: function (off) {
    var action = off ? 'removeEventListener' : 'addEventListener'
    var self = this
    function onfocus (e) {
      self.picker.setColor(self.input.value, true)
      self.picker.show()
    }
    this.input[action]('focus', onfocus)
  }
})
<|endoftext|>


<commit_before>exports.run = (client, payload) => {
  const action = payload.action;
  const pullRequest = payload.pull_request;
  const number = pullRequest.number;
  const repository = payload.repository;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  const review = payload.review;
  if (client.cfg.reviewedLabel && client.cfg.needsReviewLabel) {
    exports.managePRLabels(client, action, pullRequest, review, repository);
  }
  if (action === "submitted" && client.cfg.pullRequestsAssignee) {
    client.issues.addAssigneesToIssue({
      owner: repoOwner, repo: repoName, number: number, assignees: [review.user.login]
    });
  } else if (action === "labeled" && client.cfg.areaLabels) {
    client.issues.get({
      owner: repoOwner, repo: repoName, number: number
    }).then((response) => {
      client.automations.get("areaLabel").run(client, response.data, repository, payload.label);
    });
  } else if (!client.cfg.areaLabels || !client.cfg.commitReferenceEnabled) {
    return;
  }
  if (action === "opened") {
    client.automations.get("issueReferenced").run(client, pullRequest, repository, true);
  } else if (action === "synchronize") {
    client.automations.get("issueReferenced").run(client, pullRequest, repository, false);
    if (client.cfg.checkMergeConflicts) {
      client.automations.get("checkMergeConflicts").check(client, number, repoName, repoOwner);
    }
  }
};

exports.managePRLabels = (client, action, pullRequest, review, repository) => {
  const number = pullRequest.number;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  client.issues.getIssueLabels({
    owner: repoOwner, repo: repoName, number: number
  }).then((response) => {
    let labels = response.data.map(label => label.name);
    const needsReview = labels.includes(client.cfg.needsReviewLabel);
    const reviewed = labels.includes(client.cfg.reviewedLabel);
    if (action === "opened" || action === "reopened") {
      labels.push(client.cfg.needsReviewLabel);
    } else if (action === "submitted" && needsReview && review.user.login !== pullRequest.user.login) {
      labels[labels.indexOf(client.cfg.needsReviewLabel)] = client.cfg.reviewedLabel;
    } else if (action === "synchronize" && reviewed) {
      labels[labels.indexOf(client.cfg.reviewedLabel)] = client.cfg.needsReviewLabel;
    } else if (action === "closed" && reviewed) {
      labels.splice(labels.indexOf(client.cfg.reviewedLabel), 1);
    } else if (action === "closed" && needsReview) {
      labels.splice(labels.indexOf(client.cfg.needsReviewLabel), 1);
    } else {
      return;
    }
    client.issues.replaceAllLabels({
      owner: repoOwner, repo: repoName, number: number, labels: labels
    });
  });
};

exports.events = ["pull_request", "pull_request_review"];
<commit_msg>pull requests: Reimplement escapeWIPString to escape team mentions.<commit_after>exports.run = (client, payload) => {
  const action = payload.action;
  const pullRequest = payload.pull_request;
  const number = pullRequest.number;
  const repository = payload.repository;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  const review = payload.review;
  if (client.cfg.reviewedLabel && client.cfg.needsReviewLabel) {
    exports.managePRLabels(client, action, pullRequest, review, repository);
  }
  if (action === "submitted" && client.cfg.pullRequestsAssignee) {
    client.issues.addAssigneesToIssue({
      owner: repoOwner, repo: repoName, number: number, assignees: [review.user.login]
    });
  } else if (action === "labeled" && client.cfg.areaLabels) {
    client.issues.get({
      owner: repoOwner, repo: repoName, number: number
    }).then((response) => {
      client.automations.get("areaLabel").run(client, response.data, repository, payload.label);
    });
  } else if (!client.cfg.areaLabels || !client.cfg.commitReferenceEnabled) {
    return;
  }
  if (action === "opened" && !pullRequest.title.includes(client.cfg.escapeWIPString)) {
    client.automations.get("issueReferenced").run(client, pullRequest, repository, true);
  } else if (action === "synchronize") {
    client.automations.get("issueReferenced").run(client, pullRequest, repository, false);
    if (client.cfg.checkMergeConflicts) {
      client.automations.get("checkMergeConflicts").check(client, number, repoName, repoOwner);
    }
  }
};

exports.managePRLabels = (client, action, pullRequest, review, repository) => {
  const number = pullRequest.number;
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  client.issues.getIssueLabels({
    owner: repoOwner, repo: repoName, number: number
  }).then((response) => {
    let labels = response.data.map(label => label.name);
    const needsReview = labels.includes(client.cfg.needsReviewLabel);
    const reviewed = labels.includes(client.cfg.reviewedLabel);
    if (action === "opened" || action === "reopened") {
      labels.push(client.cfg.needsReviewLabel);
    } else if (action === "submitted" && needsReview && review.user.login !== pullRequest.user.login) {
      labels[labels.indexOf(client.cfg.needsReviewLabel)] = client.cfg.reviewedLabel;
    } else if (action === "synchronize" && reviewed) {
      labels[labels.indexOf(client.cfg.reviewedLabel)] = client.cfg.needsReviewLabel;
    } else if (action === "closed" && reviewed) {
      labels.splice(labels.indexOf(client.cfg.reviewedLabel), 1);
    } else if (action === "closed" && needsReview) {
      labels.splice(labels.indexOf(client.cfg.needsReviewLabel), 1);
    } else {
      return;
    }
    client.issues.replaceAllLabels({
      owner: repoOwner, repo: repoName, number: number, labels: labels
    });
  });
};

exports.events = ["pull_request", "pull_request_review"];
<|endoftext|>


<commit_before>/* @flow */

import type Site from '../site';

import { skipMeta, skipDirectories } from '../transforms/skip-items';

export const NAVIGATION_META_KEY = 'navigation';

const TITLE_KEY = 'title';
const INDEX_KEY = 'index';

export type NavigationEntry = {
    title: string,
    index: number,
    path: string
};

export default function buildNavigation(site : Site) : Site {
    const navigation : NavigationEntry[] = [];
    site.forEachWithFilters([skipMeta, skipDirectories], (item) => {
        const navigationEntry : NavigationEntry = {
            title: item.getMeta(TITLE_KEY),
            index: item.getMeta(INDEX_KEY),
            path: item.getFilePath()
        };
        navigation.push(navigationEntry);
    });
    navigation.sort((a, b) => {
        const aIndex = a[INDEX_KEY];
        const bIndex = b[INDEX_KEY];
        if (aIndex < bIndex) {
            return -1;
        } else if (aIndex > bIndex) {
            return 1;
        } else {
            return 0;
        }
    });
    return site.withMeta(NAVIGATION_META_KEY, navigation);
}
<commit_msg>Fix navigation<commit_after>/* @flow */

import type Site from '../site';
import { skipMeta, skipDirectories } from '../transforms/skip-items';
import {getLogger} from '../logging';

export const NAVIGATION_META_KEY = 'navigation';

const TITLE_KEY = 'title';
const INDEX_KEY = 'index';

export type NavigationEntry = {
    title: string,
    index: number,
    path: string
};

export default function buildNavigation(site : Site) : Site {
    const log = getLogger('navigation');
    const navigation : NavigationEntry[] = [];
    site.forEachWithFilters([skipMeta, skipDirectories], (item) => {
        if (item.getMeta(INDEX_KEY)) {
            log.debug(`Entry in file: ${item.getFilePath()}`);
            const navigationEntry : NavigationEntry = {
                title: item.getMeta(TITLE_KEY),
                index: item.getMeta(INDEX_KEY),
                path: item.getFilePath()
            };
            navigation.push(navigationEntry);
        }
    });
    const sortedNavigation = navigation.sort((a, b) => {
        if (a.index < b.index) {
            return -1;
        } else if (a.index > b.index) {
            return 1;
        } else {
            return 0;
        }
    });
    log.info('Final navigation entries:'
            + sortedNavigation.map((x) => x.title).toString());
    return site.withMeta(NAVIGATION_META_KEY, sortedNavigation);
}
<|endoftext|>


<commit_before>/**
 * Created by arielmashraki on 8/1/14.
 */
<commit_msg>fix(rtrim): fix regex for filter<commit_after>/**
* @ngdoc filter
* @name rtrim
* @kind function
*
* @description
* Right trim. Similar to trimFilter, but only for right side.
*/

angular.module('a8m.rtrim', [])

  .filter('rtrim', function () {
    return function(input, chars) {

      var trim = chars || '\\s';

      if(!isString(input)) {
        return input;
      }

      return input.replace(new RegExp(trim + '+$'), '');
    }
  });
<|endoftext|>


<commit_before>import * as web from 'express-decorators';
import multer from 'multer';
import fsp from 'fs-promise';
import _ from 'lodash';
import utils from 'libs/utils';
import errors from 'libs/errors';
import permissions from 'libs/permissions';

const upload = multer({
  storage: multer.diskStorage({}),
  limits: {
    fieldSize: Math.max(
      DI.config.compile.limits.sizeOfCode,
      DI.config.compile.limits.sizeOfBin,
      DI.config.compile.limits.sizeOfText
    ) * 2,
    fileSize: DI.config.compile.limits.sizeOfBin * 2,
  },
});

@web.controller('/submission')
export default class Handler {

  @web.use()
  async navType(req, res, next) {
    res.locals.nav_type = 'submission';
    next();
  }

  @web.get('/')
  @web.middleware(utils.checkLogin())
  async getSubmissionAction(req, res) {
    const sdocs = await DI.models.Submission.getUserSubmissionsAsync(req.credential._id);
    res.render('submission_main', {
      page_title: 'My Submissions',
      sdocs,
    });
  }

  @web.get('/create')
  @web.middleware(utils.checkProfile())
  @web.middleware(utils.checkLogin())
  async getSubmissionCreateAction(req, res) {
    res.render('submission_create', {
      page_title: 'Submit My Brain',
      canSubmit: await DI.models.Submission.isUserAllowedToSubmitAsync(req.credential._id),
    });
  }

  @web.post('/create')
  @web.middleware(utils.sanitizeBody({
    code: utils.checkNonEmptyString(),
  }))
  @web.middleware(utils.checkProfile())
  @web.middleware(utils.checkLogin())
  async postSubmissionCreateAction(req, res) {
    await DI.models.Submission.createSubmissionAsync(
      req.credential._id,
      req.data.code
    );
    res.redirect(utils.url('/submission'));
  }

  @web.get('/:id')
  @web.middleware(utils.checkLogin())
  async getSubmissionDetailAction(req, res) {
    const sdoc = await DI.models.Submission.getSubmissionObjectByIdAsync(req.params.id);
    if (
      !sdoc.user.equals(req.credential._id)
      && !req.credential.hasPermission(permissions.PERM_VIEW_ALL_SUBMISSION)
    ) {
      throw new errors.PermissionError();
    }
    await sdoc.populate('user').execPopulate();
    res.render('submission_detail', {
      page_title: 'Submission Detail',
      sdoc,
    });
  }

  @web.post('/api/compileBegin')
  @web.middleware(utils.sanitizeBody({
    id: utils.checkNonEmptyString(),
    token: utils.checkNonEmptyString(),
  }))
  @web.middleware(utils.checkAPI())
  async apiCompileBegin(req, res) {
    const sdoc = await DI.models.Submission.judgeStartCompileAsync(
      req.data.id,
      req.data.token
    );
    await sdoc.populate('user').execPopulate();
    res.json(sdoc);
  }

  @web.post('/api/compileError')
  @web.middleware(utils.sanitizeBody({
    id: utils.checkNonEmptyString(),
    token: utils.checkNonEmptyString(),
    text: utils.checkString(),
  }))
  @web.middleware(utils.checkAPI())
  async apiCompileError(req, res) {
    const sdoc = await DI.models.Submission.judgeSetSystemErrorAsync(
      req.data.id,
      req.data.token,
      req.data.text
    );
    res.json(sdoc);
  }

  @web.post('/api/compileEnd')
  @web.middleware(utils.sanitizeBody({
    id: utils.checkNonEmptyString(),
    token: utils.checkNonEmptyString(),
    text: utils.checkString(),
    success: utils.checkBool(),
  }))
  @web.middleware(upload.single('binary'))
  @web.middleware(utils.checkAPI())
  async apiCompileEnd(req, res) {
    let buffer = null;
    if (req.data.success && req.file) {
      buffer = await fsp.readFile(req.file.path);
      try {
        await fsp.remove(req.file.path);
      } catch (ignore) {
      }
    }
    const sdoc = await DI.models.Submission.judgeCompleteCompileAsync(
      req.data.id,
      req.data.token,
      req.data.success,
      req.data.text,
      buffer,
    );
    res.json(sdoc);
  }

  @web.get('/api/binary')
  @web.middleware(utils.sanitizeQuery({
    id: utils.checkNonEmptyString(),
  }))
  @web.middleware(utils.checkAPI())
  async apiGetBinary(req, res) {
    const sdoc = await DI.models.Submission.getSubmissionObjectByIdAsync(
      req.data.id,
      { executable: 1 }
    );
    res.send(sdoc.executable.buffer);
  }

}
<commit_msg>fix buffer<commit_after>import * as web from 'express-decorators';
import multer from 'multer';
import fsp from 'fs-promise';
import _ from 'lodash';
import utils from 'libs/utils';
import errors from 'libs/errors';
import permissions from 'libs/permissions';

const upload = multer({
  storage: multer.diskStorage({}),
  limits: {
    fieldSize: Math.max(
      DI.config.compile.limits.sizeOfCode,
      DI.config.compile.limits.sizeOfBin,
      DI.config.compile.limits.sizeOfText
    ) * 2,
    fileSize: DI.config.compile.limits.sizeOfBin * 2,
  },
});

@web.controller('/submission')
export default class Handler {

  @web.use()
  async navType(req, res, next) {
    res.locals.nav_type = 'submission';
    next();
  }

  @web.get('/')
  @web.middleware(utils.checkLogin())
  async getSubmissionAction(req, res) {
    const sdocs = await DI.models.Submission.getUserSubmissionsAsync(req.credential._id);
    res.render('submission_main', {
      page_title: 'My Submissions',
      sdocs,
    });
  }

  @web.get('/create')
  @web.middleware(utils.checkProfile())
  @web.middleware(utils.checkLogin())
  async getSubmissionCreateAction(req, res) {
    res.render('submission_create', {
      page_title: 'Submit My Brain',
      canSubmit: await DI.models.Submission.isUserAllowedToSubmitAsync(req.credential._id),
    });
  }

  @web.post('/create')
  @web.middleware(utils.sanitizeBody({
    code: utils.checkNonEmptyString(),
  }))
  @web.middleware(utils.checkProfile())
  @web.middleware(utils.checkLogin())
  async postSubmissionCreateAction(req, res) {
    await DI.models.Submission.createSubmissionAsync(
      req.credential._id,
      req.data.code
    );
    res.redirect(utils.url('/submission'));
  }

  @web.get('/:id')
  @web.middleware(utils.checkLogin())
  async getSubmissionDetailAction(req, res) {
    const sdoc = await DI.models.Submission.getSubmissionObjectByIdAsync(req.params.id);
    if (
      !sdoc.user.equals(req.credential._id)
      && !req.credential.hasPermission(permissions.PERM_VIEW_ALL_SUBMISSION)
    ) {
      throw new errors.PermissionError();
    }
    await sdoc.populate('user').execPopulate();
    res.render('submission_detail', {
      page_title: 'Submission Detail',
      sdoc,
    });
  }

  @web.post('/api/compileBegin')
  @web.middleware(utils.sanitizeBody({
    id: utils.checkNonEmptyString(),
    token: utils.checkNonEmptyString(),
  }))
  @web.middleware(utils.checkAPI())
  async apiCompileBegin(req, res) {
    const sdoc = await DI.models.Submission.judgeStartCompileAsync(
      req.data.id,
      req.data.token
    );
    await sdoc.populate('user').execPopulate();
    res.json(sdoc);
  }

  @web.post('/api/compileError')
  @web.middleware(utils.sanitizeBody({
    id: utils.checkNonEmptyString(),
    token: utils.checkNonEmptyString(),
    text: utils.checkString(),
  }))
  @web.middleware(utils.checkAPI())
  async apiCompileError(req, res) {
    const sdoc = await DI.models.Submission.judgeSetSystemErrorAsync(
      req.data.id,
      req.data.token,
      req.data.text
    );
    res.json(sdoc);
  }

  @web.post('/api/compileEnd')
  @web.middleware(utils.sanitizeBody({
    id: utils.checkNonEmptyString(),
    token: utils.checkNonEmptyString(),
    text: utils.checkString(),
    success: utils.checkBool(),
  }))
  @web.middleware(upload.single('binary'))
  @web.middleware(utils.checkAPI())
  async apiCompileEnd(req, res) {
    let buffer = null;
    if (req.data.success && req.file) {
      buffer = await fsp.readFile(req.file.path);
      try {
        await fsp.remove(req.file.path);
      } catch (ignore) {
      }
    }
    const sdoc = await DI.models.Submission.judgeCompleteCompileAsync(
      req.data.id,
      req.data.token,
      req.data.success,
      req.data.text,
      buffer,
    );
    res.json(sdoc);
  }

  @web.get('/api/binary')
  @web.middleware(utils.sanitizeQuery({
    id: utils.checkNonEmptyString(),
  }))
  @web.middleware(utils.checkAPI())
  async apiGetBinary(req, res) {
    const sdoc = await DI.models.Submission.getSubmissionObjectByIdAsync(
      req.data.id,
      { executable: 1 }
    );
    res.send(new Buffer(sdoc.executable));
  }

}
<|endoftext|>


<commit_before>import isReturned from "./is-returned";
import useFastRoot from "./use-fast-root";
import moduleSource from "./module-source";

const map = new WeakMap();

const rootElementFinder = {
  JSXElement(path) {
    const { jsx, crossedFunction } = this;

    // No need to traverse our JSX element.
    if (path === jsx) {
      path.skip();
      return;
    }

    const returned = isReturned(jsx);
    const otherIsReturned = isReturned(path);

    // We're looking for a root element, which must be returned by the function.
    if (otherIsReturned && (crossedFunction || !returned)) {
      this.root = path;
      path.stop();
    }
  },

  // Don't traverse into other functions, since they cannot contain the root.
  Function(path) {
    path.skip();
  }
};

function inPatchRoot(path, plugin) {
  const { opts, file } = plugin;
  if (useFastRoot(path, opts)) {
    return true;
  }

  const importSource = moduleSource(plugin);
  if (!importSource) {
    return true;
  }

  const patchRoots = [];
  const { imports } = file.metadata.modules;
  const iDOMImport = imports.find((imported) => {
    return imported.source === importSource;
  });

  if (iDOMImport && iDOMImport.imported.includes("patch")) {
    const patchImport = iDOMImport.specifiers.find((imported) => {
      return imported.imported === "patch";
    });
    const binding = file.scope.getBinding(patchImport.local);

    binding.referencePaths.forEach((reference) => {
      const { parentPath } = reference;
      if (parentPath.isCallExpression()) {
        patchRoots.push(parentPath);
      }
    });
  } else if (iDOMImport && iDOMImport.imported.includes("*")) {
    const starImport = iDOMImport.specifiers.find((imported) => {
      return imported.kind === "namespace";
    });
    const binding = file.scope.getBinding(starImport.local);

    binding.referencePaths.forEach((reference) => {
      const { parentPath } = reference;
      if (parentPath.isMemberExpression()) {
        const property = parentPath.get("property");
        if (property.isIdentifier({ name: "patch" })) {
          const grandParentPath = parentPath.parentPath;
          if (grandParentPath.isCallExpression()) {
            patchRoots.push(grandParentPath);
          }
        }
      }
    });
  }

  return !patchRoots.length || path.findParent((parent) => {
    return patchRoots.includes(parent);
  });
}

// Detects if this JSX element is the root element.
// It is not the root if there is another root element in this
// or a higher function scope.
export default function isRootJSX(path, plugin) {
  const state = {
    root: null,
    crossedFunction: false,
    jsx: path
  };

  if (!path.isJSX() && path.getFunctionParent().isProgram()) {
    return true;
  }

  if (!isReturned(path)) {
    return false;
  }

  if (!inPatchRoot(path, plugin)) {
    return false;
  }

  path.findParent((path) => {
    if (path.isJSXElement()) {
      state.root = path;
    } else if (path.isFunction() || path.isProgram()) {
      if (map.has(path)) {
        state.root = map.get(path);
      } else {
        path.traverse(rootElementFinder, state);
        map.set(path, state.root);
      }

      state.crossedFunction = true;
    }

    // End early if another JSXElement is found.
    return state.root;
  });

  return !state.root || state.root === path;
}
<commit_msg>Fix for Node 4<commit_after>import isReturned from "./is-returned";
import useFastRoot from "./use-fast-root";
import moduleSource from "./module-source";

const map = new WeakMap();

const rootElementFinder = {
  JSXElement(path) {
    const { jsx, crossedFunction } = this;

    // No need to traverse our JSX element.
    if (path === jsx) {
      path.skip();
      return;
    }

    const returned = isReturned(jsx);
    const otherIsReturned = isReturned(path);

    // We're looking for a root element, which must be returned by the function.
    if (otherIsReturned && (crossedFunction || !returned)) {
      this.root = path;
      path.stop();
    }
  },

  // Don't traverse into other functions, since they cannot contain the root.
  Function(path) {
    path.skip();
  }
};

function inPatchRoot(path, plugin) {
  const { opts, file } = plugin;
  if (useFastRoot(path, opts)) {
    return true;
  }

  const importSource = moduleSource(plugin);
  if (!importSource) {
    return true;
  }

  const patchRoots = [];
  const { imports } = file.metadata.modules;
  const iDOMImport = imports.find((imported) => {
    return imported.source === importSource;
  });

  if (iDOMImport && iDOMImport.imported.indexOf("patch") > -1) {
    const patchImport = iDOMImport.specifiers.find((imported) => {
      return imported.imported === "patch";
    });
    const binding = file.scope.getBinding(patchImport.local);

    binding.referencePaths.forEach((reference) => {
      const { parentPath } = reference;
      if (parentPath.isCallExpression()) {
        patchRoots.push(parentPath);
      }
    });
  } else if (iDOMImport && iDOMImport.imported.indexOf("*") > -1) {
    const starImport = iDOMImport.specifiers.find((imported) => {
      return imported.kind === "namespace";
    });
    const binding = file.scope.getBinding(starImport.local);

    binding.referencePaths.forEach((reference) => {
      const { parentPath } = reference;
      if (parentPath.isMemberExpression()) {
        const property = parentPath.get("property");
        if (property.isIdentifier({ name: "patch" })) {
          const grandParentPath = parentPath.parentPath;
          if (grandParentPath.isCallExpression()) {
            patchRoots.push(grandParentPath);
          }
        }
      }
    });
  }

  return !patchRoots.length || path.findParent((parent) => {
    return patchRoots.indexOf(parent) > -1;
  });
}

// Detects if this JSX element is the root element.
// It is not the root if there is another root element in this
// or a higher function scope.
export default function isRootJSX(path, plugin) {
  const state = {
    root: null,
    crossedFunction: false,
    jsx: path
  };

  if (!path.isJSX() && path.getFunctionParent().isProgram()) {
    return true;
  }

  if (!isReturned(path)) {
    return false;
  }

  if (!inPatchRoot(path, plugin)) {
    return false;
  }

  path.findParent((path) => {
    if (path.isJSXElement()) {
      state.root = path;
    } else if (path.isFunction() || path.isProgram()) {
      if (map.has(path)) {
        state.root = map.get(path);
      } else {
        path.traverse(rootElementFinder, state);
        map.set(path, state.root);
      }

      state.crossedFunction = true;
    }

    // End early if another JSXElement is found.
    return state.root;
  });

  return !state.root || state.root === path;
}
<|endoftext|>


<commit_before>import React from 'react'
//
import { types } from '../actions'

export const defaultState = {}

const defaultReducer = (old, newState) => newState

export const useTableState = (
  initialState = {},
  overrides,
  { reducer = defaultReducer, useState: userUseState = React.useState } = {}
) => {
  let [state, setState] = userUseState({
    ...defaultState,
    ...initialState,
  })

  const overriddenState = React.useMemo(() => {
    const newState = {
      ...state,
    }
    if (overrides) {
      Object.keys(overrides).forEach(key => {
        newState[key] = overrides[key]
      })
    }
    return newState
  }, [overrides, state])

  const overriddenStateRef = React.useRef()
  overriddenStateRef.current = overriddenState

  const reducedSetState = React.useCallback(
    (updater, type) => {
      return setState(old => {
        const newState = updater(old)
        return reducer(old, newState, type)
      })
    },
    [reducer, setState]
  )

  return React.useMemo(() => [overriddenState, reducedSetState], [
    overriddenState,
    reducedSetState,
  ])
}
<commit_msg>fix: cleanup<commit_after>import React from 'react'
//
export const defaultState = {}

const defaultReducer = (old, newState) => newState

export const useTableState = (
  initialState = {},
  overrides,
  { reducer = defaultReducer, useState: userUseState = React.useState } = {}
) => {
  let [state, setState] = userUseState({
    ...defaultState,
    ...initialState,
  })

  const overriddenState = React.useMemo(() => {
    const newState = {
      ...state,
    }
    if (overrides) {
      Object.keys(overrides).forEach(key => {
        newState[key] = overrides[key]
      })
    }
    return newState
  }, [overrides, state])

  const overriddenStateRef = React.useRef()
  overriddenStateRef.current = overriddenState

  const reducedSetState = React.useCallback(
    (updater, type) => {
      return setState(old => {
        const newState = updater(old)
        return reducer(old, newState, type)
      })
    },
    [reducer, setState]
  )

  return React.useMemo(() => [overriddenState, reducedSetState], [
    overriddenState,
    reducedSetState,
  ])
}
<|endoftext|>


<commit_before>'use strict';

/* eslint-disable max-len */
/**
 * Checks if input `value` is `Generator Function`
 *
 * @func isGeneratorFunction
 * @memberOf RA
 * @since {@link https://char0n.github.io/ramda-adjunct/0.5.0|v0.5.0}
 * @category Type
 * @sig * -> Boolean
 * @param {*} val The value to test
 * @return {Boolean}
 * @see {@link RA.isFunction|isFunction}, {@link RA.isAsyncFunction|isAsyncFunction}, {@link RA.isNotGeneratorFunction|isNotGeneratorFunction}
 * @example
 *
 * RA.isGeneratorFunction(function* test() { }); //=> true
 * RA.isGeneratorFunction(null); //=> false
 * RA.isGeneratorFunction(function test() { }); //=> false
 * RA.isGeneratorFunction(() => {}); //=> false
 */
/* eslint-enable max-len */

module.exports = val => Object.prototype.toString.call(val) === '[object GeneratorFunction]';
<commit_msg>fix(isGeneratorFunction): add legacy check<commit_after>'use strict';

const isNotNull = require('./isNotNull');

let GeneratorFunction;
try {
  GeneratorFunction = new Function('return function* () {}')().constructor; // eslint-disable-line no-new-func
} catch (e) {
  GeneratorFunction = null;
}

/* eslint-disable max-len */
/**
 * Checks if input `value` is `Generator Function`
 *
 * @func isGeneratorFunction
 * @memberOf RA
 * @since {@link https://char0n.github.io/ramda-adjunct/0.5.0|v0.5.0}
 * @category Type
 * @sig * -> Boolean
 * @param {*} val The value to test
 * @return {Boolean}
 * @see {@link RA.isFunction|isFunction}, {@link RA.isAsyncFunction|isAsyncFunction}, {@link RA.isNotGeneratorFunction|isNotGeneratorFunction}
 * @example
 *
 * RA.isGeneratorFunction(function* test() { }); //=> true
 * RA.isGeneratorFunction(null); //=> false
 * RA.isGeneratorFunction(function test() { }); //=> false
 * RA.isGeneratorFunction(() => {}); //=> false
 */
/* eslint-enable max-len */

module.exports = (val) => {
  const toStringCheck = Object.prototype.toString.call(val) === '[object GeneratorFunction]';
  const legacyConstructorCheck = isNotNull(GeneratorFunction) && val instanceof GeneratorFunction;

  return toStringCheck || legacyConstructorCheck;
};
<|endoftext|>


<commit_before>/**
 *
 * ZigbeeClassifier - Determines properties from Zigbee clusters.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.*
 */

'use strict';

const zclId = require('zcl-id');
const utils = require('../utils');
const ZigbeeProperty = require('./zb-property');

const ZHA_PROFILE_ID = zclId.profile('HA').value;
const ZHA_PROFILE_ID_HEX = utils.hexStr(ZHA_PROFILE_ID, 4);
const CLUSTER_ID_GENONOFF = zclId.cluster('genOnOff').value;
const CLUSTER_ID_GENONOFF_HEX = utils.hexStr(CLUSTER_ID_GENONOFF, 4);
const CLUSTER_ID_GENLEVELCTRL = zclId.cluster('genLevelCtrl').value;
const CLUSTER_ID_GENLEVELCTRL_HEX = utils.hexStr(CLUSTER_ID_GENLEVELCTRL, 4);

const THING_TYPE_ON_OFF_SWITCH = 'onOffSwitch';
const THING_TYPE_MULTI_LEVEL_SWITCH = 'multiLevelSwitch';

class ZigbeeClassifier {

  constructor() {
  }

  addLevelProperty(node, endpoint) {
    this.addProperty(
      node,                           // device
      'level',                        // name
      {                               // property description
        type: 'number',
        unit: '%',
        min: 0,
        max: 100,
      },
      ZHA_PROFILE_ID,                 // profileId
      endpoint,                       // endpoint
      CLUSTER_ID_GENLEVELCTRL,        // clusterId
      'currentLevel',                 // attr
      'setLevelValue',                // setAttrFromValue
      'parseLevelAttr'                // parseValueFromAttr
    );
  }

  addOnProperty(node, endpoint) {
    this.addProperty(
      node,                           // device
      'on',                           // name
      {                               // property description
        type: 'boolean',
      },
      ZHA_PROFILE_ID,                 // profileId
      endpoint,                       // endpoint
      CLUSTER_ID_GENONOFF,            // clusterId
      'onOff',                        // attr
      'setOnOffValue',                // setAttrFromValue
      'parseOnOffAttr'                // parseValueFromAttr
    );
  }

  addProperty(node, name, descr, profileId, endpoint, clusterId,
              attr, setAttrFromValue, parseValueFromAttr) {
    let property =  new ZigbeeProperty(node, name, descr, profileId,
                                       endpoint, clusterId, attr,
                                       setAttrFromValue, parseValueFromAttr);
    node.properties.set(name, property);
    node.sendFrames([
      node.makeBindFrame(property),
      node.makeConfigReportFrame(property),
      node.makeReadAttributeFrame(property),
    ]);
  }

  findZhaEndpointWithInputClusterIdHex(node, clusterIdHex) {
    for (var endpointNum in node.activeEndpoints) {
      var endpoint = node.activeEndpoints[endpointNum];
      if (endpoint.profileId == ZHA_PROFILE_ID_HEX) {
        if (endpoint.inputClusters.includes(clusterIdHex)) {
          return endpointNum;
        }
      }
    }
  }

  // internal function allows us to use early returns.
  classifyInternal(node) {
    let endpoint;

    endpoint =
      this.findZhaEndpointWithInputClusterIdHex(node,
                                                CLUSTER_ID_GENLEVELCTRL_HEX);
    if (endpoint) {
      this.initMultiLevelSwitch(node, endpoint);
      return;
    }

    endpoint =
      this.findZhaEndpointWithInputClusterIdHex(node,
                                                CLUSTER_ID_GENONOFF_HEX);
    if (endpoint) {
      this.initOnOffSwitch(node, endpoint);
      return;
    }
  }

  classify(node) {
    if (node.isCoordinator) {
      return;
    }

    this.classifyInternal(node);

    // Now that we know the type, set the default name.
    node.defaultName = node.id + '-' + node.type;
    if (!node.name) {
      node.name = node.defaultName;
    }
  }

  initOnOffSwitch(node, endpointNum) {
    node.type = THING_TYPE_ON_OFF_SWITCH;
    this.addOnProperty(node, endpointNum);
  }

  initMultiLevelSwitch(node, endpointNum) {
    node.type = THING_TYPE_MULTI_LEVEL_SWITCH;
    this.addOnProperty(node, endpointNum);
    this.addLevelProperty(node, endpointNum);
  }
}

module.exports = new ZigbeeClassifier();
<commit_msg>Temporarily disable multilevel switch (#482)<commit_after>/**
 *
 * ZigbeeClassifier - Determines properties from Zigbee clusters.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.*
 */

'use strict';

const zclId = require('zcl-id');
const utils = require('../utils');
const ZigbeeProperty = require('./zb-property');

const ZHA_PROFILE_ID = zclId.profile('HA').value;
const ZHA_PROFILE_ID_HEX = utils.hexStr(ZHA_PROFILE_ID, 4);
const CLUSTER_ID_GENONOFF = zclId.cluster('genOnOff').value;
const CLUSTER_ID_GENONOFF_HEX = utils.hexStr(CLUSTER_ID_GENONOFF, 4);
const CLUSTER_ID_GENLEVELCTRL = zclId.cluster('genLevelCtrl').value;
const CLUSTER_ID_GENLEVELCTRL_HEX = utils.hexStr(CLUSTER_ID_GENLEVELCTRL, 4);

const THING_TYPE_ON_OFF_SWITCH = 'onOffSwitch';
const THING_TYPE_MULTI_LEVEL_SWITCH = 'multiLevelSwitch';

const UI_SUPPORTS_MULTILEVEL = false;

class ZigbeeClassifier {

  constructor() {
  }

  addLevelProperty(node, endpoint) {
    this.addProperty(
      node,                           // device
      'level',                        // name
      {                               // property description
        type: 'number',
        unit: '%',
        min: 0,
        max: 100,
      },
      ZHA_PROFILE_ID,                 // profileId
      endpoint,                       // endpoint
      CLUSTER_ID_GENLEVELCTRL,        // clusterId
      'currentLevel',                 // attr
      'setLevelValue',                // setAttrFromValue
      'parseLevelAttr'                // parseValueFromAttr
    );
  }

  addOnProperty(node, endpoint) {
    this.addProperty(
      node,                           // device
      'on',                           // name
      {                               // property description
        type: 'boolean',
      },
      ZHA_PROFILE_ID,                 // profileId
      endpoint,                       // endpoint
      CLUSTER_ID_GENONOFF,            // clusterId
      'onOff',                        // attr
      'setOnOffValue',                // setAttrFromValue
      'parseOnOffAttr'                // parseValueFromAttr
    );
  }

  addProperty(node, name, descr, profileId, endpoint, clusterId,
              attr, setAttrFromValue, parseValueFromAttr) {
    let property =  new ZigbeeProperty(node, name, descr, profileId,
                                       endpoint, clusterId, attr,
                                       setAttrFromValue, parseValueFromAttr);
    node.properties.set(name, property);
    node.sendFrames([
      node.makeBindFrame(property),
      node.makeConfigReportFrame(property),
      node.makeReadAttributeFrame(property),
    ]);
  }

  findZhaEndpointWithInputClusterIdHex(node, clusterIdHex) {
    for (var endpointNum in node.activeEndpoints) {
      var endpoint = node.activeEndpoints[endpointNum];
      if (endpoint.profileId == ZHA_PROFILE_ID_HEX) {
        if (endpoint.inputClusters.includes(clusterIdHex)) {
          return endpointNum;
        }
      }
    }
  }

  // internal function allows us to use early returns.
  classifyInternal(node) {
    let endpoint;

    if (UI_SUPPORTS_MULTILEVEL) {
      endpoint =
        this.findZhaEndpointWithInputClusterIdHex(node,
                                                  CLUSTER_ID_GENLEVELCTRL_HEX);
      if (endpoint) {
        this.initMultiLevelSwitch(node, endpoint);
        return;
      }
    }

    endpoint =
      this.findZhaEndpointWithInputClusterIdHex(node,
                                                CLUSTER_ID_GENONOFF_HEX);
    if (endpoint) {
      this.initOnOffSwitch(node, endpoint);
      return;
    }
  }

  classify(node) {
    if (node.isCoordinator) {
      return;
    }

    this.classifyInternal(node);

    // Now that we know the type, set the default name.
    node.defaultName = node.id + '-' + node.type;
    if (!node.name) {
      node.name = node.defaultName;
    }
  }

  initOnOffSwitch(node, endpointNum) {
    node.type = THING_TYPE_ON_OFF_SWITCH;
    this.addOnProperty(node, endpointNum);
  }

  initMultiLevelSwitch(node, endpointNum) {
    node.type = THING_TYPE_MULTI_LEVEL_SWITCH;
    this.addOnProperty(node, endpointNum);
    this.addLevelProperty(node, endpointNum);
  }
}

module.exports = new ZigbeeClassifier();
<|endoftext|>


<commit_before>/* global angular, console, _, Backbone, $ */
angular
	.module('boxie', ['ui', 'indx'])
	.factory('ObjsFactory', function () {
		var Objs = Backbone.Collection.extend({
			initialize: function (attributes, options) {
				if (options && options.box) { this.setBox(options.box); }
			},
			fetch: function () {
				var that = this,
					promise = $.Deferred(),
					ids = this.box.getObjIDs();
				that.box.getObj(ids).then(function (objs) {
					that.reset(objs);
					promise.resolve();
				});
				return promise;
			},
			setBox: function (box) {
				var that = this;
				this.box = box;
				that.box.on('all', function (e) {
					console.log(e, arguments)
				});
				this.box.on('obj-add', function (id) {
					that.box.getObj(id).then(function (obj) {
						that.add(obj);
					});
				});
				this.box.on('obj-remove', function (id) {
					that.box.getObj(id).then(function (obj) {
						that.remove(obj);
					});
				});
				return this;
			}
		});

		return Objs;
	})
	.factory('FilterObjsFactory', function (ObjsFactory) {
		var FilterObjs = Backbone.Collection.extend({
			initialize: function (attributes, options) {
				this.objs = new ObjsFactory(attributes, options);
				this.objs.on('add', this.add, this);
				this.objs.on('remove', this.remove, this);
				this.objs.on('reset', function (objs) {
					this.reset(objs.models);
				}, this);
				this._textFilter = '';
			},
			fetch: function () {
				return this.objs.fetch();
			},
			setBox: function (box) {
				this.objs.setBox(box);
				return this;
			},
			textFilter: function (str) {
				this._textFilter = str.toLocaleLowerCase();
				this.reset(this.objs.select(this.objPassFilter, this));
			},
			add: function (obj) {
				if (_.isArray(obj)) {
					_.each(obj, this.add, this);
				} else {
					if (this.objPassFilter(obj)) {
						Backbone.Collection.prototype.add.apply(this, arguments);
					}
				}
				return this;
			},
			objPassFilter: function (obj) {
				if (!obj) { return false; }
				return obj.id.toLocaleLowerCase().indexOf(this._textFilter) > -1;
			}
		});

		return FilterObjs;
	})
	.controller('root', function ($scope, client, utils, FilterObjsFactory) {
		'use strict';

		var box,
			u = utils,
			objs = new FilterObjsFactory();

		$scope.objs = objs;

		objs.on('add remove reset', function () {
			$update();
		});

		$scope.$watch('s.textFilter', function () {
			objs.textFilter($scope.s.textFilter);
		});

		$scope.$watch('selectedBox + selectedUser', function () {
			delete $scope.msg;
			if (!$scope.selectedUser) {
				$scope.msg = 'Please log in.';
			} else if (!$scope.selectedBox) {
				$scope.msg = 'Please select a box.';
			} else {
				client.store.getBox($scope.selectedBox)
					.then(function (box) { init(box); })
					.fail(function (e) { u.error('error ', e); $scope.msg = 'An error occured.'; });
			}

		});

		var init = function (box) {
			window.box = box;
			window.objs = objs;
			objs.setBox(box).fetch();
		};
		var $update = function () {
			u.safeApply($scope);
		};
		$scope.s = {
			page: 0,
			orderBy: 'id',
			orderReverse: false,
			perPage: 15,
			textFilter: ''
		}; // state
		$scope.Math = window.Math;

	}).filter('startFrom', function() {
		return function (input, start) {
			start = +start; //parse to int
			return input.slice(start);
		}
	});
<commit_msg>box in path<commit_after>/* global angular, console, _, Backbone, $ */
angular
	.module('boxie', ['ui', 'indx'])
	.factory('ObjsFactory', function () {
		var Objs = Backbone.Collection.extend({
			initialize: function (attributes, options) {
				if (options && options.box) { this.setBox(options.box); }
			},
			fetch: function () {
				var that = this,
					promise = $.Deferred(),
					ids = this.box.getObjIDs();
				that.box.getObj(ids).then(function (objs) {
					that.reset(objs);
					promise.resolve();
				});
				return promise;
			},
			setBox: function (box) {
				var that = this;
				this.box = box;
				that.box.on('all', function (e) {
					console.log(e, arguments)
				});
				this.box.on('obj-add', function (id) {
					that.box.getObj(id).then(function (obj) {
						that.add(obj);
					});
				});
				this.box.on('obj-remove', function (id) {
					that.box.getObj(id).then(function (obj) {
						that.remove(obj);
					});
				});
				return this;
			}
		});

		return Objs;
	})
	.factory('FilterObjsFactory', function (ObjsFactory) {
		var FilterObjs = Backbone.Collection.extend({
			initialize: function (attributes, options) {
				this.objs = new ObjsFactory(attributes, options);
				this.objs.on('add', this.add, this);
				this.objs.on('remove', this.remove, this);
				this.objs.on('reset', function (objs) {
					this.reset(objs.models);
				}, this);
				this._textFilter = '';
			},
			fetch: function () {
				return this.objs.fetch();
			},
			setBox: function (box) {
				this.objs.setBox(box);
				return this;
			},
			textFilter: function (str) {
				this._textFilter = str.toLocaleLowerCase();
				this.reset(this.objs.select(this.objPassFilter, this));
			},
			add: function (obj) {
				if (_.isArray(obj)) {
					_.each(obj, this.add, this);
				} else {
					if (this.objPassFilter(obj)) {
						Backbone.Collection.prototype.add.apply(this, arguments);
					}
				}
				return this;
			},
			objPassFilter: function (obj) {
				if (!obj) { return false; }
				return obj.id.toLocaleLowerCase().indexOf(this._textFilter) > -1;
			}
		});

		return FilterObjs;
	})
	.controller('root', function ($scope, $location, client, utils, FilterObjsFactory) {
		'use strict';

		//$location.html5Mode(false);

		$scope.$watch(function() {
			return $location.path();
		}, function (path) {
			$scope.selectedBox = path.split('/')[1];
		});

		var box,
			u = utils,
			objs = new FilterObjsFactory();

		$scope.objs = objs;

		objs.on('add remove reset', function () {
			$update();
		});

		$scope.$watch('s.textFilter', function () {
			objs.textFilter($scope.s.textFilter);
		});

		$scope.$watch('selectedBox + selectedUser', function () {
			delete $scope.msg;
			if (!$scope.selectedUser) {
				$scope.msg = 'Please log in.';
			} else if (!$scope.selectedBox) {
				$scope.msg = 'Please select a box.';
			} else {
				$location.path($scope.selectedBox);
				client.store.getBox($scope.selectedBox)
					.then(function (box) { init(box); })
					.fail(function (e) { u.error('error ', e); $scope.msg = 'An error occured.'; });
			}

		});

		var init = function (box) {
			window.box = box;
			window.objs = objs;
			objs.setBox(box).fetch();
		};
		var $update = function () {
			u.safeApply($scope);
		};
		$scope.s = {
			page: 0,
			orderBy: 'id',
			orderReverse: false,
			perPage: 15,
			textFilter: ''
		}; // state
		$scope.Math = window.Math;

	}).filter('startFrom', function() {
		return function (input, start) {
			start = +start; //parse to int
			return input.slice(start);
		}
	});
<|endoftext|>


<commit_before>describe('Inverted Index Tests: ', function() {

  var index = new Index();
  var results;

  beforeEach(function(done) {
    index.createIndex('books.json', index.populateIndex).done(function(data) {
      results = data;

      // Invoke jasmine's done callback
      done();
    });
  });

  describe('Reads book data', function() {

    it('reads the JSON file successfully', function() {
      expect(results).not.toBeUndefined();
      expect(results.length).not.toEqual(0);
      expect(results.length).toEqual(2);
    })
  });

  describe('Populates Index', function() {

    it('creates the index once JSON file has been read', function() {
      expect(index.results).not.toEqual({});
    })
  });
});
<commit_msg>Add extra tests to verify index is correct<commit_after>describe('Inverted Index Tests: ', function() {

  var index = new Index();
  var filter = new Filter();
  var results;

  beforeEach(function(done) {
    index.createIndex('books.json', index.populateIndex).done(function(data) {
      results = data;

      // Invoke jasmine's done callback
      done();
    });
  });

  describe('Reads book data', function() {

    it('reads the JSON file successfully', function() {
      expect(results).not.toBeUndefined();
      expect(results.length).not.toEqual(0);
      expect(results.length).toEqual(2);
    });
  });

  describe('Populates Index', function() {

    it('creates the index once JSON file has been read', function() {
      expect(index.results).not.toEqual({});
    });

    it('creates an index containing only lowercase terms', function() {
      var keys = Object.keys(index.results);
      for (var i = 0, len = keys.length; i < len; i++) {
        expect(keys[i]).toBe(keys[i].toLowerCase());
      }
    });

    it('creates index strings without punctuation', function() {
      var keys = Object.keys(index.results);
      for (var i = 0, len = keys.length; i < len; i++) {
        expect(keys[i].indexOf('.')).toBe(-1);
        expect(keys[i].indexOf(',')).toBe(-1);
      }
    });

    it('creates index strings without stop words', function() {
      var keys = Object.keys(index.results);
      for (var i = 0, len = keys.length; i < len; i++) {
        expect(filter.stopWords.indexOf(keys[i])).toBe(-1);
      }
    });
  });
});
<|endoftext|>


<commit_before>appshell = {}

$(document).ready(function(){

    $('.dropdown-select').click(function(e) {
        if (!$(e.target).hasClass("custom-select-item")){
            e.stopPropagation();
        }
    }) ;

    $('.custom-select-item').click(function(e){
        var tgt = $(e.currentTarget);
        var cont = tgt.parents('.custom-select-container');
        var name = cont.data('custom-select-name');

        var value = tgt.data('value')
        var text = tgt.data('text')
        if (!text){
            text = tgt.text()
        }

        $("#"+name+"-text").text(text);
        $("#"+name).val(value)

        tgt.parents('.modal').modal('hide');
    });

    appshell.datatables = {}

    $('.tablefilter').on('keyup change', function (e){
        var tgt = $(e.currentTarget);
        var id = tgt.data('tablefilter-target');
        var t = appshell.datatables[id];

        var column = tgt.data('tablefilter-column');
        var value = tgt.val()

        if (t.column(column).search() != value){
            t.column(column).search(value).draw();
        }
    })

    $('.tablefilter-range').each(function(i, elem){
        var eq =$(elem);
        var id = eq.data('tablefilter-target');
        var column = eq.data('tablefilter-column');
        function update(e){
            var t = appshell.datatables[id];
            var value = eq.find('.range-from').val() + ';' + eq.find('.range-to').val();
            if (t.column(column).search() != value){
                t.column(column).search(value).draw();
            }
        }
        eq.find('.range-from').on('keyup change', update);
        eq.find('.range-to').on('keyup change', update);
    });

    $('.checklist').each(function(i, e){
        var name = $(e).data('custom-select-name');
        function value_from_checks(){
            var value = ""
            var text = ""

            $(e).find('input[type="checkbox"]').each(function(i, c){
                if ($(c).prop('checked')){
                    value += $(c).val()+";";
                    if (text == ""){
                        text = $(c).parent().text();
                    } else {
                        text = "[..., ...]"
                    }
                }
            });

            $("#"+name+"-text").text(text);
            $("#"+name).val(value)
            $("#"+name).trigger('change');
        }
        function checks_from_value(){

        }
        console.log(e);
        $(e).find('input[type="checkbox"]').on("change", function f(){
            value_from_checks();
        });
    });

    $('.checktree').each(function(i, e){
        var name = $(e).data('custom-select-name');
        var changing = false;
        var tree = $(e);
        function value_from_checks(){
            var value = ""
            var text = ""
            $(e).find('input[type="checkbox"]').each(function(i, c){
                if ($(c).prop('checked')){
                    value += $(c).val()+";";
                    if (text == ""){
                        text = $(c).val();
                    } else {
                        text = "[..., ...]"
                    }
                }
            });

            $("#"+name+"-text").text(text);
            $("#"+name).val(value)
            $("#"+name).trigger('change');
        }
        function checks_from_value(){

        }
        $(e).find('input[type="checkbox"]').on("change", function f(e){
            var self = $(e.currentTarget);
            if (changing == false){
                changing = true;

                var checked = self.prop('checked');
                var myval = self.val()
                var desc = tree.find('input[type="checkbox"][value^="'+myval+'/"]')
                console.log(desc)
                desc.prop('checked', checked);
                console.log(checked);
                if (!checked){
                    var path = myval.split('/');
                    var i;
                    var s = path[0];
                    for (i = 1; i < (path.length); i++){
                        console.log(s)
                        tree.find("input[type='checkbox'][value='"+s+"']").prop('checked', false);
                        s = s + '/' + path[i];
                    }
                }

                changing = false;
                value_from_checks();
            }
        });

    });

    $('.datatable-action').click(function(e){
        var tgt = $(e.currentTarget);
        var id = tgt.data('target');
        var action = tgt.data('action');
        var t = appshell.datatables[id];
        var url = t.ajax.url()
        var paramstring = $.param(t.ajax.params());

        window.location = (url +
                           ((url.indexOf('?') == -1) ? '?' : '&') +
                           'action=' + action +
                           '&' + paramstring);
    });
});

(function(){
    var timeout;
    $(document).ajaxStart(function(){
        timeout = setTimeout("$('.appshell-spinner').show()", 200);
    });
    $(document).ajaxStop(function(){
        if (timeout){
            clearTimeout(timeout);
        }
        timeout = null;
        $('#appshell-ajax-spinner').hide();
    });
})()

<commit_msg>enable sorting of filesizes<commit_after>appshell = {}

$(document).ready(function(){

    $('.dropdown-select').click(function(e) {
        if (!$(e.target).hasClass("custom-select-item")){
            e.stopPropagation();
        }
    }) ;

    $('.custom-select-item').click(function(e){
        var tgt = $(e.currentTarget);
        var cont = tgt.parents('.custom-select-container');
        var name = cont.data('custom-select-name');

        var value = tgt.data('value')
        var text = tgt.data('text')
        if (!text){
            text = tgt.text()
        }

        $("#"+name+"-text").text(text);
        $("#"+name).val(value)

        tgt.parents('.modal').modal('hide');
    });

    appshell.datatables = {}

    $('.tablefilter').on('keyup change', function (e){
        var tgt = $(e.currentTarget);
        var id = tgt.data('tablefilter-target');
        var t = appshell.datatables[id];

        var column = tgt.data('tablefilter-column');
        var value = tgt.val()

        if (t.column(column).search() != value){
            t.column(column).search(value).draw();
        }
    })

    $('.tablefilter-range').each(function(i, elem){
        var eq =$(elem);
        var id = eq.data('tablefilter-target');
        var column = eq.data('tablefilter-column');
        function update(e){
            var t = appshell.datatables[id];
            var value = eq.find('.range-from').val() + ';' + eq.find('.range-to').val();
            if (t.column(column).search() != value){
                t.column(column).search(value).draw();
            }
        }
        eq.find('.range-from').on('keyup change', update);
        eq.find('.range-to').on('keyup change', update);
    });

    $('.checklist').each(function(i, e){
        var name = $(e).data('custom-select-name');
        function value_from_checks(){
            var value = ""
            var text = ""

            $(e).find('input[type="checkbox"]').each(function(i, c){
                if ($(c).prop('checked')){
                    value += $(c).val()+";";
                    if (text == ""){
                        text = $(c).parent().text();
                    } else {
                        text = "[..., ...]"
                    }
                }
            });

            $("#"+name+"-text").text(text);
            $("#"+name).val(value)
            $("#"+name).trigger('change');
        }
        function checks_from_value(){

        }
        console.log(e);
        $(e).find('input[type="checkbox"]').on("change", function f(){
            value_from_checks();
        });
    });

    $('.checktree').each(function(i, e){
        var name = $(e).data('custom-select-name');
        var changing = false;
        var tree = $(e);
        function value_from_checks(){
            var value = ""
            var text = ""
            $(e).find('input[type="checkbox"]').each(function(i, c){
                if ($(c).prop('checked')){
                    value += $(c).val()+";";
                    if (text == ""){
                        text = $(c).val();
                    } else {
                        text = "[..., ...]"
                    }
                }
            });

            $("#"+name+"-text").text(text);
            $("#"+name).val(value)
            $("#"+name).trigger('change');
        }
        function checks_from_value(){

        }
        $(e).find('input[type="checkbox"]').on("change", function f(e){
            var self = $(e.currentTarget);
            if (changing == false){
                changing = true;

                var checked = self.prop('checked');
                var myval = self.val()
                var desc = tree.find('input[type="checkbox"][value^="'+myval+'/"]')
                console.log(desc)
                desc.prop('checked', checked);
                console.log(checked);
                if (!checked){
                    var path = myval.split('/');
                    var i;
                    var s = path[0];
                    for (i = 1; i < (path.length); i++){
                        console.log(s)
                        tree.find("input[type='checkbox'][value='"+s+"']").prop('checked', false);
                        s = s + '/' + path[i];
                    }
                }

                changing = false;
                value_from_checks();
            }
        });

    });

    $('.datatable-action').click(function(e){
        var tgt = $(e.currentTarget);
        var id = tgt.data('target');
        var action = tgt.data('action');
        var t = appshell.datatables[id];
        var url = t.ajax.url()
        var paramstring = $.param(t.ajax.params());

        window.location = (url +
                           ((url.indexOf('?') == -1) ? '?' : '&') +
                           'action=' + action +
                           '&' + paramstring);
    });
});

(function(){
    var timeout;
    $(document).ajaxStart(function(){
        timeout = setTimeout("$('.appshell-spinner').show()", 200);
    });
    $(document).ajaxStop(function(){
        if (timeout){
            clearTimeout(timeout);
        }
        timeout = null;
        $('#appshell-ajax-spinner').hide();
    });
})()

/* file-size plugin */
jQuery.fn.dataTable.ext.type.detect.unshift( function ( data ) {
    if ( typeof data !== 'string' ) {
        return null;
    }

    var units = data.replace( /[\d\.]/g, '' ).toLowerCase();
    if ( units !== '' && units !== 'b' && units !== 'kb' && units !== 'mb' && units !== 'gb' ) {
        return null;
    }

    return isNaN( parseFloat( data ) ) ?
        null :
        'file-size';
} );
jQuery.fn.dataTable.ext.type.order['file-size-pre'] = function ( data ) {
    var units = data.replace( /[\d\.]/g, '' ).toLowerCase();
    var multiplier = 1;

    if ( units === 'kb' ) {
        multiplier = 1000;
    }
    else if ( units === 'mb' ) {
        multiplier = 1000000;
    }
    else if ( units === 'gb' ) {
        multiplier = 1000000000;
    }

    return parseFloat( data ) * multiplier;
};
<|endoftext|>


<commit_before>var Service = require("HAP-NodeJS").Service;
var Characteristic = require("HAP-NodeJS").Characteristic;
var wemo = require('wemo');

module.exports = {
  accessory: WeMoAccessory
}

function WeMoAccessory(log, config) {
  this.log = log;
  this.name = config["name"];
  this.service = config["service"] || "Switch";
  this.wemoName = config["wemo_name"] || this.name; // fallback to "name" if you didn't specify an exact "wemo_name"
  this.device = null; // instance of WeMo, for controlling the discovered device
  this.log("Searching for WeMo device with exact name '" + this.wemoName + "'...");
  this.search();
}

WeMoAccessory.prototype.search = function() {
  wemo.Search(this.wemoName, function(err, device) {
    if (!err && device) {
      this.log("Found '"+this.wemoName+"' device at " + device.ip);
      this.device = new wemo(device.ip, device.port);
    }
    else {
      this.log("Error finding device '" + this.wemoName + "': " + err);
      this.log("Continuing search for WeMo device with exact name '" + this.wemoName + "'...");
      this.search();
    }
  }.bind(this));
}

WeMoAccessory.prototype.getMotion = function(callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"), false);
    return;
  }

  this.log("Getting motion state on the '%s'...", this.wemoName);

  this.device.getBinaryState(function(err, result) {
    if (!err) {
      var binaryState = parseInt(result);
      var powerOn = binaryState > 0;
      this.log("Motion state for the '%s' is %s", this.wemoName, binaryState);
      callback(null, powerOn);
    }
    else {
      this.log("Error getting motion state on the '%s': %s", this.wemoName, err.message);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.getPowerOn = function(callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"), false);
    return;
  }

  this.log("Getting power state on the '%s'...", this.wemoName);

  this.device.getBinaryState(function(err, result) {
    if (!err) {
      var binaryState = parseInt(result);
      var powerOn = binaryState > 0;
      this.log("Power state for the '%s' is %s", this.wemoName, binaryState);
      callback(null, powerOn);
    }
    else {
      this.log("Error getting power state on the '%s': %s", this.wemoName, err.message);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.setPowerOn = function(powerOn, callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"));
    return;
  }

  var binaryState = powerOn ? 1 : 0; // wemo langauge
  this.log("Setting power state on the '%s' to %s", this.wemoName, binaryState);

  this.device.setBinaryState(binaryState, function(err, result) {
    if (!err) {
      this.log("Successfully set power state on the '%s' to %s", this.wemoName, binaryState);
      callback(null);
    }
    else {
      this.log("Error setting power state to %s on the '%s'", binaryState, this.wemoName);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.setTargetDoorState = function(targetDoorState, callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"));
    return;
  }

  this.log("Activating WeMo switch '%s'", this.wemoName);

  this.device.setBinaryState(1, function(err, result) {
    if (!err) {
      this.log("Successfully activated WeMo switch '%s'", this.wemoName);
      callback(null);
    }
    else {
      this.log("Error activating WeMo switch '%s'", this.wemoName);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.getServices = function() {

  if (this.service == "Switch") {
    var switchService = new Service.Switch(this.name);

    switchService
      .getCharacteristic(Characteristic.On)
      .on('get', this.getPowerOn.bind(this))
      .on('set', this.setPowerOn.bind(this));

    return [switchService];
  }
  else if (this.service == "GarageDoor") {
    var garageDoorService = new Service.GarageDoorOpener("Garage Door Opener");

    garageDoorService
      .getCharacteristic(Characteristic.TargetDoorState)
      .on('set', this.setTargetDoorState.bind(this))
      .supportsEventNotification = false;

    return [garageDoorService];
  }
  else if (this.service == "MotionSensor") {
    var motionSensorService = new Service.MotionSensor(this.name);

    motionSensorService
      .getCharacteristic(Characteristic.MotionDetected)
      .on('get', this.getMotion.bind(this));

    return [motionSensorService];
  }
  else {
    throw new Error("Unknown service type '%s'", this.service);
  }
}
<commit_msg>Remove test code from WeMo<commit_after>var Service = require("HAP-NodeJS").Service;
var Characteristic = require("HAP-NodeJS").Characteristic;
var wemo = require('wemo');

module.exports = {
  accessory: WeMoAccessory
}

function WeMoAccessory(log, config) {
  this.log = log;
  this.name = config["name"];
  this.service = config["service"] || "Switch";
  this.wemoName = config["wemo_name"] || this.name; // fallback to "name" if you didn't specify an exact "wemo_name"
  this.device = null; // instance of WeMo, for controlling the discovered device
  this.log("Searching for WeMo device with exact name '" + this.wemoName + "'...");
  this.search();
}

WeMoAccessory.prototype.search = function() {
  wemo.Search(this.wemoName, function(err, device) {
    if (!err && device) {
      this.log("Found '"+this.wemoName+"' device at " + device.ip);
      this.device = new wemo(device.ip, device.port);
    }
    else {
      this.log("Error finding device '" + this.wemoName + "': " + err);
      this.log("Continuing search for WeMo device with exact name '" + this.wemoName + "'...");
      this.search();
    }
  }.bind(this));
}

WeMoAccessory.prototype.getMotion = function(callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"), false);
    return;
  }

  this.log("Getting motion state on the '%s'...", this.wemoName);

  this.device.getBinaryState(function(err, result) {
    if (!err) {
      var binaryState = parseInt(result);
      var powerOn = binaryState > 0;
      this.log("Motion state for the '%s' is %s", this.wemoName, binaryState);
      callback(null, powerOn);
    }
    else {
      this.log("Error getting motion state on the '%s': %s", this.wemoName, err.message);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.getPowerOn = function(callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"), false);
    return;
  }

  this.log("Getting power state on the '%s'...", this.wemoName);

  this.device.getBinaryState(function(err, result) {
    if (!err) {
      var binaryState = parseInt(result);
      var powerOn = binaryState > 0;
      this.log("Power state for the '%s' is %s", this.wemoName, binaryState);
      callback(null, powerOn);
    }
    else {
      this.log("Error getting power state on the '%s': %s", this.wemoName, err.message);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.setPowerOn = function(powerOn, callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"));
    return;
  }

  var binaryState = powerOn ? 1 : 0; // wemo langauge
  this.log("Setting power state on the '%s' to %s", this.wemoName, binaryState);

  this.device.setBinaryState(binaryState, function(err, result) {
    if (!err) {
      this.log("Successfully set power state on the '%s' to %s", this.wemoName, binaryState);
      callback(null);
    }
    else {
      this.log("Error setting power state to %s on the '%s'", binaryState, this.wemoName);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.setTargetDoorState = function(targetDoorState, callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"));
    return;
  }

  this.log("Activating WeMo switch '%s'", this.wemoName);

  this.device.setBinaryState(1, function(err, result) {
    if (!err) {
      this.log("Successfully activated WeMo switch '%s'", this.wemoName);
      callback(null);
    }
    else {
      this.log("Error activating WeMo switch '%s'", this.wemoName);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.getServices = function() {

  if (this.service == "Switch") {
    var switchService = new Service.Switch(this.name);

    switchService
      .getCharacteristic(Characteristic.On)
      .on('get', this.getPowerOn.bind(this))
      .on('set', this.setPowerOn.bind(this));

    return [switchService];
  }
  else if (this.service == "GarageDoor") {
    var garageDoorService = new Service.GarageDoorOpener("Garage Door Opener");

    garageDoorService
      .getCharacteristic(Characteristic.TargetDoorState)
      .on('set', this.setTargetDoorState.bind(this));

    return [garageDoorService];
  }
  else if (this.service == "MotionSensor") {
    var motionSensorService = new Service.MotionSensor(this.name);

    motionSensorService
      .getCharacteristic(Characteristic.MotionDetected)
      .on('get', this.getMotion.bind(this));

    return [motionSensorService];
  }
  else {
    throw new Error("Unknown service type '%s'", this.service);
  }
}
<|endoftext|>


<commit_before>/*
  standalone-proxy.js: Example of proxying over HTTP with a standalone HTTP server.

  Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var util = require('util'),
    colors = require('colors'),
    http = require('http'),
    httpProxy = require('../../lib/http-proxy');

//
// Http Server with proxyRequest Handler and Latency
//
var proxy = new httpProxy.createProxyServer();
http.createServer(function (req, res) {
  setTimeout(function () {
    proxy.web(req, res, {
      target: 'http://localhost:9002'
    });
  }, 200);
}).listen(8002);

//
// Target Http Server
//
http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9002);

util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with proxy.web() handler'.cyan.underline + ' and latency'.magenta);
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9001 '.yellow);
<commit_msg>alter message error (#998)<commit_after>/*
  standalone-proxy.js: Example of proxying over HTTP with a standalone HTTP server.

  Copyright (c) 2013 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var util = require('util'),
    colors = require('colors'),
    http = require('http'),
    httpProxy = require('../../lib/http-proxy');

//
// Http Server with proxyRequest Handler and Latency
//
var proxy = new httpProxy.createProxyServer();
http.createServer(function (req, res) {
  setTimeout(function () {
    proxy.web(req, res, {
      target: 'http://localhost:9002'
    });
  }, 200);
}).listen(8002);

//
// Target Http Server
//
http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9002);

util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with proxy.web() handler'.cyan.underline + ' and latency'.magenta);
util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9002 '.yellow);
<|endoftext|>


<commit_before>
export const questionData = [
  { question: '我和警察發生推擠。', score: 'a', done: false },
  { question: '警察罵我，我罵回去。', score: 'b', done: false },
  { question: '警察抓我的時候我掙扎抗拒。', score: 'c', done: false },
  { question: '我和大家一起罵政府機關。', score: 'd', done: false },
  { question: '我和大家一起罵政府機關的官員。', score: 'e', done: false },
  { question: '我拿著麥克風，對大家宣講。', score: 'f', done: false },
  { question: '我拿著麥克風，協助控制場面。', score: 'g', done: false },
  { question: '我和大家一起衝進政府機關。', score: 'h', done: false },
  { question: '我和大家圍著政府機關靜坐抗議。', score: 'i', done: false },
  { question: '我不小心破壞了政府機關的財物。', score: 'j', done: false },
  { question: '我在臉書上發文，請大家到現場幫忙。', score: 'k', done: false },
  { question: '警察舉牌三次後，群眾不想離開。', score: 'l', done: false },
  { question: '政府官員要離開，我擋在車子前面阻擋。', score: 'm', done: false },
  { question: '我把自己綁在路中間，希望官員的車子能在前面停下來。', score: 'n', done: false },
  { question: '建築物即將被強制拆除，我待在建築物內部，要阻止建築物被拆掉。', score: 'o', done: false }
];

export const answerData = [
  {
    answer: '刑法§135條，妨礙公務罪。',
    detail: '對於公務員依法執行職務時，施強暴脅迫者，處三年以下有期徒刑、拘役或三百元以下罰金。\n意圖使公務員執行一定之職務或妨害其依法執行一定之職務或使公務員辭職，而施強暴脅迫者，亦同。\n犯前二項之罪，因而致公務員於死者，處無期徒刑或七年以上有期徒刑；致重傷者，處三年以上、十年以下有期徒刑。',
    calculate: (state) => { return ( state.a || state.b || state.c || state.o ) ? true : false; },
    key: 'criminal135'
  }, {
    answer: '刑法§136條，聚眾妨礙公務罪。',
    detail: '公然聚眾犯前條之罪者，在場助勢之人，處一年以下有期徒刑、拘役或三百元以下罰金。首謀及下手實施強暴脅迫者，處一年以上、七年以下有期徒刑。',
    calculate: (state) => { return (( state.a || state.b || state.c || state.o ) && ( state.f || state.g )) ? true : false; },
    key: 'criminal136'
  }, {
    answer: '刑法§140條侮辱公務人員、侮辱公署罪',
    detail: '於公務員依法執行職務時，當場侮辱，或對於其依法執行之職務公然侮辱者，處六月以下有期徒刑、拘役或一百元以下罰金。
對於公署公然侮辱者亦同。',
    calculate: (state) => { return ( state.b || state.d || state.e ) ? true : false; },
    key: 'criminal140'
  }, {
    answer: '刑法§153煽惑他人犯罪',
    detail: '以文字、圖畫、演說或他法，公然為左列行為之一者，處二年以下有期徒刑、拘役或一千元以下罰金：
一、煽惑他人犯罪者。
二、煽惑他人違背法令，或抗拒合法之命令者。',
    calculate: (state) => { return ( state.f || state.g || state.k ) ? true : false; },
    key: 'criminal153'
  }, {
    answer: '刑法§306侵入建物罪',
    detail: '無故侵入他人住宅、建築物或附連圍繞之土地或船艦者，處一年以下有期徒刑、拘役或三百元以下罰金。
無故隱匿其內，或受退去之要求而仍留滯者，亦同。',
    calculate: (state) => { return ( state.h || state.i ) ? true : false; },
    key: 'criminal306'
  }, {
    answer: '刑法§354損毀罪',
    detail: '毀棄、損壞前二條以外之他人之物或致令不堪用，足以生損害於公眾或他人者，處二年以下有期徒刑、拘役或五百元以下罰金。',
    calculate: (state) => { return ( state.j ) ? true : false; },
    key: 'criminal354'
  }, {
    answer: '集遊法§29集會遊行不解散之首謀',
    detail: '集會、遊行經該管主管機關命令解散而不解散，仍繼續舉行經制止而不遵從，首謀者處二年以下有期徒刑或拘役。',
    calculate: (state) => { return (( state.f || state.g ) && state.l ) ? true : false; },
    key: 'assembly29'
  }, {
    answer: '集遊法§30集會遊行侮辱公署罪',
    detail: '集會﹑遊行時，以文字﹑圖畫﹑演說或他法，侮辱﹑誹謗公署﹑依法執行職務之公務員或他人者，處二年以下有期徒刑﹑拘役或科或併科新台幣六萬元以下罰金。',
    calculate: (state) => { return (( state.d || state.e ) && ( state.f || state.g )) ? true : false; },
    key: 'assembly30'
  }, {
    answer: '刑法§304強制罪',
    detail: '以強暴、脅迫使人行無義務之事或妨害人行使權利者，處三年以下有期徒刑、拘役或三百元以下罰金。
前項之未遂犯罰之。',
    calculate: (state) => { return ( state.m || state.n ) ? true : false; },
    key: 'criminal304'
  }, {
    answer: '刑法§185妨害公眾往來安全罪',
    detail: '損壞或壅塞陸路、水路、橋樑或其他公眾往來之設備或以他法致生往來之危險者，處五年以下有期徒刑，拘役或五百元以下罰金。
因而致人於死者，處無期徒刑或七年以上有期徒刑。致重傷者，處三年以上十年以下有期徒刑。
第一項之未遂犯罰之。',
    calculate: (state) => { return ( state.n ) ? true : false; },
    key: 'criminal185'
  }
];

export const defaultScore = {
  a: false,
  b: false,
  c: false,
  d: false,
  e: false,
  f: false,
  g: false,
  h: false,
  i: false,
  j: false,
  k: false,
  l: false,
  m: false,
  n: false,
  o: false
};

<commit_msg>add more br for better reading<commit_after>
export const questionData = [
  { question: '我和警察發生推擠。', score: 'a', done: false },
  { question: '警察罵我，我罵回去。', score: 'b', done: false },
  { question: '警察抓我的時候我掙扎抗拒。', score: 'c', done: false },
  { question: '我和大家一起罵政府機關。', score: 'd', done: false },
  { question: '我和大家一起罵政府機關的官員。', score: 'e', done: false },
  { question: '我拿著麥克風，對大家宣講。', score: 'f', done: false },
  { question: '我拿著麥克風，協助控制場面。', score: 'g', done: false },
  { question: '我和大家一起衝進政府機關。', score: 'h', done: false },
  { question: '我和大家圍著政府機關靜坐抗議。', score: 'i', done: false },
  { question: '我不小心破壞了政府機關的財物。', score: 'j', done: false },
  { question: '我在臉書上發文，請大家到現場幫忙。', score: 'k', done: false },
  { question: '警察舉牌三次後，群眾不想離開。', score: 'l', done: false },
  { question: '政府官員要離開，我擋在車子前面阻擋。', score: 'm', done: false },
  { question: '我把自己綁在路中間，希望官員的車子能在前面停下來。', score: 'n', done: false },
  { question: '建築物即將被強制拆除，我待在建築物內部，要阻止建築物被拆掉。', score: 'o', done: false }
];

export const answerData = [
  {
    answer: '刑法§135條，妨礙公務罪。',
    detail: '對於公務員依法執行職務時，施強暴脅迫者，處三年以下有期徒刑、拘役或三百元以下罰金。

意圖使公務員執行一定之職務或妨害其依法執行一定之職務或使公務員辭職，而施強暴脅迫者，亦同。

犯前二項之罪，因而致公務員於死者，處無期徒刑或七年以上有期徒刑；致重傷者，處三年以上、十年以下有期徒刑。',
    calculate: (state) => { return ( state.a || state.b || state.c || state.o ) ? true : false; },
    key: 'criminal135'
  }, {
    answer: '刑法§136條，聚眾妨礙公務罪。',
    detail: '公然聚眾犯前條之罪者，在場助勢之人，處一年以下有期徒刑、拘役或三百元以下罰金。首謀及下手實施強暴脅迫者，處一年以上、七年以下有期徒刑。',
    calculate: (state) => { return (( state.a || state.b || state.c || state.o ) && ( state.f || state.g )) ? true : false; },
    key: 'criminal136'
  }, {
    answer: '刑法§140條侮辱公務人員、侮辱公署罪',
    detail: '於公務員依法執行職務時，當場侮辱，或對於其依法執行之職務公然侮辱者，處六月以下有期徒刑、拘役或一百元以下罰金。

對於公署公然侮辱者亦同。',
    calculate: (state) => { return ( state.b || state.d || state.e ) ? true : false; },
    key: 'criminal140'
  }, {
    answer: '刑法§153煽惑他人犯罪',
    detail: '以文字、圖畫、演說或他法，公然為左列行為之一者，處二年以下有期徒刑、拘役或一千元以下罰金：

一、煽惑他人犯罪者。

二、煽惑他人違背法令，或抗拒合法之命令者。',
    calculate: (state) => { return ( state.f || state.g || state.k ) ? true : false; },
    key: 'criminal153'
  }, {
    answer: '刑法§306侵入建物罪',
    detail: '無故侵入他人住宅、建築物或附連圍繞之土地或船艦者，處一年以下有期徒刑、拘役或三百元以下罰金。

無故隱匿其內，或受退去之要求而仍留滯者，亦同。',
    calculate: (state) => { return ( state.h || state.i ) ? true : false; },
    key: 'criminal306'
  }, {
    answer: '刑法§354損毀罪',
    detail: '毀棄、損壞前二條以外之他人之物或致令不堪用，足以生損害於公眾或他人者，處二年以下有期徒刑、拘役或五百元以下罰金。',
    calculate: (state) => { return ( state.j ) ? true : false; },
    key: 'criminal354'
  }, {
    answer: '集遊法§29集會遊行不解散之首謀',
    detail: '集會、遊行經該管主管機關命令解散而不解散，仍繼續舉行經制止而不遵從，首謀者處二年以下有期徒刑或拘役。',
    calculate: (state) => { return (( state.f || state.g ) && state.l ) ? true : false; },
    key: 'assembly29'
  }, {
    answer: '集遊法§30集會遊行侮辱公署罪',
    detail: '集會﹑遊行時，以文字﹑圖畫﹑演說或他法，侮辱﹑誹謗公署﹑依法執行職務之公務員或他人者，處二年以下有期徒刑﹑拘役或科或併科新台幣六萬元以下罰金。',
    calculate: (state) => { return (( state.d || state.e ) && ( state.f || state.g )) ? true : false; },
    key: 'assembly30'
  }, {
    answer: '刑法§304強制罪',
    detail: '以強暴、脅迫使人行無義務之事或妨害人行使權利者，處三年以下有期徒刑、拘役或三百元以下罰金。

前項之未遂犯罰之。',
    calculate: (state) => { return ( state.m || state.n ) ? true : false; },
    key: 'criminal304'
  }, {
    answer: '刑法§185妨害公眾往來安全罪',
    detail: '損壞或壅塞陸路、水路、橋樑或其他公眾往來之設備或以他法致生往來之危險者，處五年以下有期徒刑，拘役或五百元以下罰金。

因而致人於死者，處無期徒刑或七年以上有期徒刑。致重傷者，處三年以上十年以下有期徒刑。

第一項之未遂犯罰之。',
    calculate: (state) => { return ( state.n ) ? true : false; },
    key: 'criminal185'
  }
];

export const defaultScore = {
  a: false,
  b: false,
  c: false,
  d: false,
  e: false,
  f: false,
  g: false,
  h: false,
  i: false,
  j: false,
  k: false,
  l: false,
  m: false,
  n: false,
  o: false
};

<|endoftext|>


<commit_before>const path = require('path');
const childProcess = require('child_process');
const fetch = require('node-fetch');
const log = require('../util/log');
const config = require('../config');
const remoteSSH = require('./remote-ssh');
const remoteCopy = require('./remote-copy');
const updateHAProxyConfig = require('./update-haproxy-config');
const createDroplet = require('../api/create-droplet');

module.exports = function (droplets) {
    log('Scaling up');

    let i = parseInt(Math.max.apply(null, droplets.map(droplet => droplet.name.replace('lamp', '')))) + 1;

    // create new lamp with API
    return createDroplet(i).then(id => {
        return fetch('https://api.digitalocean.com/v2/droplets/' + id, {
            headers: {
                'Authorization': `Bearer ${config.API_TOKEN}`
            }
        })
            .then(response => response.json())
            .then(json => json.droplet)
            .then(droplet => {
                console.log(droplet);
                let ip = droplet.networks.v4.find(network => network.type === 'public').ip_address;
                let options = {cwd: path.resolve(__dirname, '../stage/prime-calculator')};
                // add it's IP address to known_hosts file
                log(`Adding IP address ${ip} to known hosts`);
                childProcess.execSync(`ssh-keyscan -H ${ip} >> ~/.ssh/known_hosts`);
                log(`Copying new sources to ${droplet.name}`);
                remoteCopy('./www/*', '/var/www/html/.', ip, options);
                remoteCopy('./api/', '/var/www/html/.', ip, options);

                let lamps = droplets.map(droplet => {
                    return {
                        name: droplet.name,
                        ip: droplet.networks.v4.find(network => network.type === 'public').ip_address
                    }
                });

                // add new born
                lamps.push(droplet);

                log('Updating haproxy');
                updateHAProxyConfig(lamps);

                options = {cwd: path.resolve(__dirname, '../stage/')};
                remoteCopy('./haproxy.cfg', '/etc/haproxy/haproxy.cfg', config.PROXY.IP, options);
                remoteSSH('service haproxy restart', config.PROXY.IP, options);
            });
    });
};
<commit_msg>outputting key add to known_hosts<commit_after>const path = require('path');
const childProcess = require('child_process');
const fetch = require('node-fetch');
const log = require('../util/log');
const config = require('../config');
const remoteSSH = require('./remote-ssh');
const remoteCopy = require('./remote-copy');
const updateHAProxyConfig = require('./update-haproxy-config');
const createDroplet = require('../api/create-droplet');

module.exports = function (droplets) {
    log('Scaling up');

    let i = parseInt(Math.max.apply(null, droplets.map(droplet => droplet.name.replace('lamp', '')))) + 1;

    // create new lamp with API
    return createDroplet(i).then(id => {
        return fetch('https://api.digitalocean.com/v2/droplets/' + id, {
            headers: {
                'Authorization': `Bearer ${config.API_TOKEN}`
            }
        })
            .then(response => response.json())
            .then(json => json.droplet)
            .then(droplet => {
                let ip = droplet.networks.v4.find(network => network.type === 'public').ip_address;
                let options = {cwd: path.resolve(__dirname, '../stage/prime-calculator')};
                // add it's IP address to known_hosts file
                log(`Adding IP address ${ip} to known hosts`);
                console.log(childProcess.execSync(`ssh-keyscan -H ${ip} >> ~/.ssh/known_hosts`));
                log(`Copying new sources to ${droplet.name}`);
                remoteCopy('./www/*', '/var/www/html/.', ip, options);
                remoteCopy('./api/', '/var/www/html/.', ip, options);

                let lamps = droplets.map(droplet => {
                    return {
                        name: droplet.name,
                        ip: droplet.networks.v4.find(network => network.type === 'public').ip_address
                    }
                });

                // add new born
                lamps.push(droplet);

                log('Updating haproxy');
                updateHAProxyConfig(lamps);

                options = {cwd: path.resolve(__dirname, '../stage/')};
                remoteCopy('./haproxy.cfg', '/etc/haproxy/haproxy.cfg', config.PROXY.IP, options);
                remoteSSH('service haproxy restart', config.PROXY.IP, options);
            });
    });
};
<|endoftext|>