<commit_before>var path = require('path');
var BPromise = require('bluebird');

var config = require('../config');
var logger = require('../logger');

var result =  {

  cache: {},

  file: function(res, response) {
    BPromise.delay(response.latency || 200).then(function() {

      var filePath = path.join(config.options.data, response.file);
      var status = response.status || 200;

      if(response.headers) {
        res.set(response.headers);
      }

      res.status(status).sendFile(filePath, function(err) {
        if(err) {
          logger.fileNotFound(filePath);
          res.sendStatus(404);
        } else {
          logger.fileFound(filePath, status);
        }
      });
    });
  },

  url: function(res, response) {
    console.log('url');
    console.log(response);

    res.redirect(response.url);
  },

  send: function(req, res) {
    var route = res.locals.route;
    var request = res.locals.request;

    var routeId = route.id;
    var requestId = request.id;
    // cache: {
    //  'route1_request2': 0
    // }
    var cacheKey = routeId + '_' + requestId;

    var index = result.cache[cacheKey];
    var innerIndex = 0;
    if(index === undefined || index === null) {
      // nothing cached so set the index to 0 to return the first response configuration
      index = result.cache[cacheKey] = 0;
    }else {
      for(var i = 0; i < request.responses.length; i++) {
        if(request.responses[i].repeat && request.responses[i].repeat > 1) {
          innerIndex += request.responses[i].repeat;
        }else {
          innerIndex++;
        }
      }

      // increment the response index in a circular fashion
      index = (index + 1) % innerIndex;
    }
    // cache the latest index
    result.cache[cacheKey] = index;
    // return the appropriate response object
    var response;
    innerIndex = 0;
    for(var j = 0; j < request.responses.length; j++) {
      if(request.responses[j].repeat && request.responses[j].repeat > 1) {
        innerIndex += request.responses[j].repeat;
      }else {
        innerIndex++;
      }

      if(index < innerIndex) {
        response = request.responses[j];
        break;
      }
    }

    if(response.file) {
      this.file(res, response);
      return;
    }

    this.url(res, response);

  }
};

module.exports = result;
<commit_msg>remove console log<commit_after>var path = require('path');
var BPromise = require('bluebird');

var config = require('../config');
var logger = require('../logger');

var result =  {

  cache: {},

  file: function(res, response) {
    BPromise.delay(response.latency || 200).then(function() {

      var filePath = path.join(config.options.data, response.file);
      var status = response.status || 200;

      if(response.headers) {
        res.set(response.headers);
      }

      res.status(status).sendFile(filePath, function(err) {
        if(err) {
          logger.fileNotFound(filePath);
          res.sendStatus(404);
        } else {
          logger.fileFound(filePath, status);
        }
      });
    });
  },

  url: function(res, response) {
    res.redirect(response.url);
  },

  send: function(req, res) {
    var route = res.locals.route;
    var request = res.locals.request;

    var routeId = route.id;
    var requestId = request.id;
    // cache: {
    //  'route1_request2': 0
    // }
    var cacheKey = routeId + '_' + requestId;

    var index = result.cache[cacheKey];
    var innerIndex = 0;
    if(index === undefined || index === null) {
      // nothing cached so set the index to 0 to return the first response configuration
      index = result.cache[cacheKey] = 0;
    }else {
      for(var i = 0; i < request.responses.length; i++) {
        if(request.responses[i].repeat && request.responses[i].repeat > 1) {
          innerIndex += request.responses[i].repeat;
        }else {
          innerIndex++;
        }
      }

      // increment the response index in a circular fashion
      index = (index + 1) % innerIndex;
    }
    // cache the latest index
    result.cache[cacheKey] = index;

    // return the appropriate response object
    var response;
    innerIndex = 0;
    for(var j = 0; j < request.responses.length; j++) {
      if(request.responses[j].repeat && request.responses[j].repeat > 1) {
        innerIndex += request.responses[j].repeat;
      }else {
        innerIndex++;
      }

      if(index < innerIndex) {
        response = request.responses[j];
        break;
      }
    }

    if(response.file) {
      this.file(res, response);
      return;
    }

    this.url(res, response);

  }
};

module.exports = result;
<|endoftext|>


<commit_before>import React from 'react';
import { Header, Feed, Divider, Label } from 'semantic-ui-react';
import { capitalize, toLower } from 'lodash/string';

const { ipcRenderer } = require('electron');
const remote = require('@electron/remote');

const config = remote.getGlobal('config');

const STATUS_COLOR_MAP = {
  success: 'green',
  info: 'blue',
  warning: 'yellow',
  error: 'red',
  debug: 'darkgrey',
};
const STATUS_ICON_MAP = {
  success: 'check',
  info: 'info circle',
  warning: 'warning sign',
  error: 'x',
  debug: 'code',
};
const determineLabelColor = (status) => STATUS_COLOR_MAP[status] || 'grey';
const determineLabelIcon = (status) => STATUS_ICON_MAP[status] || 'question';

class Logs extends React.Component {
  constructor() {
    super();
    this.state = { entries: [] };
  }

  componentDidMount() {
    ipcRenderer.on('logupdated', (event, message) => {
      this.update(message);
    });
    this.setState({ entries: ipcRenderer.sendSync('logGetEntries') });
  }

  componentWillUnmount() {
    ipcRenderer.removeAllListeners('logupdated');
  }

  update(entries) {
    this.setState({ entries });
  }

  render() {
    const LogEntries = this.state.entries.map((entry) => {
      if (entry.type !== 'debug' || config.Config.App.debug) {
        return (
          <Feed key={entry.id} className="log" size="small">
            <Feed.Event>
              <Feed.Content>
                <Feed.Summary>

                    <Icon name={determineLabelIcon(entry.type)} />
                    {capitalize(entry.source)}
                    {entry.name && {entry.name}}

                  <Feed.Date>{entry.date}</Feed.Date>
                </Feed.Summary>
                <Feed.Extra>

                </Feed.Extra>
              </Feed.Content>
            </Feed.Event>
          </Feed>
        );
      }
    });

    return (

        Logs
        {LogEntries}

    );
  }
}

module.exports = Logs;
<commit_msg>lint: remove empty lien<commit_after>import React from 'react';
import { Header, Feed, Divider, Label } from 'semantic-ui-react';
import { capitalize, toLower } from 'lodash/string';

const { ipcRenderer } = require('electron');
const remote = require('@electron/remote');

const config = remote.getGlobal('config');

const STATUS_COLOR_MAP = {
  success: 'green',
  info: 'blue',
  warning: 'yellow',
  error: 'red',
  debug: 'darkgrey',
};
const STATUS_ICON_MAP = {
  success: 'check',
  info: 'info circle',
  warning: 'warning sign',
  error: 'x',
  debug: 'code',
};
const determineLabelColor = (status) => STATUS_COLOR_MAP[status] || 'grey';
const determineLabelIcon = (status) => STATUS_ICON_MAP[status] || 'question';

class Logs extends React.Component {
  constructor() {
    super();
    this.state = { entries: [] };
  }

  componentDidMount() {
    ipcRenderer.on('logupdated', (event, message) => {
      this.update(message);
    });
    this.setState({ entries: ipcRenderer.sendSync('logGetEntries') });
  }

  componentWillUnmount() {
    ipcRenderer.removeAllListeners('logupdated');
  }

  update(entries) {
    this.setState({ entries });
  }
  render() {
    const LogEntries = this.state.entries.map((entry) => {
      if (entry.type !== 'debug' || config.Config.App.debug) {
        return (
          <Feed key={entry.id} className="log" size="small">
            <Feed.Event>
              <Feed.Content>
                <Feed.Summary>

                    <Icon name={determineLabelIcon(entry.type)} />
                    {capitalize(entry.source)}
                    {entry.name && {entry.name}}

                  <Feed.Date>{entry.date}</Feed.Date>
                </Feed.Summary>
                <Feed.Extra>

                </Feed.Extra>
              </Feed.Content>
            </Feed.Event>
          </Feed>
        );
      }
    });

    return (

        Logs
        {LogEntries}

    );
  }
}

module.exports = Logs;
<|endoftext|>


<commit_before>/**
 * Server
 */
function Server(config)
{
    EventEmitter.call(this);

    this.config  = config;
    this.app     = express();
    this.server  = new http.Server(this.app);
    this.clients = new Collection([], 'id', true);

    this.roomRepository  = new RoomRepository();
    this.roomsController = new RoomsController(this.roomRepository);

    this.authorizationHandler  = this.authorizationHandler.bind(this);
    this.onSocketConnection    = this.onSocketConnection.bind(this);
    this.onSocketDisconnection = this.onSocketDisconnection.bind(this);
    this.onError               = this.onError.bind(this);

    this.app.use(express.static('web'));

    this.server.on('error', this.onError);
    this.server.on('upgrade', this.authorizationHandler);
    this.server.listen(config.port);

    console.info('Listening on: %s', config.port);
}

Server.prototype = Object.create(EventEmitter.prototype);
Server.prototype.constructor = Server;

/**
 * Authorization Handler
 *
 * @param {Object} request
 * @param {Object} socket
 * @param {Buffer} body
 */
Server.prototype.authorizationHandler = function(request, socket, head)
{
    return WebSocket.isWebSocket(request) ? this.onSocketConnection(new WebSocket(request, socket, head, ['websocket'], {ping: 5})) : socket.end();
};

/**
 * On socket connection
 *
 * @param {Socket} socket
 */
Server.prototype.onSocketConnection = function(socket)
{
    var server = this,
        client = new SocketClient(socket, 3);

    this.clients.add(client);
    client.on('close', this.onSocketDisconnection);
    client.addEvent('open', client.id);
    this.emit('client', client);

    console.info('Client connected', client.id);

    this.roomsController.attach(client);
};

/**
 * On socket connection
 *
 * @param {SocketClient} client
 */
Server.prototype.onSocketDisconnection = function(client)
{
    console.info('Client disconnected', client.id);

    this.clients.remove(client);
};

/**
 * On error
 *
 * @param {Error} error
 */
Server.prototype.onError = function(error)
{
    console.error('Server Error:', error.stack);
};
<commit_msg>Added timeout<commit_after>/**
 * Server
 */
function Server(config)
{
    EventEmitter.call(this);

    this.config  = config;
    this.app     = express();
    this.server  = new http.Server(this.app);
    this.clients = new Collection([], 'id', true);

    this.roomRepository  = new RoomRepository();
    this.roomsController = new RoomsController(this.roomRepository);

    this.authorizationHandler  = this.authorizationHandler.bind(this);
    this.onSocketConnection    = this.onSocketConnection.bind(this);
    this.onSocketDisconnection = this.onSocketDisconnection.bind(this);
    this.onError               = this.onError.bind(this);

    this.app.use(express.static('web'));

    this.server.on('error', this.onError);
    this.server.on('upgrade', this.authorizationHandler);
    this.server.listen(config.port);

    console.info('Listening on: %s', config.port);
}

Server.prototype = Object.create(EventEmitter.prototype);
Server.prototype.constructor = Server;

/**
 * Authorization Handler
 *
 * @param {Object} request
 * @param {Object} socket
 * @param {Buffer} body
 */
Server.prototype.authorizationHandler = function(request, socket, head)
{
    return WebSocket.isWebSocket(request) ? this.onSocketConnection(new WebSocket(request, socket, head, ['websocket'], {ping: 5})) : socket.end();
};

/**
 * On socket connection
 *
 * @param {Socket} socket
 */
Server.prototype.onSocketConnection = function(socket)
{
    var server = this,
        client = new SocketClient(socket, 3);

    this.clients.add(client);
    client.on('close', this.onSocketDisconnection);

    setTimeout(function () {
        console.info('Client connected', client.id);
        client.addEvent('open', client.id);
        server.emit('client', client);
        server.roomsController.attach(client);
    }, 500);
};

/**
 * On socket connection
 *
 * @param {SocketClient} client
 */
Server.prototype.onSocketDisconnection = function(client)
{
    console.info('Client disconnected', client.id);

    this.clients.remove(client);
};

/**
 * On error
 *
 * @param {Error} error
 */
Server.prototype.onError = function(error)
{
    console.error('Server Error:', error.stack);
};
<|endoftext|>


<commit_before>/**
 * cbpAnimatedHeader.min.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
var cbpAnimatedHeader=(function(){var b=document.documentElement,g=document.querySelector(".cbp-af-header"),e=false,a=300;function f(){window.addEventListener("scroll",function(h){if(!e){e=true;setTimeout(d,250)}},false)}function d(){var h=c();if(h>=a){classie.add(g,"cbp-af-header-shrink")}else{classie.remove(g,"cbp-af-header-shrink")}e=false}function c(){return window.pageYOffset||b.scrollTop}f()})();<commit_msg>Delete cbpAnimatedHeader.min.js<commit_after><|endoftext|>


<commit_before>module.exports = {
  en: [
    ["Home", "about-appium/intro.md"],
    ["About", ["about-appium",
      ["Introduction", "intro.md"],
      ["The Appium Clients", "appium-clients.md"],
      ["Getting Started", "getting-started.md"],
      ["Supported Platforms", "platform-support.md"],
      ["API Documentation", "api.md"],
    ]],
    ["Drivers", ["drivers",
      ["XCUITest (iOS)", "ios-xcuitest.md"],
      ["XCUITest Real Devices (iOS)", "ios-xcuitest-real-devices.md"],
      ["UIAutomation (iOS)", "ios-uiautomation.md"],
      ["UIAutomation Safari Launcher (iOS)", "ios-uiautomation-safari-launcher.md"],
      ["UIAutomator (Android)", "android-uiautomator.md"],
      ["UIAutomator2 (Android)", "android-uiautomator2.md"],
      ["Espresso (Android)", "android-espresso.md"],
      ["Selendroid (Android)", "android-selendroid.md"],
      ["Windows", "windows.md"],
      ["Mac", "mac.md"],
    ]],
    ["Commands", ["commands",
      ["Status", "status.md"],
      ["Execute Mobile Command", "mobile-command.md"],
      ["Session", ["session",
        ["Create", "create.md"],
        ["End", "delete.md"],
        ["Get Session Capabilities", "get.md"],
        ["Go Back", "back.md"],
        ["Screenshot", "screenshot.md"],
        ["Source", "source.md"],
        ["Timeouts", ["timeouts",
          ["Timeouts", "timeouts.md"],
          ["Implicit Wait", "implicit-wait.md"],
          ["Async Script", "async-script.md"],
        ]],
        ["Orientation", ["orientation",
          ["Get Orientation", "get-orientation.md"],
          ["Set Orientation", "set-orientation.md"],
        ]],
        ["Geolocation", ["geolocation",
          ["Get Geolocation", "get-geolocation.md"],
          ["Set Geolocation", "set-geolocation.md"],
        ]],
        ["Logs", ["logs",
          ["Get Log Types", "get-log-types.md"],
          ["Get Logs", "get-log.md"],
        ]],
        ["Settings", ["settings",
          ["Update Settings", "update-settings.md"],
          ["Get Device Settings", "get-settings.md"],
        ]],
      ]],
      ["Device", ["device",
        ["Activity", ["activity",
          ["Start Activity", "start-activity.md"],
          ["Current Activity", "current-activity.md"],
          ["Current Package", "current-package.md"],
        ]],
        ["App", ["app",
          ["Install App", "install-app.md"],
          ["Is App Installed", "is-app-installed.md"],
          ["Launch App", "launch-app.md"],
          ["Background App", "background-app.md"],
          ["Close App", "close-app.md"],
          ["Reset App", "reset-app.md"],
          ["Remove App", "remove-app.md"],
          ["Get App Strings", "get-app-strings.md"],
          ["End Test Coverage", "end-test-coverage.md"],
        ]],
        ["Files", ["files",
          ["Push File", "push-file.md"],
          ["Pull File", "pull-file.md"],
          ["Pull Folder", "pull-folder.md"],
        ]],
        ["Interactions", ["interactions",
          ["Shake", "shake.md"],
          ["Lock", "lock.md"],
          ["Unlock", "unlock.md"],
          ["Is Locked", "is-locked.md"],
          ["Rotate", "rotate.md"],
        ]],
        ["Keys", ["keys",
          ["Press keycode", "press-keycode.md"],
          ["Long press keycode", "long-press-keycode.md"],
          ["Hide Keyboard", "hide-keyboard.md"],
          ["Is Keyboard Shown", "is-keyboard-shown.md"],
        ]],
        ["Network", ["network",
          ["Toggle Airplane Mode", "toggle-airplane-mode.md"],
          ["Toggle Data", "toggle-data.md"],
          ["Toggle WiFi", "toggle-wifi.md"],
          ["Toggle Location Services", "toggle-location-services.md"],
          ["Send SMS", "send-sms.md"],
          ["GSM Call", "gsm-call.md"],
          ["GSM Signal", "gsm-signal.md"],
          ["GSM Voice", "gsm-voice.md"],
        ]],
        ["Performance Data", ["performance-data",
          ["Get Performance Data", "get-performance-data.md"],
          ["Performance Data Types", "performance-data-types.md"],
        ]],
        ["Screen Recording", ["recording-screen",
          ["Start Screen Recording", "start-recording-screen.md"],
          ["Stop Screen Recording", "stop-recording-screen.md"],
        ]],
        ["Simulator", ["simulator",
          ["Perform Touch ID", "touch-id.md"],
          ["Toggle Touch ID Enrollment", "toggle-touch-id-enrollment.md"],
        ]],
        ["System", ["system",
          ["Open Notifications", "open-notifications.md"],
          ["System Bars", "system-bars.md"],
          ["System Time", "system-time.md"],
        ]],
        ["Authentication", ["authentication",
          ["Finger Print", "finger-print.md"],
        ]],
      ]],
      ["Element", ["element",
        ["Find Element", "find-element.md"],
        ["Find Elements", "find-elements.md"],
        ["Actions", ["actions",
          ["Click", "click.md"],
          ["Send Keys", "send-keys.md"],
          ["Clear", "clear.md"],
        ]],
        ["Attributes", ["attributes",
          ["Text", "text.md"],
          ["Name", "name.md"],
          ["Attribute", "attribute.md"],
          ["Selected", "selected.md"],
          ["Enabled", "enabled.md"],
          ["Displayed", "displayed.md"],
          ["Location", "location.md"],
          ["Size", "size.md"],
          ["Rect", "rect.md"],
          ["CSS Property", "css-property.md"],
          ["Location in View", "location-in-view.md"],
        ]],
        ["Other", ["other",
          ["Submit", "submit.md"],
          ["Active Element", "active.md"],
          ["Equals Element", "equals-element.md"],
        ]]
      ]],
      ["Context", ["context",
        ["Get Context", "get-context.md"],
        ["Get All Contexts", "get-contexts.md"],
        ["Set Context", "set-context.md"],
      ]],
      ["Interactions", ["interactions",
        ["Mouse", ["mouse",
          ["Move To", "moveto.md"],
          ["Click", "click.md"],
          ["Double Click", "doubleclick.md"],
          ["Button Down", "button-down.md"],
          ["Button Up", "button-up.md"],
        ]],
        ["Touch", ["touch",
          ["Single Tap", "tap.md"],
          ["Double Tap", "double-tap.md"],
          ["Move", "move.md"],
          ["Touch Down", "touch-down.md"],
          ["Touch Up", "touch-up.md"],
          ["Long Press", "long-press.md"],
          ["Scroll", "scroll.md"],
          ["Flick", "flick.md"],
          ["Multi Touch Perform", "multi-touch-perform.md"],
          ["Touch Perform", "touch-perform.md"],
        ]],
        ["W3C Actions", "actions.md"],
      ]],
      ["Web", ["web",
        ["Window", ["window",
          ["Set Window", "set-window.md"],
          ["Close Window", "close-window.md"],
          ["Get Handle", "get-handle.md"],
          ["Get Handles", "get-handles.md"],
          ["Get Title", "title.md"],
          ["Get Window Size", "get-window-size.md"],
          ["Set Window Size", "set-window-size.md"],
          ["Get Window Position", "get-window-position.md"],
          ["Set Window Position", "set-window-position.md"],
          ["Maximize Window", "maximize-window.md"],
        ]],
        ["Navigation", ["navigation",
          ["Go to URL", "go-to-url.md"],
          ["Get URL", "url.md"],
          ["Back", "back.md"],
          ["Forward", "forward.md"],
          ["Refresh", "refresh.md"],
        ]],
        ["Storage", ["storage",
          ["Get All Cookies", "get-all-cookies.md"],
          ["Set Cookie", "set-cookie.md"],
          ["Delete Cookie", "delete-cookie.md"],
          ["Delete All Cookies", "delete-all-cookies.md"],
        ]],
        ["Frame", ["frame",
          ["Switch to Frame", "switch.md"],
          ["Switch to Parent Frame", "parent.md"],
        ]],
        ["Execute Async", "execute-async.md"],
        ["Execute", "execute.md"],
      ]],
    ]],
    ["Writing & Running Tests", ["writing-running-appium",
      ["Running Tests", "running-tests.md"],
      ["Desired Capabilities", "caps.md"],
      ["The --default-capabilities flag", "default-capabilities-arg.md"],
      ["Finding Elements", "finding-elements.md"],
      ["Touch Actions", "touch-actions.md"],
      ["CLI Arguments", "server-args.md"],
      ["Web/Web Views", ["web",
        ["Mobile Web Testing", "mobile-web.md"],
        ["Automating Hybrid Apps", "hybrid.md"],
        ["Using ios-webkit-debug-proxy", "ios-webkit-debug-proxy.md"],
        ["Using Chromedriver", "chromedriver.md"],
      ]],
      ["iOS", ["ios",
        ["XCUITest Mobile Gestures", "ios-xctest-mobile-gestures.md"],
        ["XCUITest Mobile App Management", "ios-xctest-mobile-apps-management.md"],
        ["iOS Pasteboard Guide", "ios-xctest-pasteboard.md"],
        ["iOS Predicate Guide", "ios-predicate.md"],
        ["iOS Touch ID Guide", "ios-touch-id.md"],
        ["iOS Install Certificate", "ios-xctest-install-certificate.md"],
      ]],
      ["Android", ["android",
        ["UiSelector Guide", "uiautomator-uiselector.md"],
        ["Android Code Coverage Guide", "android-coverage.md"],
        ["Activities Startup Troubleshooting Guide", "activity-startup.md"],
        ["How To Execute Shell Commands On The Remote Device", "android-shell.md"],
        ["How To Emulate IME Actions Generation", "android-ime.md"],
        ["How To Test Android App Bundle", "android-appbundle.md"]
      ]],
      ["Other", ["other",
        ["Reset Strategies", "reset-strategies.md"],
        ["Network Connection Guide", "network-connection.md"],
        ["Using Unicode with Appium", "unicode.md"],
        ["Troubleshooting", "troubleshooting.md"]
      ]],
    ]],
    ["Advanced", ["advanced-concepts",
      ["Finding Image Elements", "image-elements.md"],
      ["Using Element Finding Plugins", "element-finding-plugins.md"],
      ["Migrating to XCUITest", "migrating-to-xcuitest.md"],
      ["Using Selenium Grid with Appium", "grid.md"],
      ["Cross-domain iframes", "cross-domain-iframes.md"],
      ["Using a custom WDA server", "wda-custom-server.md"],
      ["Running with multiple versions of Xcode", "multiple-xcode-versions.md"],
      ["The Event Timings API", "event-timings.md"],
      ["Setup for Parallel Testing", "parallel-tests.md"],
      ["The Settings API", "settings.md"]]],
    ["Contributing", ["contributing-to-appium",
      ["Running Appium from Source", "appium-from-source.md"],
      ["Developer Overview", "developers-overview.md"],
      ["Standard Dev Commands", "dev-tools.md"],
      ["Appium Style Guide", "style-guide.md"],
      ["How to Write Docs", "how-to-write-docs.md"],
      ["Appium Package Structure", "appium-packages.md"],
      ["Credits", "credits.md"]]]
  ], "cn": [
  ]
};
<commit_msg>fix toc.js (add missing contents, clipboard and emulator commands) (#11846)<commit_after>module.exports = {
  en: [
    ["Home", "about-appium/intro.md"],
    ["About", ["about-appium",
      ["Introduction", "intro.md"],
      ["The Appium Clients", "appium-clients.md"],
      ["Getting Started", "getting-started.md"],
      ["Supported Platforms", "platform-support.md"],
      ["API Documentation", "api.md"],
    ]],
    ["Drivers", ["drivers",
      ["XCUITest (iOS)", "ios-xcuitest.md"],
      ["XCUITest Real Devices (iOS)", "ios-xcuitest-real-devices.md"],
      ["UIAutomation (iOS)", "ios-uiautomation.md"],
      ["UIAutomation Safari Launcher (iOS)", "ios-uiautomation-safari-launcher.md"],
      ["UIAutomator (Android)", "android-uiautomator.md"],
      ["UIAutomator2 (Android)", "android-uiautomator2.md"],
      ["Espresso (Android)", "android-espresso.md"],
      ["Selendroid (Android)", "android-selendroid.md"],
      ["Windows", "windows.md"],
      ["Mac", "mac.md"],
    ]],
    ["Commands", ["commands",
      ["Status", "status.md"],
      ["Execute Mobile Command", "mobile-command.md"],
      ["Session", ["session",
        ["Create", "create.md"],
        ["End", "delete.md"],
        ["Get Session Capabilities", "get.md"],
        ["Go Back", "back.md"],
        ["Screenshot", "screenshot.md"],
        ["Source", "source.md"],
        ["Timeouts", ["timeouts",
          ["Timeouts", "timeouts.md"],
          ["Implicit Wait", "implicit-wait.md"],
          ["Async Script", "async-script.md"],
        ]],
        ["Orientation", ["orientation",
          ["Get Orientation", "get-orientation.md"],
          ["Set Orientation", "set-orientation.md"],
        ]],
        ["Geolocation", ["geolocation",
          ["Get Geolocation", "get-geolocation.md"],
          ["Set Geolocation", "set-geolocation.md"],
        ]],
        ["Logs", ["logs",
          ["Get Log Types", "get-log-types.md"],
          ["Get Logs", "get-log.md"],
        ]],
        ["Settings", ["settings",
          ["Update Settings", "update-settings.md"],
          ["Get Device Settings", "get-settings.md"],
        ]],
      ]],
      ["Device", ["device",
        ["Activity", ["activity",
          ["Start Activity", "start-activity.md"],
          ["Current Activity", "current-activity.md"],
          ["Current Package", "current-package.md"],
        ]],
        ["App", ["app",
          ["Install App", "install-app.md"],
          ["Is App Installed", "is-app-installed.md"],
          ["Launch App", "launch-app.md"],
          ["Background App", "background-app.md"],
          ["Close App", "close-app.md"],
          ["Reset App", "reset-app.md"],
          ["Remove App", "remove-app.md"],
          ["Get App Strings", "get-app-strings.md"],
          ["End Test Coverage", "end-test-coverage.md"],
        ]],
        ["Clipboard", ["clipboard",
          ["Get Clipboard", "get-clipboard.md"],
          ["Set Clipboard", "set-Clipboard.md"],
        ]],
        ["Emulator", ["emulator",
          ["Power AC", "power_ac.md"],
          ["Power Capacity", "power_capacity.md"],
        ]],
        ["Files", ["files",
          ["Push File", "push-file.md"],
          ["Pull File", "pull-file.md"],
          ["Pull Folder", "pull-folder.md"],
        ]],
        ["Interactions", ["interactions",
          ["Shake", "shake.md"],
          ["Lock", "lock.md"],
          ["Unlock", "unlock.md"],
          ["Is Locked", "is-locked.md"],
          ["Rotate", "rotate.md"],
        ]],
        ["Keys", ["keys",
          ["Press keycode", "press-keycode.md"],
          ["Long press keycode", "long-press-keycode.md"],
          ["Hide Keyboard", "hide-keyboard.md"],
          ["Is Keyboard Shown", "is-keyboard-shown.md"],
        ]],
        ["Network", ["network",
          ["Toggle Airplane Mode", "toggle-airplane-mode.md"],
          ["Toggle Data", "toggle-data.md"],
          ["Toggle WiFi", "toggle-wifi.md"],
          ["Toggle Location Services", "toggle-location-services.md"],
          ["Send SMS", "send-sms.md"],
          ["GSM Call", "gsm-call.md"],
          ["GSM Signal", "gsm-signal.md"],
          ["GSM Voice", "gsm-voice.md"],
        ]],
        ["Performance Data", ["performance-data",
          ["Get Performance Data", "get-performance-data.md"],
          ["Performance Data Types", "performance-data-types.md"],
        ]],
        ["Screen Recording", ["recording-screen",
          ["Start Screen Recording", "start-recording-screen.md"],
          ["Stop Screen Recording", "stop-recording-screen.md"],
        ]],
        ["Simulator", ["simulator",
          ["Perform Touch ID", "touch-id.md"],
          ["Toggle Touch ID Enrollment", "toggle-touch-id-enrollment.md"],
        ]],
        ["System", ["system",
          ["Open Notifications", "open-notifications.md"],
          ["System Bars", "system-bars.md"],
          ["System Time", "system-time.md"],
        ]],
        ["Authentication", ["authentication",
          ["Finger Print", "finger-print.md"],
        ]],
      ]],
      ["Element", ["element",
        ["Find Element", "find-element.md"],
        ["Find Elements", "find-elements.md"],
        ["Actions", ["actions",
          ["Click", "click.md"],
          ["Send Keys", "send-keys.md"],
          ["Clear", "clear.md"],
        ]],
        ["Attributes", ["attributes",
          ["Text", "text.md"],
          ["Name", "name.md"],
          ["Attribute", "attribute.md"],
          ["Selected", "selected.md"],
          ["Enabled", "enabled.md"],
          ["Displayed", "displayed.md"],
          ["Location", "location.md"],
          ["Size", "size.md"],
          ["Rect", "rect.md"],
          ["CSS Property", "css-property.md"],
          ["Location in View", "location-in-view.md"],
        ]],
        ["Other", ["other",
          ["Submit", "submit.md"],
          ["Active Element", "active.md"],
          ["Equals Element", "equals-element.md"],
        ]]
      ]],
      ["Context", ["context",
        ["Get Context", "get-context.md"],
        ["Get All Contexts", "get-contexts.md"],
        ["Set Context", "set-context.md"],
      ]],
      ["Interactions", ["interactions",
        ["Mouse", ["mouse",
          ["Move To", "moveto.md"],
          ["Click", "click.md"],
          ["Double Click", "doubleclick.md"],
          ["Button Down", "button-down.md"],
          ["Button Up", "button-up.md"],
        ]],
        ["Touch", ["touch",
          ["Single Tap", "tap.md"],
          ["Double Tap", "double-tap.md"],
          ["Move", "move.md"],
          ["Touch Down", "touch-down.md"],
          ["Touch Up", "touch-up.md"],
          ["Long Press", "long-press.md"],
          ["Scroll", "scroll.md"],
          ["Flick", "flick.md"],
          ["Multi Touch Perform", "multi-touch-perform.md"],
          ["Touch Perform", "touch-perform.md"],
        ]],
        ["W3C Actions", "actions.md"],
      ]],
      ["Web", ["web",
        ["Window", ["window",
          ["Set Window", "set-window.md"],
          ["Close Window", "close-window.md"],
          ["Get Handle", "get-handle.md"],
          ["Get Handles", "get-handles.md"],
          ["Get Title", "title.md"],
          ["Get Window Size", "get-window-size.md"],
          ["Set Window Size", "set-window-size.md"],
          ["Get Window Position", "get-window-position.md"],
          ["Set Window Position", "set-window-position.md"],
          ["Maximize Window", "maximize-window.md"],
        ]],
        ["Navigation", ["navigation",
          ["Go to URL", "go-to-url.md"],
          ["Get URL", "url.md"],
          ["Back", "back.md"],
          ["Forward", "forward.md"],
          ["Refresh", "refresh.md"],
        ]],
        ["Storage", ["storage",
          ["Get All Cookies", "get-all-cookies.md"],
          ["Set Cookie", "set-cookie.md"],
          ["Delete Cookie", "delete-cookie.md"],
          ["Delete All Cookies", "delete-all-cookies.md"],
        ]],
        ["Frame", ["frame",
          ["Switch to Frame", "switch.md"],
          ["Switch to Parent Frame", "parent.md"],
        ]],
        ["Execute Async", "execute-async.md"],
        ["Execute", "execute.md"],
      ]],
    ]],
    ["Writing & Running Tests", ["writing-running-appium",
      ["Running Tests", "running-tests.md"],
      ["Desired Capabilities", "caps.md"],
      ["The --default-capabilities flag", "default-capabilities-arg.md"],
      ["Finding Elements", "finding-elements.md"],
      ["Touch Actions", "touch-actions.md"],
      ["CLI Arguments", "server-args.md"],
      ["Web/Web Views", ["web",
        ["Mobile Web Testing", "mobile-web.md"],
        ["Automating Hybrid Apps", "hybrid.md"],
        ["Using ios-webkit-debug-proxy", "ios-webkit-debug-proxy.md"],
        ["Using Chromedriver", "chromedriver.md"],
      ]],
      ["iOS", ["ios",
        ["XCUITest Mobile Gestures", "ios-xctest-mobile-gestures.md"],
        ["XCUITest Mobile App Management", "ios-xctest-mobile-apps-management.md"],
        ["iOS Pasteboard Guide", "ios-xctest-pasteboard.md"],
        ["iOS Predicate Guide", "ios-predicate.md"],
        ["iOS Touch ID Guide", "ios-touch-id.md"],
        ["iOS Install Certificate", "ios-xctest-install-certificate.md"],
      ]],
      ["Android", ["android",
        ["UiSelector Guide", "uiautomator-uiselector.md"],
        ["Android Code Coverage Guide", "android-coverage.md"],
        ["Activities Startup Troubleshooting Guide", "activity-startup.md"],
        ["How To Execute Shell Commands On The Remote Device", "android-shell.md"],
        ["How To Emulate IME Actions Generation", "android-ime.md"],
        ["How To Test Android App Bundle", "android-appbundle.md"]
      ]],
      ["Other", ["other",
        ["Reset Strategies", "reset-strategies.md"],
        ["Network Connection Guide", "network-connection.md"],
        ["Using Unicode with Appium", "unicode.md"],
        ["Troubleshooting", "troubleshooting.md"]
      ]],
    ]],
    ["Advanced", ["advanced-concepts",
      ["Finding Image Elements", "image-elements.md"],
      ["Using Element Finding Plugins", "element-finding-plugins.md"],
      ["Migrating to XCUITest", "migrating-to-xcuitest.md"],
      ["Using Selenium Grid with Appium", "grid.md"],
      ["Cross-domain iframes", "cross-domain-iframes.md"],
      ["Using a custom WDA server", "wda-custom-server.md"],
      ["Running with multiple versions of Xcode", "multiple-xcode-versions.md"],
      ["The Event Timings API", "event-timings.md"],
      ["Setup for Parallel Testing", "parallel-tests.md"],
      ["The Settings API", "settings.md"]]],
    ["Contributing", ["contributing-to-appium",
      ["Running Appium from Source", "appium-from-source.md"],
      ["Developer Overview", "developers-overview.md"],
      ["Standard Dev Commands", "dev-tools.md"],
      ["Appium Style Guide", "style-guide.md"],
      ["How to Write Docs", "how-to-write-docs.md"],
      ["Appium Package Structure", "appium-packages.md"],
      ["Credits", "credits.md"]]]
  ], "cn": [
  ]
};
<|endoftext|>


<commit_before>function coinmap() {

  var tileOSM = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Map data by OpenStreetMap, under CC BY SA.',
    maxZoom: 18
  });

  var tileToner = L.tileLayer('http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {
    attribution: 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.',
    maxZoom: 18
  });

  var tileMapQuest = L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
    subdomains: ['otile1','otile2','otile3','otile4'],
    attribution: 'Map tiles by MapQuest. Data by OpenStreetMap, under CC BY SA.',
    maxZoom: 18
  });

  var map = L.map('map', { zoom: 3, layers: [tileOSM] });

  L.control.layers({
    "OpenStreetMap": tileOSM,
    "MapQuest Open": tileMapQuest,
    "Toner": tileToner,
  }).addTo(map);

  var markers = new L.MarkerClusterGroup({showCoverageOnHover: false, maxClusterRadius: 32});

  coinmap_populate(markers);

  map.addLayer(markers);

  map.locate({setView: true, maxZoom: 6});
}
<commit_msg>add mapquest aerial<commit_after>function coinmap() {

  var tileOSM = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: 'Data by OpenStreetMap, under CC BY SA.',
    maxZoom: 18
  });

  var tileToner = L.tileLayer('http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {
    attribution: 'Map tiles by Stamen Design, under CC BY 3.0. Data by OpenStreetMap, under CC BY SA.',
    maxZoom: 18
  });

  var tileMapQuest = L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {
    subdomains: ['otile1','otile2','otile3','otile4'],
    attribution: 'Map tiles by MapQuest. Data by OpenStreetMap, under CC BY SA.',
    maxZoom: 18
  });

  var tileMapQuestAerial = L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.png', {
    subdomains: ['otile1','otile2','otile3','otile4'],
    attribution: 'Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency. Data by OpenStreetMap, under CC BY SA.',
    maxZoom: 18
  });

  var map = L.map('map', { zoom: 3, layers: [tileOSM] });

  L.control.layers({
    "OpenStreetMap": tileOSM,
    "MapQuest Open": tileMapQuest,
    "MapQuest Open Aerial": tileMapQuestAerial,
    "Toner": tileToner,
  }).addTo(map);

  var markers = new L.MarkerClusterGroup({showCoverageOnHover: false, maxClusterRadius: 32});

  coinmap_populate(markers);

  map.addLayer(markers);

  map.locate({setView: true, maxZoom: 6});
}
<|endoftext|>


<commit_before>const client = require("client");
const buildFromFolder = require("template").buildFromFolder;
const Blog = require("blog");
const { promisify } = require("util");
const Update = require("./update");
const Rename = require("./rename");
const localPath = require("helper/localPath");
const clfdate = require("helper/clfdate");
const uuid = require("uuid/v4");
const renames = require("./renames");
const lockfile = require("proper-lockfile");
const type = require("helper/type");
const email = require("helper/email");
const lowerCaseContents = require("./lowerCaseContents");

function sync(blogID, callback) {
  if (!type(blogID, "string")) {
    throw new TypeError("Expected blogID with type:String as first argument");
  }

  if (!type(callback, "function")) {
    throw new TypeError(
      "Expected callback with type:Function as second argument"
    );
  }

  const syncID = "sync_" + uuid().slice(0, 7);
  const log = function () {
    console.log.apply(null, [
      clfdate(),
      blogID.slice(0, 12),
      syncID,
      ...arguments,
    ]);
  };

  log("Starting sync, fetching blog information");

  Blog.get({ id: blogID }, async function (err, blog) {
    // It would be nice to get an error from Blog.get instead of this...
    if (err || !blog || !blog.id || blog.isDisabled) {
      log("Error with blog's ability to sync");
      return callback(new Error("Cannot sync blog " + blogID));
    }

    let release;

    try {
      log("Acquiring lock on folder");
      release = await lockfile.lock(localPath(blogID, "/"));
      log("Successfully acquired lock on folder");
    } catch (e) {
      log("Failed to acquire lock on folder");
      return callback(new Error("Failed to acquire folder lock"));
    }

    const folder = {
      path: localPath(blogID, "/"),
      update: new Update(blog, log),
      rename: Rename(blog, log),
      lowerCaseContents: lowerCaseContents(blog, promisify(Rename(blog, log))),
      status: (message) => client.publish("sync:status:" + blogID, message),
      log,
    };

    const timeout = setTimeout(function () {
      log("Warning: sync exceeded 10 minutes");
      email.LONG_SYNC();
    }, 10 * 60 * 1000); // 10 minutes

    // Right now localPath returns a path with a trailing slash for some
    // crazy reason. This means that we need to remove the trailing
    // slash for this to work properly. In future, you should be able
    // to remove this line when localPath works properly.
    if (folder.path.slice(-1) === "/") folder.path = folder.path.slice(0, -1);

    // We acquired a lock on the resource!
    // This function is to be called when we are finished
    // with the lock on the user's folder.
    folder.status("Syncing");

    // Pass methods to trigger folder updates back to the
    // function which wanted to modify the blog's folder.
    callback(null, folder, function (syncError, callback) {
      log("Sync callback invoked");
      folder.status("Synced");

      if (typeof syncError === "function")
        throw new Error("Pass an error or null as first argument to done");

      if (typeof callback !== "function")
        throw new Error("Pass a callback to done");

      log("Checking for renamed files");
      renames(blogID, async function (err) {
        if (err) {
          log("Error checking file renames");
          log("Releasing lock");
          await release();
          clearTimeout(timeout);
          return callback(err);
        }

        // What is the appropriate order for this?
        log("Building templates from folder");
        buildFromFolder(blogID, async function (err) {
          if (err) {
            log("Error building templates from folder");
            log("Releasing lock");
            await release();
            clearTimeout(timeout);
            return callback(err);
          }

          const cacheID = Date.now();

          // Passing in cacheID manually busts the cache.
          // Since Blog.set and Blog.flushCache depend on each other
          // we can't put this there. Ideally we would expose a single function to
          // wipe the cache. So fix that eventually...
          log("Updating cacheID of blog");
          Blog.set(blogID, { cacheID }, async function (err) {
            if (err) {
              log("Error updating cacheID of blog");
              log("Releasing lock");
              await release();
              clearTimeout(timeout);
              return callback(err);
            }

            // We could do these next two things in parallel
            // but it's a little bit of refactoring...
            log("Releasing lock");
            await release();
            clearTimeout(timeout);
            log("Finished sync");
            callback(syncError);
          });
        });
      });
    });
  });
}

module.exports = sync;
<commit_msg>Adds retries to sync lock<commit_after>const client = require("client");
const buildFromFolder = require("template").buildFromFolder;
const Blog = require("blog");
const { promisify } = require("util");
const Update = require("./update");
const Rename = require("./rename");
const localPath = require("helper/localPath");
const clfdate = require("helper/clfdate");
const uuid = require("uuid/v4");
const renames = require("./renames");
const lockfile = require("proper-lockfile");
const type = require("helper/type");
const email = require("helper/email");
const lowerCaseContents = require("./lowerCaseContents");

function sync(blogID, callback) {
  if (!type(blogID, "string")) {
    throw new TypeError("Expected blogID with type:String as first argument");
  }

  if (!type(callback, "function")) {
    throw new TypeError(
      "Expected callback with type:Function as second argument"
    );
  }

  const syncID = "sync_" + uuid().slice(0, 7);
  const log = function () {
    console.log.apply(null, [
      clfdate(),
      blogID.slice(0, 12),
      syncID,
      ...arguments,
    ]);
  };

  log("Starting sync, fetching blog information");

  Blog.get({ id: blogID }, async function (err, blog) {
    // It would be nice to get an error from Blog.get instead of this...
    if (err || !blog || !blog.id || blog.isDisabled) {
      log("Error with blog's ability to sync");
      return callback(new Error("Cannot sync blog " + blogID));
    }

    let release;

    try {
      log("Acquiring lock on folder");
      release = await lockfile.lock(localPath(blogID, "/"), {
        retries: {
          retries: 3,
          factor: 2,
          minTimeout: 100,
          maxTimeout: 200,
          randomize: true,
        },
      });
      log("Successfully acquired lock on folder");
    } catch (e) {
      log("Failed to acquire lock on folder");
      return callback(new Error("Failed to acquire folder lock"));
    }

    const folder = {
      path: localPath(blogID, "/"),
      update: new Update(blog, log),
      rename: Rename(blog, log),
      lowerCaseContents: lowerCaseContents(blog, promisify(Rename(blog, log))),
      status: (message) => {
        log(message);
        client.publish("sync:status:" + blogID, message);
      },
      log,
    };

    const timeout = setTimeout(function () {
      log("Warning: sync exceeded 10 minutes");
      email.LONG_SYNC();
    }, 10 * 60 * 1000); // 10 minutes

    // Right now localPath returns a path with a trailing slash for some
    // crazy reason. This means that we need to remove the trailing
    // slash for this to work properly. In future, you should be able
    // to remove this line when localPath works properly.
    if (folder.path.slice(-1) === "/") folder.path = folder.path.slice(0, -1);

    // We acquired a lock on the resource!
    // This function is to be called when we are finished
    // with the lock on the user's folder.
    folder.status("Syncing");

    // Pass methods to trigger folder updates back to the
    // function which wanted to modify the blog's folder.
    callback(null, folder, function (syncError, callback) {
      log("Sync callback invoked");
      folder.status("Synced");

      if (typeof syncError === "function")
        throw new Error("Pass an error or null as first argument to done");

      if (typeof callback !== "function")
        throw new Error("Pass a callback to done");

      log("Checking for renamed files");
      renames(blogID, async function (err) {
        if (err) {
          log("Error checking file renames");
          log("Releasing lock");
          await release();
          clearTimeout(timeout);
          return callback(err);
        }

        // What is the appropriate order for this?
        log("Building templates from folder");
        buildFromFolder(blogID, async function (err) {
          if (err) {
            log("Error building templates from folder");
            log("Releasing lock");
            await release();
            clearTimeout(timeout);
            return callback(err);
          }

          const cacheID = Date.now();

          // Passing in cacheID manually busts the cache.
          // Since Blog.set and Blog.flushCache depend on each other
          // we can't put this there. Ideally we would expose a single function to
          // wipe the cache. So fix that eventually...
          log("Updating cacheID of blog");
          Blog.set(blogID, { cacheID }, async function (err) {
            if (err) {
              log("Error updating cacheID of blog");
              log("Releasing lock");
              await release();
              clearTimeout(timeout);
              return callback(err);
            }

            // We could do these next two things in parallel
            // but it's a little bit of refactoring...
            log("Releasing lock");
            await release();
            clearTimeout(timeout);
            log("Finished sync");
            callback(syncError);
          });
        });
      });
    });
  });
}

module.exports = sync;
<|endoftext|>


<commit_before>BI.RootTreeLeafItem = BI.inherit(BI.BasicButton, {
    _defaultConfig: function () {
        return BI.extend(BI.RootTreeLeafItem.superclass._defaultConfig.apply(this, arguments), {
            extraCls: "bi-root-tree-leaf-item bi-list-item-active",
            logic: {
                dynamic: false
            },
            id: "",
            pId: "",
            layer: 0,
            height: 24
        });
    },
    _init: function () {
        BI.RootTreeLeafItem.superclass._init.apply(this, arguments);
        var o = this.options;
        this.text = BI.createWidget({
            type: "bi.label",
            textAlign: "left",
            whiteSpace: "nowrap",
            textHeight: o.height,
            height: o.height,
            hgap: o.hgap,
            text: o.text,
            value: o.value,
            py: o.py,
            keyword: o.keyword
        });
        var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left);
        var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, {
            width: 24,
            el: {
                type: "bi.layout",
                width: 24,
                height: o.height
            }
        }, {
            el: this.text
        });
        BI.createWidget(BI.extend({
            element: this
        }, BI.LogicFactory.createLogic(type, BI.extend(o.logic, {
            items: items
        }))));
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    },

    doHighLight: function () {
        this.text.doHighLight.apply(this.text, arguments);
    },

    unHighLight: function () {
        this.text.unHighLight.apply(this.text, arguments);
    },

    getId: function () {
        return this.options.id;
    },

    getPId: function () {
        return this.options.pId;
    }
});

BI.shortcut("bi.root_tree_leaf_item", BI.RootTreeLeafItem);
<commit_msg>DEC-15891 fix: 补充唯一根节点item场景<commit_after>BI.RootTreeLeafItem = BI.inherit(BI.BasicButton, {
    props: {
        baseCls: "bi-root-tree-leaf-item bi-list-item-active",
        logic: {
            dynamic: false
        },
        id: "",
        pId: "",
        layer: 0,
        height: 24
    },

    render: function () {
        var self = this;
        var o = this.options;
        var text = {
            type: "bi.label",
            ref: function (_ref) {
                self.text = _ref;
            },
            textAlign: "left",
            whiteSpace: "nowrap",
            textHeight: o.height,
            height: o.height,
            hgap: o.hgap,
            text: o.text,
            value: o.value,
            py: o.py,
            keyword: o.keyword
        };

        var type = BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left);
        var items = BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left, {
            width: 24,
            el: {
                type: "bi.layout",
                width: 24,
                height: o.height
            }
        }, {
            el: text
        });

        return BI.LogicFactory.createLogic(type, BI.extend(o.logic, {
            items: items
        }));
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    },

    doHighLight: function () {
        this.text.doHighLight.apply(this.text, arguments);
    },

    unHighLight: function () {
        this.text.unHighLight.apply(this.text, arguments);
    },

    getId: function () {
        return this.options.id;
    },

    getPId: function () {
        return this.options.pId;
    }
});

BI.shortcut("bi.root_tree_leaf_item", BI.RootTreeLeafItem);
<|endoftext|>


<commit_before>"use strict"

const { getPrecinct } = require('./arc_gis')
const { getCandidatesForContests, getAllContestIds } = require('./candidate')
const { getPollingPlace } = require('./polling_place')
const STATIC_AMENDMENTS = require('./../data/static_amendments.json')

function getDistrictInfo(dp) {
  return getPrecinct(dp).then(results => {
    let pollingId = ''
    let contestsFromAllDistricts = results.map(result => {
      pollingId = result.attributes.PollingID
      return result.attributes.Contests.split('-')
    })

    let amendmentsFromAllDistricts = results.map(result => {
      return result.attributes.Amendments.split('-')
    })

    const allContests = [].concat.apply([], contestsFromAllDistricts)
    const allAmendmentContestIds = [].concat.apply([], amendmentsFromAllDistricts)

    const allCandidateContests = allContests.filter(contestId => {
      return allAmendmentContestIds.indexOf(contestId) < 0
    })

    return {
      pollingId: pollingId,
      contestIds: allCandidateContests,
      amendmentIds: allAmendmentContestIds,
    }
  })
}

function getCandidatesMappedIntoContests(contestIds) {
  const candidatesForContestsPr = getCandidatesForContests(contestIds)
  return candidatesForContestsPr.then(candidates => {
    var contestIdToCandidates = {}
    candidates.forEach(candidate => {
      const { contest_id } = candidate

      contestIdToCandidates[contest_id] = contestIdToCandidates[contest_id] || []
      contestIdToCandidates[contest_id].push(candidate)
    })

    let contests = []
    contestIds.forEach(contestId => {
      if (contestIdToCandidates[contestId]) {
        contests.push({
          contest_id: contestId,
          candidates: contestIdToCandidates[contestId],
        })
      }
    })

    return contests
  })
}

function getAmendmentsArray() {
  return Promise.resolve(STATIC_AMENDMENTS)
}

function getBallot(districtId) {
  return getDistrictInfo(districtId).then(districtInfo => {
    const {pollingId, contestIds} = districtInfo

    const pollingPlacePr = getPollingPlace(pollingId)
    const contestsWithCandidatesPr = getCandidatesMappedIntoContests(contestIds)
    const amendmentsPr = getAmendmentsArray()

    return Promise.all([pollingPlacePr, contestsWithCandidatesPr, amendmentsPr]).then(results => {
      const ballot = {
        pollingPlace: results[0],
        contests: results[1],
        amendments: results[2],
      }

      return ballot
    })
  })
}

function getStatewideBallot() {
  return getAllContestIds().then(contestIds => {
    let amendments = STATIC_AMENDMENTS
    const contestsWithCandidatesPr = getCandidatesMappedIntoContests(contestIds)
    return contestsWithCandidatesPr.then(contests => {
      const ballot = {
        contests,
        amendments: amendments,
      }
      return ballot
    })
  })
}

module.exports = {
  getBallot,
  getStatewideBallot,
}
<commit_msg>Temporarily remove amendments until the end of the primary<commit_after>"use strict"

const { getPrecinct } = require('./arc_gis')
const { getCandidatesForContests, getAllContestIds } = require('./candidate')
const { getPollingPlace } = require('./polling_place')
const STATIC_AMENDMENTS = require('./../data/static_amendments.json')

function getDistrictInfo(dp) {
  return getPrecinct(dp).then(results => {
    let pollingId = ''
    let contestsFromAllDistricts = results.map(result => {
      pollingId = result.attributes.PollingID
      return result.attributes.Contests.split('-')
    })

    let amendmentsFromAllDistricts = results.map(result => {
      return result.attributes.Amendments.split('-')
    })

    const allContests = [].concat.apply([], contestsFromAllDistricts)
    const allAmendmentContestIds = [].concat.apply([], amendmentsFromAllDistricts)

    const allCandidateContests = allContests.filter(contestId => {
      return allAmendmentContestIds.indexOf(contestId) < 0
    })

    return {
      pollingId: pollingId,
      contestIds: allCandidateContests,
      amendmentIds: allAmendmentContestIds,
    }
  })
}

function getCandidatesMappedIntoContests(contestIds) {
  const candidatesForContestsPr = getCandidatesForContests(contestIds)
  return candidatesForContestsPr.then(candidates => {
    var contestIdToCandidates = {}
    candidates.forEach(candidate => {
      const { contest_id } = candidate

      contestIdToCandidates[contest_id] = contestIdToCandidates[contest_id] || []
      contestIdToCandidates[contest_id].push(candidate)
    })

    let contests = []
    contestIds.forEach(contestId => {
      if (contestIdToCandidates[contestId]) {
        contests.push({
          contest_id: contestId,
          candidates: contestIdToCandidates[contestId],
        })
      }
    })

    return contests
  })
}

function getAmendmentsArray() {
  return Promise.resolve(STATIC_AMENDMENTS)
}

function getBallot(districtId) {
  return getDistrictInfo(districtId).then(districtInfo => {
    const {pollingId, contestIds} = districtInfo

    const pollingPlacePr = getPollingPlace(pollingId)
    const contestsWithCandidatesPr = getCandidatesMappedIntoContests(contestIds)
    const amendmentsPr = getAmendmentsArray()

    return Promise.all([pollingPlacePr, contestsWithCandidatesPr, amendmentsPr]).then(results => {
      const ballot = {
        pollingPlace: results[0],
        contests: results[1],
        // Disabled for the primary
        // amendments: results[2],
        amendments: [],
      }

      return ballot
    })
  })
}

function getStatewideBallot() {
  return getAllContestIds().then(contestIds => {
    let amendments = STATIC_AMENDMENTS
    const contestsWithCandidatesPr = getCandidatesMappedIntoContests(contestIds)
    return contestsWithCandidatesPr.then(contests => {
      const ballot = {
        contests,
        // Disabled for the primary
        // amendments: amendments,
        amendments: []
      }
      return ballot
    })
  })
}

module.exports = {
  getBallot,
  getStatewideBallot,
}
<|endoftext|>


<commit_before>const buster = require("buster")
    , fs     = require("fs.extra")
    , path   = require("path")
    , exec   = require("child_process").exec
    , wrench = require("wrench")

buster.testRunner.timeout = 10000
buster.spec.expose()

var execBinaryCommand = function(cmd, callback) {
  var self = this

  exec(__dirname + '/../bin/jquery.skeleton ' + cmd, {
    cwd: this.sandboxFolder
  }, function(err, stdout, stderr) {
    self.err    = err
    self.stdout = stdout
    self.stderr = stderr

    callback && callback()
  })
}

var copyFile = function(src, dest, callback) {
  fs.copy(src, dest, function(err) {
    if(err) {
      throw err
    } else {
      callback && callback()
    }
  })
}

var update = function(callback) {
  var self = this
}

describe('jquery.skeleton', function() {
  describe('binary', function() {
    before(function(done) {
      this.sandboxFolderName = 'jquery.' + (+new Date())
      this.sandboxFolder     = __dirname + '/sandbox/' + this.sandboxFolderName

      wrench.mkdirSyncRecursive(this.sandboxFolder)
      copyFile(__dirname + '/../package.json', this.sandboxFolder + '/package.json', done)
    })

    after(function() {
      wrench.rmdirSyncRecursive(__dirname + '/sandbox')
    })

    describe('init', function() {
      before(function(done) {
        execBinaryCommand.call(this, 'init', done)
      })

      it("doesn't throw an error", function() {
        expect(this.err).toBeNull()
      })

      it("creates a dist folder", function() {
        expect(path.existsSync(this.sandboxFolder + '/dist')).toBeTrue()
      })

      it("creates a lib folder", function() {
        expect(path.existsSync(this.sandboxFolder + '/lib')).toBeTrue()
      })

      it("creates a spec folder", function() {
        expect(path.existsSync(this.sandboxFolder + '/spec')).toBeTrue()
      })

      it("creates a src folder", function() {
        expect(path.existsSync(this.sandboxFolder + '/src')).toBeTrue()
      })

      it("adds busterjs to the package.json", function() {
        var packageContent = fs.readFileSync(this.sandboxFolder + '/package.json').toString()
          , packageJSON    = JSON.parse(packageContent)

        expect(packageJSON.devDependencies.buster).toBeDefined()
      })

      it("sets the test command in the package.json", function() {
        var packageContent = fs.readFileSync(this.sandboxFolder + '/package.json').toString()
          , packageJSON    = JSON.parse(packageContent)

        expect(packageJSON.scripts.test).toMatch(/.*minify.*buster-test/)
        expect(packageJSON.scripts.minify).toMatch(/.*compiler\.jar/)
        expect(packageJSON.scripts.minify.indexOf("sed -e 's/.*jquery\\.//'`.min.js")).not.toEqual(-1)
      })

      it("adds the buster.js to the spec folder", function() {
        expect(path.existsSync(this.sandboxFolder + '/spec/buster.js')).toBeTrue()
      })

      it("adds the compiler.jar to the dist folder", function() {
        expect(path.existsSync(this.sandboxFolder + '/dist/compiler.jar')).toBeTrue()
      })

      it("adds the minified version of jquery to the lib folder", function() {
        expect(path.existsSync(this.sandboxFolder + '/lib/jquery-1.7.2.min.js')).toBeTrue()
      })

      it("adds the travis setup file to the target project's root", function() {
        expect(path.existsSync(this.sandboxFolder + '/.travis.yml')).toBeTrue()
      })

      describe('spec file', function() {
        before(function() {
          this.filePath = this.sandboxFolder + '/spec/' + this.sandboxFolderName + '.spec.js'
        })

        it("adds a dummy spec file", function() {
          expect(path.existsSync(this.filePath)).toBeTrue()
        })

        it("removes all occurrences of jquery.skeleton", function() {
          var specContent = fs.readFileSync(this.filePath).toString()
          expect(specContent.indexOf('jquery.skeleton')).toEqual(-1)
        })

        it("adds the project name", function() {
          var specContent = fs.readFileSync(this.filePath).toString()
          expect(specContent.indexOf(this.sandboxFolderName)).not.toEqual(-1)
        })
      })

      describe('spec file', function() {
        before(function() {
          this.filePath = this.sandboxFolder + '/src/' + this.sandboxFolderName + '.js'
        })

        it("adds a dummy src file", function() {
          expect(path.existsSync(this.filePath)).toBeTrue()
        })

        it("removes all occurrences of jquery.skeleton", function() {
          var specContent = fs.readFileSync(this.filePath).toString()
          expect(specContent.indexOf('jquery.skeleton')).toEqual(-1)
        })

        it("adds the project name", function() {
          var specContent = fs.readFileSync(this.filePath).toString()
          expect(specContent.indexOf(this.sandboxFolderName.replace('jquery.', '$.fn.'))).not.toEqual(-1)
        })
      })
    })

    describe('update', function() {
      before(function(done) {
        var self = this

        execBinaryCommand.call(this, 'init', function() {
          var packageContent = fs.readFileSync(self.sandboxFolder + '/package.json').toString()
            , packageJSON    = JSON.parse(packageContent)

          delete packageJSON.dependencies.buster
          packageJSON.scripts.test = 'foo'

          fs.writeFileSync(self.sandboxFolder + '/package.json', JSON.stringify(packageJSON))

          execBinaryCommand.call(self, 'update', done)
        })
      })

      it("sets the test command in the package.json", function() {
        var packageContent = fs.readFileSync(this.sandboxFolder + '/package.json').toString()
          , packageJSON    = JSON.parse(packageContent)

        expect(packageJSON.scripts.test).toMatch(/.*minify.*buster-test/)
        expect(packageJSON.scripts.minify).toMatch(/.*compiler\.jar/)
        expect(packageJSON.scripts.minify.indexOf("sed -e 's/.*jquery\\.//'`.min.js")).not.toEqual(-1)
      })

      it("adds buster to the dev dependency list", function() {
        var packageContent = fs.readFileSync(this.sandboxFolder + '/package.json').toString()
          , packageJSON    = JSON.parse(packageContent)

        expect(packageJSON.devDependencies.buster).toBeDefined()
      })
    })

    describe('license', function() {
      before(function(done) {
        execBinaryCommand.call(this, 'init --license', done)
      })

      it("adds the MIT-LICENSE file", function() {
        expect(path.existsSync(this.sandboxFolder + '/MIT-LICENSE')).toBeTrue()
      })

      it("adds a hint for the MIT license to the readme", function() {
        var readme = fs.readFileSync(this.sandboxFolder + '/README.md').toString()

        expect(readme.indexOf('## License')).not.toEqual(-1)
        expect(readme.indexOf('Hereby placed under MIT license.')).not.toEqual(-1)
      })
    })
  })
})
<commit_msg>use fs instead of path<commit_after>const buster = require("buster")
    , fs     = require("fs.extra")
    , exec   = require("child_process").exec
    , wrench = require("wrench")

buster.testRunner.timeout = 10000
buster.spec.expose()

var execBinaryCommand = function(cmd, callback) {
  var self = this

  exec(__dirname + '/../bin/jquery.skeleton ' + cmd, {
    cwd: this.sandboxFolder
  }, function(err, stdout, stderr) {
    self.err    = err
    self.stdout = stdout
    self.stderr = stderr

    callback && callback()
  })
}

var copyFile = function(src, dest, callback) {
  fs.copy(src, dest, function(err) {
    if(err) {
      throw err
    } else {
      callback && callback()
    }
  })
}

var update = function(callback) {
  var self = this
}

describe('jquery.skeleton', function() {
  describe('binary', function() {
    before(function(done) {
      this.sandboxFolderName = 'jquery.' + (+new Date())
      this.sandboxFolder     = __dirname + '/sandbox/' + this.sandboxFolderName

      wrench.mkdirSyncRecursive(this.sandboxFolder)
      copyFile(__dirname + '/../package.json', this.sandboxFolder + '/package.json', done)
    })

    after(function() {
      wrench.rmdirSyncRecursive(__dirname + '/sandbox')
    })

    describe('init', function() {
      before(function(done) {
        execBinaryCommand.call(this, 'init', done)
      })

      it("doesn't throw an error", function() {
        expect(this.err).toBeNull()
      })

      it("creates a dist folder", function() {
        expect(fs.existsSync(this.sandboxFolder + '/dist')).toBeTrue()
      })

      it("creates a lib folder", function() {
        expect(fs.existsSync(this.sandboxFolder + '/lib')).toBeTrue()
      })

      it("creates a spec folder", function() {
        expect(fs.existsSync(this.sandboxFolder + '/spec')).toBeTrue()
      })

      it("creates a src folder", function() {
        expect(fs.existsSync(this.sandboxFolder + '/src')).toBeTrue()
      })

      it("adds busterjs to the package.json", function() {
        var packageContent = fs.readFileSync(this.sandboxFolder + '/package.json').toString()
          , packageJSON    = JSON.parse(packageContent)

        expect(packageJSON.devDependencies.buster).toBeDefined()
      })

      it("sets the test command in the package.json", function() {
        var packageContent = fs.readFileSync(this.sandboxFolder + '/package.json').toString()
          , packageJSON    = JSON.parse(packageContent)

        expect(packageJSON.scripts.test).toMatch(/.*minify.*buster-test/)
        expect(packageJSON.scripts.minify).toMatch(/.*compiler\.jar/)
        expect(packageJSON.scripts.minify.indexOf("sed -e 's/.*jquery\\.//'`.min.js")).not.toEqual(-1)
      })

      it("adds the buster.js to the spec folder", function() {
        expect(fs.existsSync(this.sandboxFolder + '/spec/buster.js')).toBeTrue()
      })

      it("adds the compiler.jar to the dist folder", function() {
        expect(fs.existsSync(this.sandboxFolder + '/dist/compiler.jar')).toBeTrue()
      })

      it("adds the minified version of jquery to the lib folder", function() {
        expect(fs.existsSync(this.sandboxFolder + '/lib/jquery-1.7.2.min.js')).toBeTrue()
      })

      it("adds the travis setup file to the target project's root", function() {
        expect(fs.existsSync(this.sandboxFolder + '/.travis.yml')).toBeTrue()
      })

      describe('spec file', function() {
        before(function() {
          this.filePath = this.sandboxFolder + '/spec/' + this.sandboxFolderName + '.spec.js'
        })

        it("adds a dummy spec file", function() {
          expect(fs.existsSync(this.filePath)).toBeTrue()
        })

        it("removes all occurrences of jquery.skeleton", function() {
          var specContent = fs.readFileSync(this.filePath).toString()
          expect(specContent.indexOf('jquery.skeleton')).toEqual(-1)
        })

        it("adds the project name", function() {
          var specContent = fs.readFileSync(this.filePath).toString()
          expect(specContent.indexOf(this.sandboxFolderName)).not.toEqual(-1)
        })
      })

      describe('spec file', function() {
        before(function() {
          this.filePath = this.sandboxFolder + '/src/' + this.sandboxFolderName + '.js'
        })

        it("adds a dummy src file", function() {
          expect(fs.existsSync(this.filePath)).toBeTrue()
        })

        it("removes all occurrences of jquery.skeleton", function() {
          var specContent = fs.readFileSync(this.filePath).toString()
          expect(specContent.indexOf('jquery.skeleton')).toEqual(-1)
        })

        it("adds the project name", function() {
          var specContent = fs.readFileSync(this.filePath).toString()
          expect(specContent.indexOf(this.sandboxFolderName.replace('jquery.', '$.fn.'))).not.toEqual(-1)
        })
      })
    })

    describe('update', function() {
      before(function(done) {
        var self = this

        execBinaryCommand.call(this, 'init', function() {
          var packageContent = fs.readFileSync(self.sandboxFolder + '/package.json').toString()
            , packageJSON    = JSON.parse(packageContent)

          delete packageJSON.dependencies.buster
          packageJSON.scripts.test = 'foo'

          fs.writeFileSync(self.sandboxFolder + '/package.json', JSON.stringify(packageJSON))

          execBinaryCommand.call(self, 'update', done)
        })
      })

      it("sets the test command in the package.json", function() {
        var packageContent = fs.readFileSync(this.sandboxFolder + '/package.json').toString()
          , packageJSON    = JSON.parse(packageContent)

        expect(packageJSON.scripts.test).toMatch(/.*minify.*buster-test/)
        expect(packageJSON.scripts.minify).toMatch(/.*compiler\.jar/)
        expect(packageJSON.scripts.minify.indexOf("sed -e 's/.*jquery\\.//'`.min.js")).not.toEqual(-1)
      })

      it("adds buster to the dev dependency list", function() {
        var packageContent = fs.readFileSync(this.sandboxFolder + '/package.json').toString()
          , packageJSON    = JSON.parse(packageContent)

        expect(packageJSON.devDependencies.buster).toBeDefined()
      })
    })

    describe('license', function() {
      before(function(done) {
        execBinaryCommand.call(this, 'init --license', done)
      })

      it("adds the MIT-LICENSE file", function() {
        expect(fs.existsSync(this.sandboxFolder + '/MIT-LICENSE')).toBeTrue()
      })

      it("adds a hint for the MIT license to the readme", function() {
        var readme = fs.readFileSync(this.sandboxFolder + '/README.md').toString()

        expect(readme.indexOf('## License')).not.toEqual(-1)
        expect(readme.indexOf('Hereby placed under MIT license.')).not.toEqual(-1)
      })
    })
  })
})
<|endoftext|>