<commit_before>/*
 Copyright (c) 2015 GFT Appverse, S.L., Sociedad Unipersonal.
 This Source Code Form is subject to the terms of the Appverse Public License
 Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this
 file, You can obtain one at http://www.appverse.mobi/licenses/apl_v2.0.pdf.
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the conditions of the AppVerse Public License v2.0
 are met.
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, IN NO EVENT
 SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

angular.module('App.Controllers')

.controller('simpleIDBController', ['$scope', '$rootScope', '$stateParams', '$log', 'IDBService',
    function ($scope, $rootScope, $stateParams, $log, IDBService) {
        'use strict';

        if ($stateParams.key) {
            IDBService.getDefault(Number($stateParams.key)).then(function (note) {
                $scope.note = note;
                $scope.tagString = "";

                if (note.tags.length) $scope.tagString = note.tags.join(",");
            });
        }

        $scope.clearForm = function () {
            $scope.note.title = "";
            $scope.note.body = "";
            $scope.tagString = "";
            $scope.note.id = "";
        };

        $scope.saveNote = function () {
            var item = new IDBService.item(
                $scope.note.id,
                $scope.note.title,
                $scope.note.body,
                //$scope.note.tags
                $scope.tagString
            );

            IDBService.saveDefault(item).then(function () {
                getNotes();
            });

        };

        function getNotes() {
            IDBService.getDefaults().then(function (res) {
                $scope.notes = res;
            });
        }

        $scope.loadNote = function (key) {
            IDBService.getDefault(key).then(function (note) {
                $scope.note = note;
                $scope.tagString = note.tags;
                $scope.noteSelected = true;
            });
        };

        $scope.deleteNote = function (key) {
            IDBService.deleteDefault(key).then(function () {
                getNotes();
            });
        };

        if (IDBService.isSupported()) {
            getNotes();
        } else {
            $log.error("The HTML5 spec for Indexed DB is not supported in ths browser.");
        }

        IDBService.getDefaults().then(function (res) {
            if(!res.length) {
                createMultipleItems(4, res, createDefaultItem);
            }
        });

        function createMultipleItems(num, data, callback) {
            if(!num) { return; }

            if(typeof callback === 'function') {
                for(var i = 1; i<=num; i++) {
                    callback(i, data);
                }
            }
        }

        function createDefaultItem(num, res) {
            $scope.note = res;

            var item = new IDBService.item(
                $scope.note.id,
                $scope.note.title = 'IndexedDB ' + num,
                $scope.note.body = 'Description ' + num
            );

            IDBService.saveDefault(item).then(function () {
                getNotes();
            });

            $scope.clearForm();
        }

    }]);
<commit_msg>Amend code that displays 4 rows of items by default if IndexedDB is empty.<commit_after>/*
 Copyright (c) 2015 GFT Appverse, S.L., Sociedad Unipersonal.
 This Source Code Form is subject to the terms of the Appverse Public License
 Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this
 file, You can obtain one at http://www.appverse.mobi/licenses/apl_v2.0.pdf.
 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the conditions of the AppVerse Public License v2.0
 are met.
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, IN NO EVENT
 SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

angular.module('App.Controllers')

.controller('simpleIDBController', ['$scope', '$rootScope', '$stateParams', '$log', 'IDBService',
    function ($scope, $rootScope, $stateParams, $log, IDBService) {
        'use strict';

        if ($stateParams.key) {
            IDBService.getDefault(Number($stateParams.key)).then(function (note) {
                $scope.note = note;
                $scope.tagString = "";

                if (note.tags.length) $scope.tagString = note.tags.join(",");
            });
        }

        $scope.clearForm = function () {
            $scope.note.title = "";
            $scope.note.body = "";
            $scope.tagString = "";
            $scope.note.id = "";
        };

        $scope.saveNote = function () {
            var item = new IDBService.item(
                $scope.note.id,
                $scope.note.title,
                $scope.note.body,
                //$scope.note.tags
                $scope.tagString
            );

            IDBService.saveDefault(item).then(function () {
                getNotes();
            });

        };

        function getNotes() {
            IDBService.getDefaults().then(function (res) {
                $scope.notes = res;
            });
        }

        $scope.loadNote = function (key) {
            IDBService.getDefault(key).then(function (note) {
                $scope.note = note;
                $scope.tagString = note.tags;
                $scope.noteSelected = true;
            });
        };

        $scope.deleteNote = function (key) {
            IDBService.deleteDefault(key).then(function () {
                getNotes();
            });
        };

        if (IDBService.isSupported()) {
            getNotes();
        } else {
            $log.error("The HTML5 spec for Indexed DB is not supported in ths browser.");
        }

        IDBService.getDefaults().then(function (res) {
            if(!res.length) {
                createMultipleItems(4, res, createDefaultItem);
            }
        });

        function createMultipleItems(num, data, callback) {
            if(!num) { return; }

            if(typeof callback === 'function') {
                for(var i = 1; i<=num; i++) {
                    callback(i, data);
                }
                getNotes();
            }
        }

        function createDefaultItem(num, res) {
            var item = new IDBService.item(
                res.id = null,
                res.title = 'IndexedDB ' + num,
                res.body = 'Description ' + num
            );

            IDBService.saveDefault(item);
        }

    }]);
<|endoftext|>


<commit_before>/** @babel */

import childProcess from 'child_process'
import kill from 'tree-kill'
import { Disposable } from 'atom'

export default class ProcessManager extends Disposable {
  processes = new Set()

  constructor () {
    super(() => this.killChildProcesses())
  }

  executeChildProcess (command, options = {}) {
    const { allowKill, showError, ...execOptions } = options
    return new Promise(resolve => {
      // Windows does not like \$ appearing in command lines so only escape
      // if we need to.
      if (process.platform !== 'win32') command = command.replace('$', '\\$')
      const { pid } = childProcess.exec(command, execOptions, (error, stdout, stderr) => {
        if (allowKill) {
          this.processes.delete(pid)
        }
        if (error && showError) {
          latex.log.error(`An error occurred while trying to run "${command}" (${error.code}).`)
        }
        resolve({
          statusCode: error ? error.code : 0,
          stdout,
          stderr
        })
      })
      if (allowKill) {
        this.processes.add(pid)
      }
    })
  }

  killChildProcesses () {
    for (const pid of this.processes.values()) {
      kill(pid)
    }
    this.processes.clear()
  }
}
<commit_msg>Add guard to process error log<commit_after>/** @babel */

import childProcess from 'child_process'
import kill from 'tree-kill'
import { Disposable } from 'atom'

export default class ProcessManager extends Disposable {
  processes = new Set()

  constructor () {
    super(() => this.killChildProcesses())
  }

  executeChildProcess (command, options = {}) {
    const { allowKill, showError, ...execOptions } = options
    return new Promise(resolve => {
      // Windows does not like \$ appearing in command lines so only escape
      // if we need to.
      if (process.platform !== 'win32') command = command.replace('$', '\\$')
      const { pid } = childProcess.exec(command, execOptions, (error, stdout, stderr) => {
        if (allowKill) {
          this.processes.delete(pid)
        }
        if (error && showError && latex && latex.log) {
          latex.log.error(`An error occurred while trying to run "${command}" (${error.code}).`)
        }
        resolve({
          statusCode: error ? error.code : 0,
          stdout,
          stderr
        })
      })
      if (allowKill) {
        this.processes.add(pid)
      }
    })
  }

  killChildProcesses () {
    for (const pid of this.processes.values()) {
      kill(pid)
    }
    this.processes.clear()
  }
}
<|endoftext|>


<commit_before>"use strict";

const React = require("react");
const PropTypes = require("prop-types");
const AnimatedLogo = require("@sandhose/prettier-animated-logo");
const { MarkdownBlock, Container } = require("../../core/CompLibrary.js");

const siteConfig = require(process.cwd() + "/siteConfig.js");

const ButtonGroup = (props) => (

{props.children}

);

ButtonGroup.propTypes = {
  children: PropTypes.node,
};

class Button extends React.Component {
  render() {
    return (

          {this.props.children}

    );
  }
}

Button.defaultProps = {
  target: "_self",
};

Button.propTypes = {
  href: PropTypes.string,
  target: PropTypes.string,
  children: PropTypes.any,
};

function Tidelift() {
  return (

      PRETTIER FOR ENTERPRISE

  );
}

const HomeSplash = (props) => {
  return (

      <Tidelift />

            <AnimatedLogo version="wide" />

                  <Button href="/playground/">Try It Online</Button>
                  <Button href={"/docs/" + props.language + "/install.html"}>
                    Install Prettier
                  </Button>

  );
};

HomeSplash.propTypes = {
  language: PropTypes.string,
};

const TldrSection = ({ language }) => (

    <Container>

What is Prettier?

An opinionated code formatter

Supports many languages

Integrates with most editors

Has few options

Why?

You press save and code is formatted

No need to discuss style in code review

Saves you time and energy

              And more

    </Container>

);

TldrSection.propTypes = {
  language: PropTypes.string,
};

const Language = ({ name, nameLink, showName, image, variants }) => (

      {showName && (

          {nameLink ? {name} : name}

      )}
      {variants.map((variant) => (

          <MarkdownBlock>{variant}</MarkdownBlock>

      ))}

);

Language.propTypes = {
  name: PropTypes.string,
  nameLink: PropTypes.string,
  showName: PropTypes.bool,
  image: PropTypes.string,
  variants: PropTypes.array,
};

const LanguagesSection = () => {
  const languageChunks = siteConfig.supportedLanguages.reduce(
    (acc, language) => {
      const last = acc[acc.length - 1];
      if (
        last &&
        last.length < 2 &&
        last.reduce((sum, lang) => sum + lang.variants.length, 0) +
          language.variants.length <
          9
      ) {
        last.push(language);
      } else {
        acc.push([language]);
      }
      return acc;
    },
    []
  );

  return (

      <Container>

Works with the Tools You Use

          {languageChunks.map((languageChunk, index) => (

              {languageChunk.map((language) => (
                <Language key={language.name} {...language} />
              ))}

          ))}

      </Container>

  );
};

const Editor = ({ content = "", image, name }) => (

{name}

      <MarkdownBlock>{content.replace(/\n/g, "  \n")}</MarkdownBlock>

);

Editor.propTypes = {
  content: PropTypes.string,
  image: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
};

const EditorSupportSection = () => (

    <Container>

Editor Support

        {siteConfig.editors.map((editor) => (
          <Editor key={editor.name} {...editor} />
        ))}

    </Container>

      Got more?
      <a
        href={`${siteConfig.githubUrl}/edit/master/website/data/editors.yml`}
        className="button"
      >
        Send a PR

);

const UsersSection = ({ language }) => {
  const showcase = siteConfig.users
    .filter((user) => {
      return user.pinned;
    })
    .map((user, i) => {
      return (

      );
    });

  return (

      <Container>

Used By People You Rely On

          {showcase}

            See All Others

          <a
            className="button"
            href={`${siteConfig.githubUrl}/edit/master/website/data/users.yml`}
          >
            Add Your Project

Established in the Ecosystem

                More than{" "}
                1.8 million{" "}
                dependent repositories on GitHub

              <Button href="https://github.com/prettier/prettier/network/dependents">
                Check Them Out
              </Button>

                More than 5000{" "}
                dependent packages on npm

              <Button href="https://www.npmjs.com/browse/depended/prettier">
                See them all
              </Button>

      </Container>

  );
};

UsersSection.propTypes = {
  language: PropTypes.string,
};

class Index extends React.Component {
  render() {
    const language = this.props.language || "en";

    return (


<commit_before>'use strict';

angular.module('ximsApp')
  .controller('EmployeeListCtrl',
    ['$scope', '$filter', '$rootScope', 'ModuleService', 'UserService','EmployeeService', 'AppSettings',
      function($scope, $filter, $rootScope, ModuleService, UserService, EmployeeService, AppSettings) {
    ModuleService.name = ModuleService.EMPLOYEE;
    $scope.employees = [];
    $scope.employeesCache = [];
    $scope.meta = {};
    $scope.totalItems = 0;
    $scope.currentPage = 0;
    $scope.searchText = "";
    $scope.searchingEmployees = true;
    $scope.maxSize = AppSettings.pagination.maxSize;
    $scope.itemsPerPage = AppSettings.pagination.itemsPerPage;

    $scope.setEmployees = function(page) {
      if($scope.searchText == "")
        EmployeeService.getAll(page).success(successResponse);
      else
        EmployeeService.search($scope.searchText, page).success(successResponse);
    }

    $scope.search = function() {
      if($scope.searchingEmployees) { return; }
      if($scope.searchText == "") { $scope.setEmployees(); return; }
      $scope.searchingEmployees = true;
      EmployeeService.search($scope.searchText).success(successResponse);
    }

    $scope.$watch("searchText", function(newVal) {
      setEmployeesFiltered(newVal);
    });

    function setEmployeesFiltered(newVal) {
      var result = $filter('filter')($scope.employeesCache, newVal);
      if(result.length) { $scope.employees = result; }
      else { $scope.employees = $scope.employeesCache; }
    }

    function successResponse(response) {
      $scope.employees = response.data;
      $scope.employeesCache = response.data;
      $scope.totalItems = response.meta.total_items;
      $scope.currentPage = response.meta.current_page;
      $scope.searchingEmployees = false;
    }

    $rootScope.$on('userLogged', function() { $scope.setEmployees(); });
    if(UserService.currentUser) { $scope.setEmployees(); }
  }])
  .controller('EmployeeCtrl', function(ModuleService, $routeParams, $scope) {
    ModuleService.name = ModuleService.EMPLOYEE;
    // $scope.employee = $routeParams.employeeId;
    $scope.employee = {id:1,
      displayName: 'Juan Perez', dni: 45996136,
      workingArea: 'Chancado', age: 35,
      riskInsurance: {expirationDate: '12/12/14'},
      medicalExamination: {expirationDate: '10/06/14'},
      occupation: 'Perforista'
    };
  })
  .controller('EmployeeUpdateCtrl', function(ModuleService, $routeParams, $scope) {
    ModuleService.name = ModuleService.EMPLOYEE;
    // $scope.employee = $routeParams.employeeId;
    $scope.employee = {id:1,
      displayName: 'Juan Perez', dni: 45996136,
      workingArea: 'Chancado', age: 35,
      riskInsurance: {expirationDate: '12/12/14'},
      medicalExamination: {expirationDate: '10/06/14'}};
  });<commit_msg>adding hidePagination to employeesCtrl<commit_after>'use strict';

angular.module('ximsApp')
  .controller('EmployeeListCtrl',
    ['$scope', '$filter', '$rootScope', 'ModuleService', 'UserService','EmployeeService', 'AppSettings',
      function($scope, $filter, $rootScope, ModuleService, UserService, EmployeeService, AppSettings) {
    ModuleService.name = ModuleService.EMPLOYEE;
    $scope.employees = [];
    $scope.employeesCache = [];
    $scope.meta = {};
    $scope.totalItems = 0;
    $scope.currentPage = 0;
    $scope.searchText = "";
    $scope.searchingEmployees = true;
    $scope.maxSize = AppSettings.pagination.maxSize;
    $scope.itemsPerPage = AppSettings.pagination.itemsPerPage;

    $scope.setEmployees = function(page) {
      if($scope.searchText == "")
        EmployeeService.getAll(page).success(successResponse);
      else
        EmployeeService.search($scope.searchText, page).success(successResponse);
    }

    $scope.search = function() {
      if($scope.searchingEmployees) { return; }
      if($scope.searchText == "") { $scope.setEmployees(); return; }
      $scope.searchingEmployees = true;
      EmployeeService.search($scope.searchText).success(successResponse);
    }

    $scope.$watch("searchText", function(newVal) {
      setEmployeesFiltered(newVal);
    });

    $scope.hidePagination = function() {
      if($scope.employees.length > 0) { return false; }
      else if ($scope.searchingEmployees) { return true; }
      else { return true; }
    }

    function setEmployeesFiltered(newVal) {
      var result = $filter('filter')($scope.employeesCache, newVal);
      if(result.length) { $scope.employees = result; }
      else { $scope.employees = $scope.employeesCache; }
    }

    function successResponse(response) {
      $scope.employees = response.data;
      $scope.employeesCache = response.data;
      $scope.totalItems = response.meta.total_items;
      $scope.currentPage = response.meta.current_page;
      $scope.searchingEmployees = false;
    }

    $rootScope.$on('userLogged', function() { $scope.setEmployees(); });
    if(UserService.currentUser) { $scope.setEmployees(); }
  }])
  .controller('EmployeeCtrl', function(ModuleService, $routeParams, $scope) {
    ModuleService.name = ModuleService.EMPLOYEE;
    // $scope.employee = $routeParams.employeeId;
    $scope.employee = {id:1,
      displayName: 'Juan Perez', dni: 45996136,
      workingArea: 'Chancado', age: 35,
      riskInsurance: {expirationDate: '12/12/14'},
      medicalExamination: {expirationDate: '10/06/14'},
      occupation: 'Perforista'
    };
  })
  .controller('EmployeeUpdateCtrl', function(ModuleService, $routeParams, $scope) {
    ModuleService.name = ModuleService.EMPLOYEE;
    // $scope.employee = $routeParams.employeeId;
    $scope.employee = {id:1,
      displayName: 'Juan Perez', dni: 45996136,
      workingArea: 'Chancado', age: 35,
      riskInsurance: {expirationDate: '12/12/14'},
      medicalExamination: {expirationDate: '10/06/14'}};
  });<|endoftext|>


<commit_before>"use strict";

const Base = require("./Base");
const Call = require("./Call");
const SystemJoinMessages = require("../Constants").SystemJoinMessages;
const User = require("./User");

/**
* Represents a message
* @prop {String} id The ID of the message
* @prop {Channel} channel The channel the message is in
* @prop {Number} timestamp Timestamp of message creation
* @prop {Number} type The type of the message
* @prop {User} author The message author
* @prop {Member?} member The message author with server-specific data
* @prop {User[]} mentions Array of mentioned users
* @prop {String} content Message content
* @prop {String?} cleanContent Message content with mentions replaced by names, and @everyone/@here escaped
* @prop {String[]} roleMentions Array of mentioned roles' ids
* @prop {String[]?} channelMentions Array of mentions channels' ids
* @prop {Number?} editedTimestamp Timestamp of latest message edit
* @prop {Boolean} tts Whether to play the message using TTS or not
* @prop {Boolean} mentionEveryone Whether the message mentions everyone/here or not
* @prop {Object[]} attachments Array of attachments
* @prop {Object[]} embeds Array of embeds
* @prop {Object} reactions An object containing the reactions on the message
* @prop {Number} reactions.count The number of times the reaction was used
* @prop {Boolean} reactions.me Whether or not the bot user did the reaction
* @prop {Boolean} command True if message is a command, false if not (CommandClient only)
*/
class Message extends Base {
    constructor(data, client) {
        super(data.id);
        this._client = client;
        this.type = data.type || 0;
        this.timestamp = Date.parse(data.timestamp);
        this.channel = client.getChannel(data.channel_id) || {
            id: data.channel_id
        };
        this.content = "";
        this.hit = !!data.hit;
        this.reactions = {};
        if(data.author) {
            if(data.author.discriminator !== "0000") {
                this.author = client.users.add(data.author, client);
            } else {
                this.author = new User(data.author, client);
            }
        } else if(data.timestamp) {
            this._client.emit("error", "MESSAGE_CREATE but no message author:\n" + JSON.stringify(data, null, 2));
        }
        if(this.type === 0 || this.type === undefined);
        else if(this.type === 1) {
            data.content = `${this.author.mention} added <@${data.mentions[0].id}>.`;
        } else if(this.type === 2) {
            if(this.author.id === data.mentions[0].id) {
                data.content = `@${this.author.username} left the group.`;
            } else {
                data.content = `${this.author.mention} removed @${data.mentions[0].username}.`;
            }
        } else if(this.type === 3) { // (╯°□°）╯︵ ┻━┻
            if(data.call.ended_timestamp) {
                if((!this.channel.lastCall || this.channel.lastCall.endedTimestamp < Date.parse(data.call.ended_timestamp))) {
                    data.call.id = this.id;
                    this.channel.lastCall = new Call(data.call, this.channel);
                }
                if(~data.call.participants.indexOf(client.user.id)) {
                    data.content = `You missed a call from ${this.author.mention}.`;
                } else {
                    data.content = `${this.author.mention} started a call.`;
                }
            } else {
                if(!this.channel.call) {
                    data.call.id = this.id;
                    this.channel.call = new Call(data.call, this.channel);
                }
                data.content = `${this.author.mention} started a call. — Join the call.`;
            }
        } else if(this.type === 4) {
            data.content = `${this.author.mention} changed the channel name: ${data.content}`;
        } else if(this.type === 5) {
            data.content = `${this.author.mention} changed the channel icon.`;
        } else if(this.type === 6) {
            data.content = `${this.author.mention} pinned a message to this channel. See all the pins.`;
        } else if(this.type === 7) {
            data.content = SystemJoinMessages[~~(this.createdAt % SystemJoinMessages.length)].replace(/%user%/g, this.author.mention);
        } else {
            throw new Error("Unhandled MESSAGE_CREATE type: " + JSON.stringify(data, null, 2));
        }

        this.update(data, client);
    }

    update(data, client) {
        if(this.type === 3) { // (╯°□°）╯︵ ┻━┻
            (this.channel.call || this.channel.lastCall).update(data.call);
        }
        if(data.content !== undefined) {
            this.content = data.content || "";
            this._cleanContent = null;
            this.mentionEveryone = !!data.mention_everyone;

            this.mentions = data.mentions.map((mention) => client.users.add(mention, client));

            this.roleMentions = data.mention_roles;
        }

        this.pinned = data.pinned !== undefined ? !!data.pinned : this.pinned;
        this.editedTimestamp = data.edited_timestamp !== undefined ? Date.parse(data.edited_timestamp) : this.editedTimestamp;
        this.tts = data.tts !== undefined ? data.tts : this.tts;
        this.attachments = data.attachments !== undefined ? data.attachments : this.attachments; // TODO parse attachments
        this.embeds = data.embeds !== undefined ? data.embeds : this.embeds; // TODO parse embeds

        if(data.reactions) {
            data.reactions.forEach((reaction) => {
                this.reactions[reaction.emoji.id ? `${reaction.emoji.name}:${reaction.emoji.id}` : reaction.emoji.name] = {
                    count: reaction.count,
                    me: reaction.me
                };
            });
        }
    }

    get cleanContent() {
        if(this._cleanContent) {
            return this._cleanContent;
        }

        this._cleanContent = this.content;

        if(this.mentions) {
            this.mentions.forEach((mention) => {
                if(this.channel.guild) {
                    var member = this.channel.guild.members.get(mention.id);
                    if(member) {
                        this._cleanContent = this._cleanContent.replace(new RegExp(`<@!${mention.id}>`, "g"), "@" + member.nick || mention.username);
                    }
                }
                this._cleanContent = this._cleanContent.replace(new RegExp(`<@!?${mention.id}>`, "g"), "@" + mention.username);
            });
        }

        if(this.channel.guild && this.roleMentions) {
            for(var roleID of this.roleMentions) {
                var role = this.channel.guild.roles.get(roleID);
                var roleName = role ? role.name : "deleted-role";
                this._cleanContent = this._cleanContent.replace(new RegExp(`<@&${roleID}>`, "g"), "@" + roleName);
            }
        }

        this.channelMentions.forEach((id) => {
            var channel = this._client.getChannel(id);
            if(channel && channel.name && channel.mention) {
                this._cleanContent = this._cleanContent.replace(channel.mention, "#" + channel.name);
            }
        });

        return (this._cleanContent = this._cleanContent.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere"));
    }

    get channelMentions() {
        if(this._channelMentions) {
            return this._channelMentions;
        }

        return (this._channelMentions = (this.content.match(/<#[0-9]+>/g) || []).map((mention) => mention.substring(2, mention.length - 1)));
    }

    get member() {
        return this.channel.guild && this.author && this.channel.guild.members.get(this.author.id) || null;
    }

    /**
    * Edit the message
    * @arg {String | Array | Object} content A string, array of strings, or object. If an object is passed:
    * @arg {String} content.content A content string
    * @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
    * @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
    * @returns {Promise<Message>}
    */
    edit(content) {
        return this._client.editMessage.call(this._client, this.channel.id, this.id, content);
    }

    /**
    * Pin the message
    * @returns {Promise}
    */
    pin() {
        return this._client.pinMessage.call(this._client, this.channel.id, this.id);
    }

    /**
    * Unpin the message
    * @returns {Promise}
    */
    unpin() {
        return this._client.unpinMessage.call(this._client, this.channel.id, this.id);
    }

    /**
    * Get a list of users who reacted with a specific reaction
    * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
    * @arg {Number} [limit=100] The maximum number of users to get
    * @returns {Promise<User[]>}
    */
    getReaction(reaction, limit) {
        return this._client.getMessageReaction.call(this._client, this.channel.id, this.id, reaction, limit);
    }

    /**
    * Add a reaction to a message
    * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
    * @arg {String} [userID="@me"] The ID of the user to react as
    * @returns {Promise}
    */
    addReaction(reaction, userID) {
        return this._client.addMessageReaction.call(this._client, this.channel.id, this.id, reaction, userID);
    }

    /**
    * Remove a reaction from a message
    * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
    * @arg {String} [userID="@me"] The ID of the user to remove the reaction for
    * @returns {Promise}
    */
    removeReaction(reaction, userID) {
        return this._client.removeMessageReaction.call(this._client, this.channel.id, this.id, reaction, userID);
    }

    /**
    * Remove all reactions from a message
    * @returns {Promise}
    */
    removeReactions() {
        return this._client.removeMessageReactions.call(this._client, this.channel.id, this.id);
    }

    /**
    * Delete the message
    * @arg {String} [reason] The reason to be displayed in audit logs
    * @returns {Promise}
    */
    delete(reason) {
        return this._client.deleteMessage.call(this._client, this.channel.id, this.id, reason);
    }
}

module.exports = Message;
<commit_msg>Update Message docs<commit_after>"use strict";

const Base = require("./Base");
const Call = require("./Call");
const SystemJoinMessages = require("../Constants").SystemJoinMessages;
const User = require("./User");

/**
* Represents a message
* @prop {String} id The ID of the message
* @prop {Channel} channel The channel the message is in
* @prop {Number} timestamp Timestamp of message creation
* @prop {Number} type The type of the message
* @prop {User} author The message author
* @prop {Member?} member The message author with server-specific data
* @prop {User[]} mentions Array of mentioned users
* @prop {String} content Message content
* @prop {String?} cleanContent Message content with mentions replaced by names, and @everyone/@here escaped
* @prop {String[]} roleMentions Array of mentioned roles' ids
* @prop {String[]?} channelMentions Array of mentions channels' ids
* @prop {Number?} editedTimestamp Timestamp of latest message edit
* @prop {Boolean} tts Whether to play the message using TTS or not
* @prop {Boolean} mentionEveryone Whether the message mentions everyone/here or not
* @prop {Object[]} attachments Array of attachments
* @prop {Object[]} embeds Array of embeds
* @prop {Object} reactions An object containing the reactions on the message
* @prop {Number} reactions.count The number of times the reaction was used
* @prop {Boolean} reactions.me Whether or not the bot user did the reaction
* @prop {Boolean} pinned Whether the message is pinned or not
* @prop {Command?} command The Command used in the Message, if any (CommandClient only)
*/
class Message extends Base {
    constructor(data, client) {
        super(data.id);
        this._client = client;
        this.type = data.type || 0;
        this.timestamp = Date.parse(data.timestamp);
        this.channel = client.getChannel(data.channel_id) || {
            id: data.channel_id
        };
        this.content = "";
        this.hit = !!data.hit;
        this.reactions = {};
        if(data.author) {
            if(data.author.discriminator !== "0000") {
                this.author = client.users.add(data.author, client);
            } else {
                this.author = new User(data.author, client);
            }
        } else if(data.timestamp) {
            this._client.emit("error", "MESSAGE_CREATE but no message author:\n" + JSON.stringify(data, null, 2));
        }
        if(this.type === 0 || this.type === undefined);
        else if(this.type === 1) {
            data.content = `${this.author.mention} added <@${data.mentions[0].id}>.`;
        } else if(this.type === 2) {
            if(this.author.id === data.mentions[0].id) {
                data.content = `@${this.author.username} left the group.`;
            } else {
                data.content = `${this.author.mention} removed @${data.mentions[0].username}.`;
            }
        } else if(this.type === 3) { // (╯°□°）╯︵ ┻━┻
            if(data.call.ended_timestamp) {
                if((!this.channel.lastCall || this.channel.lastCall.endedTimestamp < Date.parse(data.call.ended_timestamp))) {
                    data.call.id = this.id;
                    this.channel.lastCall = new Call(data.call, this.channel);
                }
                if(~data.call.participants.indexOf(client.user.id)) {
                    data.content = `You missed a call from ${this.author.mention}.`;
                } else {
                    data.content = `${this.author.mention} started a call.`;
                }
            } else {
                if(!this.channel.call) {
                    data.call.id = this.id;
                    this.channel.call = new Call(data.call, this.channel);
                }
                data.content = `${this.author.mention} started a call. — Join the call.`;
            }
        } else if(this.type === 4) {
            data.content = `${this.author.mention} changed the channel name: ${data.content}`;
        } else if(this.type === 5) {
            data.content = `${this.author.mention} changed the channel icon.`;
        } else if(this.type === 6) {
            data.content = `${this.author.mention} pinned a message to this channel. See all the pins.`;
        } else if(this.type === 7) {
            data.content = SystemJoinMessages[~~(this.createdAt % SystemJoinMessages.length)].replace(/%user%/g, this.author.mention);
        } else {
            throw new Error("Unhandled MESSAGE_CREATE type: " + JSON.stringify(data, null, 2));
        }

        this.update(data, client);
    }

    update(data, client) {
        if(this.type === 3) { // (╯°□°）╯︵ ┻━┻
            (this.channel.call || this.channel.lastCall).update(data.call);
        }
        if(data.content !== undefined) {
            this.content = data.content || "";
            this._cleanContent = null;
            this.mentionEveryone = !!data.mention_everyone;

            this.mentions = data.mentions.map((mention) => client.users.add(mention, client));

            this.roleMentions = data.mention_roles;
        }

        this.pinned = data.pinned !== undefined ? !!data.pinned : this.pinned;
        this.editedTimestamp = data.edited_timestamp !== undefined ? Date.parse(data.edited_timestamp) : this.editedTimestamp;
        this.tts = data.tts !== undefined ? data.tts : this.tts;
        this.attachments = data.attachments !== undefined ? data.attachments : this.attachments;
        this.embeds = data.embeds !== undefined ? data.embeds : this.embeds;

        if(data.reactions) {
            data.reactions.forEach((reaction) => {
                this.reactions[reaction.emoji.id ? `${reaction.emoji.name}:${reaction.emoji.id}` : reaction.emoji.name] = {
                    count: reaction.count,
                    me: reaction.me
                };
            });
        }
    }

    get cleanContent() {
        if(this._cleanContent) {
            return this._cleanContent;
        }

        this._cleanContent = this.content;

        if(this.mentions) {
            this.mentions.forEach((mention) => {
                if(this.channel.guild) {
                    var member = this.channel.guild.members.get(mention.id);
                    if(member) {
                        this._cleanContent = this._cleanContent.replace(new RegExp(`<@!${mention.id}>`, "g"), "@" + member.nick || mention.username);
                    }
                }
                this._cleanContent = this._cleanContent.replace(new RegExp(`<@!?${mention.id}>`, "g"), "@" + mention.username);
            });
        }

        if(this.channel.guild && this.roleMentions) {
            for(var roleID of this.roleMentions) {
                var role = this.channel.guild.roles.get(roleID);
                var roleName = role ? role.name : "deleted-role";
                this._cleanContent = this._cleanContent.replace(new RegExp(`<@&${roleID}>`, "g"), "@" + roleName);
            }
        }

        this.channelMentions.forEach((id) => {
            var channel = this._client.getChannel(id);
            if(channel && channel.name && channel.mention) {
                this._cleanContent = this._cleanContent.replace(channel.mention, "#" + channel.name);
            }
        });

        return (this._cleanContent = this._cleanContent.replace(/@everyone/g, "@\u200beveryone").replace(/@here/g, "@\u200bhere"));
    }

    get channelMentions() {
        if(this._channelMentions) {
            return this._channelMentions;
        }

        return (this._channelMentions = (this.content.match(/<#[0-9]+>/g) || []).map((mention) => mention.substring(2, mention.length - 1)));
    }

    get member() {
        return this.channel.guild && this.author && this.channel.guild.members.get(this.author.id) || null;
    }

    /**
    * Edit the message
    * @arg {String | Array | Object} content A string, array of strings, or object. If an object is passed:
    * @arg {String} content.content A content string
    * @arg {Boolean} [content.disableEveryone] Whether to filter @everyone/@here or not (overrides default)
    * @arg {Object} [content.embed] An embed object. See [the official Discord API documentation entry](https://discordapp.com/developers/docs/resources/channel#embed-object) for object structure
    * @returns {Promise<Message>}
    */
    edit(content) {
        return this._client.editMessage.call(this._client, this.channel.id, this.id, content);
    }

    /**
    * Pin the message
    * @returns {Promise}
    */
    pin() {
        return this._client.pinMessage.call(this._client, this.channel.id, this.id);
    }

    /**
    * Unpin the message
    * @returns {Promise}
    */
    unpin() {
        return this._client.unpinMessage.call(this._client, this.channel.id, this.id);
    }

    /**
    * Get a list of users who reacted with a specific reaction
    * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
    * @arg {Number} [limit=100] The maximum number of users to get
    * @returns {Promise<User[]>}
    */
    getReaction(reaction, limit) {
        return this._client.getMessageReaction.call(this._client, this.channel.id, this.id, reaction, limit);
    }

    /**
    * Add a reaction to a message
    * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
    * @arg {String} [userID="@me"] The ID of the user to react as
    * @returns {Promise}
    */
    addReaction(reaction, userID) {
        return this._client.addMessageReaction.call(this._client, this.channel.id, this.id, reaction, userID);
    }

    /**
    * Remove a reaction from a message
    * @arg {String} reaction The reaction (Unicode string if Unicode emoji, `emojiName:emojiID` if custom emoji)
    * @arg {String} [userID="@me"] The ID of the user to remove the reaction for
    * @returns {Promise}
    */
    removeReaction(reaction, userID) {
        return this._client.removeMessageReaction.call(this._client, this.channel.id, this.id, reaction, userID);
    }

    /**
    * Remove all reactions from a message
    * @returns {Promise}
    */
    removeReactions() {
        return this._client.removeMessageReactions.call(this._client, this.channel.id, this.id);
    }

    /**
    * Delete the message
    * @arg {String} [reason] The reason to be displayed in audit logs
    * @returns {Promise}
    */
    delete(reason) {
        return this._client.deleteMessage.call(this._client, this.channel.id, this.id, reason);
    }
}

module.exports = Message;
<|endoftext|>


<commit_before><commit_msg>FIO-2729 Changed collapse setter for further extension in VPAT + added keyboard support for panel button<commit_after><|endoftext|>


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

(function() {
  var template_name = "survey";

  melange.template[template_name] = function(_self, context) {
  };

  melange.template[template_name].prototype = new melange.templates._baseTemplate();
  melange.template[template_name].prototype.constructor = melange.template[template_name];
  melange.template[template_name].apply(
    melange.template[template_name],
    [melange.template[template_name], melange.template[template_name].prototype.context]
  );
}());
<commit_msg>Make the skeleton survey JS compatible with the new JS templates.<commit_after>/* Copyright 2011 the Melange authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @author Mario Ferraro
 */

melange.templates.inherit(
  function (_self, context) {
  }
);
<|endoftext|>


<commit_before>import Joi from 'joi';

const stringOrArray = Joi.alternatives().try([
	Joi.string(),
	Joi.array().items(Joi.string()),
]);

export const querySchema = Joi.object({
	endpoint: Joi.string().required(),
	ref: Joi.string().required(),
	flags: Joi.array(),
	mockResponse: Joi.object(),
	params: Joi.object(), // can be FormData
	type: Joi.string(),
	meta: Joi.object({
		method: Joi.string().valid('get', 'post', 'delete', 'patch').insensitive(),
		noCache: Joi.bool(),
		flags: Joi.array(),
		variants: Joi.object().pattern(/\w+/, stringOrArray),
		metaRequestHeaders: Joi.array(),
	}),
});
<commit_msg>allow array for mockResponse<commit_after>import Joi from 'joi';

const stringOrArray = Joi.alternatives().try([
	Joi.string(),
	Joi.array().items(Joi.string()),
]);

export const querySchema = Joi.object({
	endpoint: Joi.string().required(),
	ref: Joi.string().required(),
	flags: Joi.array(),
	mockResponse: [Joi.object(), Joi.array()],
	params: Joi.object(), // can be FormData
	type: Joi.string(),
	meta: Joi.object({
		method: Joi.string().valid('get', 'post', 'delete', 'patch').insensitive(),
		noCache: Joi.bool(),
		flags: Joi.array(),
		variants: Joi.object().pattern(/\w+/, stringOrArray),
		metaRequestHeaders: Joi.array(),
	}),
});
<|endoftext|>


<commit_before>"use strict";

const React = require("react");
const PropTypes = require("prop-types");
const AnimatedLogo = require("@sandhose/prettier-animated-logo");
const { MarkdownBlock, Container } = require("../../core/CompLibrary.js");

const siteConfig = require(process.cwd() + "/siteConfig.js");

const ButtonGroup = (props) => (

{props.children}

);

ButtonGroup.propTypes = {
  children: PropTypes.node,
};

class Button extends React.Component {
  render() {
    return (

          {this.props.children}

    );
  }
}

Button.defaultProps = {
  target: "_self",
};

Button.propTypes = {
  href: PropTypes.string,
  target: PropTypes.string,
  children: PropTypes.any,
};

function Tidelift() {
  return (

      PRETTIER FOR ENTERPRISE

  );
}

const HomeSplash = (props) => (

    <Tidelift />

          <AnimatedLogo version="wide" />

                <Button href="/playground/">Try It Online</Button>
                <Button href={"/docs/" + props.language + "/install.html"}>
                  Install Prettier
                </Button>

);

HomeSplash.propTypes = {
  language: PropTypes.string,
};

const TldrSection = ({ language }) => (

    <Container>

What is Prettier?

An opinionated code formatter

Supports many languages

Integrates with most editors

Has few options

Why?

You press save and code is formatted

No need to discuss style in code review

Saves you time and energy

              And more

    </Container>

);

TldrSection.propTypes = {
  language: PropTypes.string,
};

const Language = ({ name, nameLink, showName, image, variants }) => (

      {showName && (

          {nameLink ? {name} : name}

      )}
      {variants.map((variant) => (

          <MarkdownBlock>{variant}</MarkdownBlock>

      ))}

);

Language.propTypes = {
  name: PropTypes.string,
  nameLink: PropTypes.string,
  showName: PropTypes.bool,
  image: PropTypes.string,
  variants: PropTypes.array,
};

const LanguagesSection = () => {
  const languageChunks = siteConfig.supportedLanguages.reduce(
    (acc, language) => {
      const last = acc[acc.length - 1];
      if (
        last &&
        last.length < 2 &&
        last.reduce((sum, lang) => sum + lang.variants.length, 0) +
          language.variants.length <
          9
      ) {
        last.push(language);
      } else {
        acc.push([language]);
      }
      return acc;
    },
    []
  );

  return (

      <Container>

Works with the Tools You Use

          {languageChunks.map((languageChunk, index) => (

              {languageChunk.map((language) => (
                <Language key={language.name} {...language} />
              ))}

          ))}

      </Container>

  );
};

const Editor = ({ content = "", image, name }) => (

{name}

      <MarkdownBlock>{content.replace(/\n/g, "  \n")}</MarkdownBlock>

);

Editor.propTypes = {
  content: PropTypes.string,
  image: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
};

const EditorSupportSection = () => (

    <Container>

Editor Support

        {siteConfig.editors.map((editor) => (
          <Editor key={editor.name} {...editor} />
        ))}

    </Container>

      Got more?
      <a
        href={`${siteConfig.githubUrl}/edit/main/website/data/editors.yml`}
        className="button"
      >
        Send a PR

);

const UsersSection = ({ language }) => {
  const showcase = siteConfig.users
    .filter((user) => user.pinned)
    .map((user, i) => (

    ));

  return (

      <Container>

Used By People You Rely On

          {showcase}

            See Others

Established in the Ecosystem

                Regularly used by more than 70% of respondents
                to State of JS 2020

              <Button href="https://2020.stateofjs.com/en-US/other-tools/utilities">
                Go to Survey Results
              </Button>

                More than{" "}
                2.9 million{" "}
                dependent repositories on GitHub

              <Button href="https://github.com/prettier/prettier/network/dependents">
                Check Them Out
              </Button>

                More than 8000{" "}
                dependent packages on npm

              <Button href="https://www.npmjs.com/browse/depended/prettier">
                See them all
              </Button>

      </Container>

  );
};

UsersSection.propTypes = {
  language: PropTypes.string,
};

class Index extends React.Component {
  render() {
    const language = this.props.language || "en";

    return (


<commit_before>exports.names = ['lottery', 'roulette'];
exports.hidden = true;
exports.enabled = true;
exports.matchStart = true;
exports.cdAll = 60;
exports.cdUser = 60;
exports.cdStaff = 60;
exports.minRole = PERMISSIONS.BOUNCER;
exports.handler = function (data) {

    var input = data.message.split(' ');
    var mins = 1;

    if (input.length >= 2) {
        mins = parseInt(_.last(input, 1));
    }
    else {
        mins = 5;
    }

    // Sanity check!
    if (mins < 1 || mins > 120) {
        mins = 5;
    }

    if (input[0] === 'roulette') {
        bot.sendChat('Wait list roulette in ' + mins + ' minutes! Chat and be in line within ' + mins + ' minutes to enter.  Winner gets moved up a random number of spots! @djs');
    }
    else {
        bot.sendChat('Wait list lottery in ' + mins + ' minutes! Chat and be in line within ' + mins + ' minutes to enter.  Winner gets the #2 spot! @djs');
    }

    if (mins > 1) {
        setTimeout(function () {
            bot.sendChat("Contest ending in ONE MINUTE - be in line and chat to enter! @djs");
        }, (mins - 1) * 60 * 1000);
    }

    setTimeout(function () {
        // Only select from users active during the lottery
        var minPosition = 2;
        getActiveDJs(mins, minPosition, function (activeDJs) {
                if (activeDJs.length > 0) {
                    var randomNumber = _.random(0, activeDJs.length - 1);
                    var winner = activeDJs[randomNumber];
                    var winnerId = parseInt(winner.site_id);
                    var message = ":tada: @" + winner.username + " emerges victorious!";
                    transferCustomPoints(null, bot.getUser(winnerId), 1);
                    var currentPosition = bot.getWaitListPosition(winnerId);
                    var position = minPosition;
                    if (input[0] === 'roulette') {
                        position = _.random(minPosition, currentPosition - 1);
                    }
                    if (currentPosition > minPosition && currentPosition > position) {
                        bot.moderateMoveDJ(winnerId, position);
                        console.log('[LOTTO] Moving ' + winner.username + ' from position ' + currentPosition + ' to position: ' + position);
                        message += ' Moving to position ' + position;
                    } else if (currentPosition == -1) {
                        console.log('[LOTTO] ' + winner.username + ' detected with waitlist position of -1');
                        message += ' Not finding ' + winner.username + '\'s position in the wait list.  Need some help @staff';
                    } else if (currentPosition <= position) {
                        console.log('[LOTTO] Leaving ' + winner.username + ' in position: ' + currentPosition + '(' + position + ')');
                        message += ' Leaving in position ' + currentPosition;
                    }
                    bot.sendChat(message);
                }
                else {
                    bot.sendChat(":thumbsdown: No one is eligible to win the contest.");
                    console.log('[LOTTO] No one is eligible to win the contest.');
                }
            }
        );
    }, mins * 60 * 1000);

};<commit_msg>Prevent a shouted 'ROULETTE' or any mixed case from accidentally starting a lottery.<commit_after>exports.names = ['lottery', 'roulette'];
exports.hidden = true;
exports.enabled = true;
exports.matchStart = true;
exports.cdAll = 60;
exports.cdUser = 60;
exports.cdStaff = 60;
exports.minRole = PERMISSIONS.BOUNCER;
exports.handler = function (data) {

    var input = data.message.split(' ');
    var mins = 1;

    if (input.length >= 2) {
        mins = parseInt(_.last(input, 1));
    }
    else {
        mins = 5;
    }

    // Sanity check!
    if (mins < 1 || mins > 120) {
        mins = 5;
    }

    if (input[0].toLowerCase() === 'roulette') {
        bot.sendChat('Wait list roulette in ' + mins + ' minutes! Chat and be in line within ' + mins + ' minutes to enter.  Winner gets moved up a random number of spots! @djs');
    }
    else {
        bot.sendChat('Wait list lottery in ' + mins + ' minutes! Chat and be in line within ' + mins + ' minutes to enter.  Winner gets the #2 spot! @djs');
    }

    if (mins > 1) {
        setTimeout(function () {
            bot.sendChat("Contest ending in ONE MINUTE - be in line and chat to enter! @djs");
        }, (mins - 1) * 60 * 1000);
    }

    setTimeout(function () {
        // Only select from users active during the lottery
        var minPosition = 2;
        getActiveDJs(mins, minPosition, function (activeDJs) {
                if (activeDJs.length > 0) {
                    var randomNumber = _.random(0, activeDJs.length - 1);
                    var winner = activeDJs[randomNumber];
                    var winnerId = parseInt(winner.site_id);
                    var message = ":tada: @" + winner.username + " emerges victorious!";
                    transferCustomPoints(null, bot.getUser(winnerId), 1);
                    var currentPosition = bot.getWaitListPosition(winnerId);
                    var position = minPosition;
                    if (input[0] === 'roulette') {
                        position = _.random(minPosition, currentPosition - 1);
                    }
                    if (currentPosition > minPosition && currentPosition > position) {
                        bot.moderateMoveDJ(winnerId, position);
                        console.log('[LOTTO] Moving ' + winner.username + ' from position ' + currentPosition + ' to position: ' + position);
                        message += ' Moving to position ' + position;
                    } else if (currentPosition == -1) {
                        console.log('[LOTTO] ' + winner.username + ' detected with waitlist position of -1');
                        message += ' Not finding ' + winner.username + '\'s position in the wait list.  Need some help @staff';
                    } else if (currentPosition <= position) {
                        console.log('[LOTTO] Leaving ' + winner.username + ' in position: ' + currentPosition + '(' + position + ')');
                        message += ' Leaving in position ' + currentPosition;
                    }
                    bot.sendChat(message);
                }
                else {
                    bot.sendChat(":thumbsdown: No one is eligible to win the contest.");
                    console.log('[LOTTO] No one is eligible to win the contest.');
                }
            }
        );
    }, mins * 60 * 1000);

};
<|endoftext|>


<commit_before>var vfs = require('enb/lib/fs/async-fs');

module.exports = require('enb/lib/build-flow').create()
    .name('mock-lang-js.js')
    .target('target', '?.js')
    .useSourceFilename('source', '?.lang.js')
    .builder(function (source) {
        return vfs.read(source, 'utf8')
            .then(function (content) {
                var mock = [
                        '(function(global, bem_) {',
                        '    global.BEM = bem_;',
                        '    var i18n = bem_.I18N = function(keyset, key) {',
                        '       var result = key;',
                        '       if(param){',
                        '           result += ": " + JSON.stringify(param);',
                        '       }',
                        '       return result;',
                        '    };',
                        '    i18n.keyset = function() { return i18n }',
                        '    i18n.key = function(key) { return key }',
                        '    i18n.lang = function() { return }',
                        '})(this, typeof BEM === \'undefined\' ? {} : BEM);'
                    ].join('\n'),
                    mapIndex = content.lastIndexOf('//# sourceMappingURL='),
                    map;

                // if there is a #sourceMappingURL pragma append
                // the mock before it so the source map will be
                // valid. We can't insert it in the beginning because
                // source map locations will point to the wrong lines.
                if (mapIndex !== -1) {
                    map = content.substring(mapIndex);
                    content = content.substring(0, mapIndex);
                }

                return [content, mock, map].join('\n');
            });
    })
    .createTech();
<commit_msg>Fix mock lang<commit_after>var vfs = require('enb/lib/fs/async-fs');

module.exports = require('enb/lib/build-flow').create()
    .name('mock-lang-js.js')
    .target('target', '?.js')
    .useSourceFilename('source', '?.lang.js')
    .builder(function (source) {
        return vfs.read(source, 'utf8')
            .then(function (content) {
                var mock = [
                        '(function(global, bem_) {',
                        '    global.BEM = bem_;',
                        '    var i18n = bem_.I18N = function(keyset, key, param) {',
                        '       var result = key;',
                        '       if(param){',
                        '           result += ": " + JSON.stringify(param);',
                        '       }',
                        '       return result;',
                        '    };',
                        '    i18n.keyset = function() { return i18n }',
                        '    i18n.key = function(key) { return key }',
                        '    i18n.lang = function() { return }',
                        '})(this, typeof BEM === \'undefined\' ? {} : BEM);'
                    ].join('\n'),
                    mapIndex = content.lastIndexOf('//# sourceMappingURL='),
                    map;

                // if there is a #sourceMappingURL pragma append
                // the mock before it so the source map will be
                // valid. We can't insert it in the beginning because
                // source map locations will point to the wrong lines.
                if (mapIndex !== -1) {
                    map = content.substring(mapIndex);
                    content = content.substring(0, mapIndex);
                }

                return [content, mock, map].join('\n');
            });
    })
    .createTech();
<|endoftext|>


<commit_before>import React from 'react'

import ActionBar from 'js/components/ActionBar'
import Select from 'js/components/Select'

import 'css/characterGenerator.css'

const renderSizes = (sizes, charSize, changeValue) => {
  if (!(sizes instanceof Array) || sizes.length < 2) {
    return
  }
  return

    Size
    <Select id='size'
      options={sizes} value={charSize}
      onChange={(event) => changeValue('characteristics.size', event.target.value)}
    />

}

const renderIncreaseOne = (appData, charAttr, setIncreaseOne) => (

    Increase One
    <Select id='increaseOne'
      options={[].concat(appData.pleaseSelect, appData.attributes)} value={charAttr.oneIncreased}
      onChange={(event) => setIncreaseOne(event.target.value)}
    />

)

const getStyles = (charData) => ({
  display: charData.mode !== 'edit' ? 'none' : ''
})

const getListWithoutSelected = (arr, value) => {
  return arr.filter(elem => elem !== value)
}

const CharacterEdit = ({
  appData, ancestryData, charData,
  changeAncestry, changeValue, setEditMode, setViewMode, createRandomCharacter,
  setIncreaseOne, adjustOneFrom, adjustOneTo
}) => (

    <ActionBar mode={charData.mode} onEdit={setEditMode} onView={setViewMode} onCreate={createRandomCharacter} />

Character Creation (Orc or Human)

        Ancestry
        <Select id='ancestry'
          options={appData.ancestries} value={charData.ancestry}
          onChange={(event) => changeAncestry(event.target.value)}
        />

      {/* All ancestries can raise one attribute by lowering another. */}

        Adjust One Attribute
        From:
        <Select id='adjustOneFrom'
          options={[].concat(appData.pleaseSelect, appData.attributes)} value={charData.attributes.oneAdjustFrom}
          onChange={(event) => adjustOneFrom(event.target.value === appData.pleaseSelect ? void 0 : event.target.value)}
        />
        To:
        <Select id='adjustOneTo'
          options={[].concat(appData.pleaseSelect, getListWithoutSelected(appData.attributes, charData.attributes.oneAdjustFrom))} value={charData.attributes.oneAdjustTo}
          onChange={(event) => adjustOneTo(event.target.value === appData.pleaseSelect ? void 0 : event.target.value)}
        />

      {ancestryData.attributes.increaseOne ? renderIncreaseOne(appData, charData.attributes, setIncreaseOne) : null}

        Name
        <Select id='name'
          options={ancestryData.commonNames} value={charData.name}
          onChange={(event) => changeValue('name', event.target.value)}
        />

        Background
        <Select id='background'
          options={ancestryData.background} value={charData.background}
          onChange={(event) => changeValue('background', event.target.value)}
        />

      {renderSizes(ancestryData.characteristics.size, charData.characteristics.size, changeValue)}

)

export default CharacterEdit
<commit_msg>[#9] Add defensive check for test suite.<commit_after>import React from 'react'

import ActionBar from 'js/components/ActionBar'
import Select from 'js/components/Select'

import 'css/characterGenerator.css'

const renderSizes = (sizes, charSize, changeValue) => {
  if (!(sizes instanceof Array) || sizes.length < 2) {
    return
  }
  return

    Size
    <Select id='size'
      options={sizes} value={charSize}
      onChange={(event) => changeValue('characteristics.size', event.target.value)}
    />

}

const renderIncreaseOne = (appData, charAttr, setIncreaseOne) => (

    Increase One
    <Select id='increaseOne'
      options={[].concat(appData.pleaseSelect, appData.attributes)} value={charAttr.oneIncreased}
      onChange={(event) => setIncreaseOne(event.target.value)}
    />

)

const getStyles = (charData) => ({
  display: charData.mode !== 'edit' ? 'none' : ''
})

const getListWithoutSelected = (arr, value) => {
  if (!arr || arr.length === 0) {
    return arr
  }
  return arr.filter(elem => elem !== value)
}

const CharacterEdit = ({
  appData, ancestryData, charData,
  changeAncestry, changeValue, setEditMode, setViewMode, createRandomCharacter,
  setIncreaseOne, adjustOneFrom, adjustOneTo
}) => (

    <ActionBar mode={charData.mode} onEdit={setEditMode} onView={setViewMode} onCreate={createRandomCharacter} />

Character Creation (Orc or Human)

        Ancestry
        <Select id='ancestry'
          options={appData.ancestries} value={charData.ancestry}
          onChange={(event) => changeAncestry(event.target.value)}
        />

      {/* All ancestries can raise one attribute by lowering another. */}

        Adjust One Attribute
        From:
        <Select id='adjustOneFrom'
          options={[].concat(appData.pleaseSelect, appData.attributes)} value={charData.attributes.oneAdjustFrom}
          onChange={(event) => adjustOneFrom(event.target.value === appData.pleaseSelect ? void 0 : event.target.value)}
        />
        To:
        <Select id='adjustOneTo'
          options={[].concat(appData.pleaseSelect, getListWithoutSelected(appData.attributes, charData.attributes.oneAdjustFrom))} value={charData.attributes.oneAdjustTo}
          onChange={(event) => adjustOneTo(event.target.value === appData.pleaseSelect ? void 0 : event.target.value)}
        />

      {ancestryData.attributes.increaseOne ? renderIncreaseOne(appData, charData.attributes, setIncreaseOne) : null}

        Name
        <Select id='name'
          options={ancestryData.commonNames} value={charData.name}
          onChange={(event) => changeValue('name', event.target.value)}
        />

        Background
        <Select id='background'
          options={ancestryData.background} value={charData.background}
          onChange={(event) => changeValue('background', event.target.value)}
        />

      {renderSizes(ancestryData.characteristics.size, charData.characteristics.size, changeValue)}

)

export default CharacterEdit
<|endoftext|>


<commit_before>import {bindable, inject, customElement, LogManager} from 'aurelia-framework';
import {Catalogues} from '../../services/catalogues';
import {Stamps} from '../../services/stamps';
import {CatalogueNumbers} from '../../services/catalogueNumbers';
import {Preferences} from '../../services/preferences';
import {Condition} from '../../util/common-models';
import {I18N} from 'aurelia-i18n';

import _ from 'lodash';
import bootbox from 'bootbox';

import 'resources/styles/components/catalogue-numbers/cn-references.css!';

const logger = LogManager.getLogger('cn-references');

@customElement('catalogue-number-references')
@bindable('model')
@inject(Element, I18N, Catalogues, CatalogueNumbers, Stamps, Preferences)
export class CatalogueNumberReferences {

    modelCopy;
    updateTemplate;
    editSlot;
    catalogues = [];

    defaultCondition = -1;
    defaultCatalogue = null;

    conditions = Condition.symbols();
    number;

    constructor(element, i18next, catalogueService, catalogueNumberService, stampService, preferenceService) {
        this.element = $(element);
        this.i18next = i18next;
        this.catalogueService = catalogueService;
        this.catalogueNumberService = catalogueNumberService;
        this.stampService = stampService;
        this.preferenceService = preferenceService;
    }

    bind() {
        let self = this;
        // Using a promise here, but not bind (view-models) do not use promises to block
        Promise.all([
            self.catalogueService.find(self.catalogueService.getDefaultSearchOptions()).then(results => {
                self.catalogues = results.models;
            }),
            self.preferenceService.find(self.preferenceService.getDefaultSearchOptions()).then(results => { //eslint-disable-line no-unused-vars
                let cond = self.preferenceService.getByNameAndCategory('condition', 'stamps');
                if( cond ) {
                    self.defaultCondition = +cond.value;
                }
                let cat = self.preferenceService.getByNameAndCategory('catalogueRefSecondary', 'stamps');
                if( cat ) {
                    self.defaultCatalogue = +cat.value;
                }
            })
        ]);
    }

    modelChanged(newModel) {
        if (newModel) {
            let self = this;
            this.modelCopy = _.clone(newModel, true);
            this.modelCopy.catalogueNumbers.forEach(catNum => {
                catNum.currencyCode = self.determineCurrencyCode(catNum.catalogueRef);
            });
        } else {
            this.modelCopy = {};
        }
    }

    determineCurrencyCode(catalogueRef) {
        let code = 'USD';
        let cat = this.catalogueService.getById(catalogueRef);
        if (cat) {
            code = cat.code;
        }
        return code;
    }

    edit(num, index) { //eslint-disable-line no-unused-vars
        num.editing = true;
    }

    cancel(num) {
        let inlineRow = $(this.element.find('.editing-row'));
        if (num.id === 0) {
            inlineRow.remove();
            let index = _.findIndex(this.modelCopy.catalogueNumbers, {id: 0});
            if (index >= 0) {
                this.modelCopy.catalogueNumbers.splice(1, index);
            }
        }
        num.editing = false;
    }

    save(num) { //eslint-disable-line no-unused-vars
        let self = this;
        self.stampService.save(this.modelCopy).then( stamp => {
            self.modelChanged(stamp);
        });
    }

    add() {
        let num = {
            id: 0,
            active: false,
            catalogueRef: this.defaultCatalogue,
            condition: this.defaultCondition,
            number: "",
            value: 0
        };
        num.editing = true;
        this.modelCopy.catalogueNumbers.push(num);
    }

    remove(num) {
        let self = this;
        let _remove = function(m) {
            self.catalogueNumberService.remove(m).then( result => {
                if( result === true ) {
                    let index = _.findIndex(self.modelCopy.catalogueNumbers, { id: m.id });
                    self.modelCopy.catalogueNumbers.splice(index, 1);
                }
            }).catch( err => {
                logger.debug("Error removing", err);
            });
        };
        bootbox.confirm({
            size: 'small',
            message: self.i18next.tr("prompts.delete-catalogue-number", { number: num.number } ),
            callback: function (result) {
                if (result === true) {
                    _remove.call(self, num);

                }
            }
        });

    }

    makeActive(num) {
        let activeNum;
        for( let i = 0; i < this.modelCopy.catalogueNumbers.length; i++ ) {
            let cn = this.modelCopy.catalogueNumbers[i];
            if( cn.active === true ) {
                activeNum = cn;
                break;
            }
        }
        if( activeNum.id === num.id ) {
            throw new Error("Can not set active as active!");
        } else {
            this.catalogueNumberService.makeActive(num.id).then( stamp => { //eslint-disable-line no-unused-vars
                activeNum.active = false;
                num.active = true;
            }).catch( err => {
                logger.error(err);
            });
        }
    }
}
<commit_msg>Force the focus in the text field<commit_after>import {bindable, inject, customElement, LogManager} from 'aurelia-framework';
import {Catalogues} from '../../services/catalogues';
import {Stamps} from '../../services/stamps';
import {CatalogueNumbers} from '../../services/catalogueNumbers';
import {Preferences} from '../../services/preferences';
import {Condition} from '../../util/common-models';
import {I18N} from 'aurelia-i18n';

import $ from 'jquery';
import _ from 'lodash';
import bootbox from 'bootbox';

import 'resources/styles/components/catalogue-numbers/cn-references.css!';

const logger = LogManager.getLogger('cn-references');

@customElement('catalogue-number-references')
@bindable('model')
@inject(Element, I18N, Catalogues, CatalogueNumbers, Stamps, Preferences)
export class CatalogueNumberReferences {

    modelCopy;
    updateTemplate;
    editSlot;
    catalogues = [];

    defaultCondition = -1;
    defaultCatalogue = null;

    conditions = Condition.symbols();
    number;

    constructor(element, i18next, catalogueService, catalogueNumberService, stampService, preferenceService) {
        this.element = $(element);
        this.i18next = i18next;
        this.catalogueService = catalogueService;
        this.catalogueNumberService = catalogueNumberService;
        this.stampService = stampService;
        this.preferenceService = preferenceService;
    }

    bind() {
        let self = this;
        // Using a promise here, but not bind (view-models) do not use promises to block
        Promise.all([
            self.catalogueService.find(self.catalogueService.getDefaultSearchOptions()).then(results => {
                self.catalogues = results.models;
            }),
            self.preferenceService.find(self.preferenceService.getDefaultSearchOptions()).then(results => { //eslint-disable-line no-unused-vars
                let cond = self.preferenceService.getByNameAndCategory('condition', 'stamps');
                if( cond ) {
                    self.defaultCondition = +cond.value;
                }
                let cat = self.preferenceService.getByNameAndCategory('catalogueRefSecondary', 'stamps');
                if( cat ) {
                    self.defaultCatalogue = +cat.value;
                }
            })
        ]);
    }

    modelChanged(newModel) {
        if (newModel) {
            let self = this;
            this.modelCopy = _.clone(newModel, true);
            this.modelCopy.catalogueNumbers.forEach(catNum => {
                catNum.currencyCode = self.determineCurrencyCode(catNum.catalogueRef);
            });
        } else {
            this.modelCopy = {};
        }
    }

    determineCurrencyCode(catalogueRef) {
        let code = 'USD';
        let cat = this.catalogueService.getById(catalogueRef);
        if (cat) {
            code = cat.code;
        }
        return code;
    }

    edit(num, index) { //eslint-disable-line no-unused-vars
        num.editing = true;
    }

    cancel(num) {
        let inlineRow = $(this.element.find('.editing-row'));
        if (num.id === 0) {
            inlineRow.remove();
            let index = _.findIndex(this.modelCopy.catalogueNumbers, {id: 0});
            if (index >= 0) {
                this.modelCopy.catalogueNumbers.splice(1, index);
            }
        }
        num.editing = false;
    }

    save(num) { //eslint-disable-line no-unused-vars
        let self = this;
        self.stampService.save(this.modelCopy).then( stamp => {
            self.modelChanged(stamp);
        });
    }

    add() {
        let num = {
            id: 0,
            active: false,
            catalogueRef: this.defaultCatalogue,
            condition: this.defaultCondition,
            number: "",
            value: 0
        };
        num.editing = true;
        this.modelCopy.catalogueNumbers.push(num);
        setTimeout( () => {
            let el = this.element.find('#cn-number');
            $(el).focus();
        }, 250);
    }

    remove(num) {
        let self = this;
        let _remove = function(m) {
            self.catalogueNumberService.remove(m).then( result => {
                if( result === true ) {
                    let index = _.findIndex(self.modelCopy.catalogueNumbers, { id: m.id });
                    self.modelCopy.catalogueNumbers.splice(index, 1);
                }
            }).catch( err => {
                logger.debug("Error removing", err);
            });
        };
        bootbox.confirm({
            size: 'small',
            message: self.i18next.tr("prompts.delete-catalogue-number", { number: num.number } ),
            callback: function (result) {
                if (result === true) {
                    _remove.call(self, num);

                }
            }
        });

    }

    makeActive(num) {
        let activeNum;
        for( let i = 0; i < this.modelCopy.catalogueNumbers.length; i++ ) {
            let cn = this.modelCopy.catalogueNumbers[i];
            if( cn.active === true ) {
                activeNum = cn;
                break;
            }
        }
        if( activeNum.id === num.id ) {
            throw new Error("Can not set active as active!");
        } else {
            this.catalogueNumberService.makeActive(num.id).then( stamp => { //eslint-disable-line no-unused-vars
                activeNum.active = false;
                num.active = true;
            }).catch( err => {
                logger.error(err);
            });
        }
    }
}
<|endoftext|>


<commit_before>// @flow

// Production and dev keys
const GTM_KEY = process.env.NODE_ENV === 'production' ? 'GTM-T2LNGD' : 'GTM-W9W847';

/**
 * @description Method for passing additional variables to GTM
 * @see {@link https://developers.google.com/tag-manager/devguide}
 */
export const gtmPush = (data: { [string]: string }) => {
	if (typeof window !== 'undefined' && window.dataLayer) {
		window.dataLayer.push(data);
	}
};

/**
 * @description Gets google tag manager JS snippet
 * @see {@link https://developers.google.com/tag-manager/quickstart}
*/
export const getGoogleTagManagerSnippet = (): string => (
	`dataLayer = [];
	(function(w,d,s,l,i){
		w[l]=w[l]||[];
		w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});
		var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
		j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;
		f.parentNode.insertBefore(j,f);
	})(window,document,'script','dataLayer','${GTM_KEY}');`;
<commit_msg>Weird fix<commit_after>// @flow

// Production and dev keys
const GTM_KEY = process.env.NODE_ENV === 'production' ? 'GTM-T2LNGD' : 'GTM-W9W847';

/**
 * @description Method for passing additional variables to GTM
 * @see {@link https://developers.google.com/tag-manager/devguide}
 */
export const gtmPush = (data: { [string]: string }) => {
	if (typeof window !== 'undefined' && window.dataLayer) {
		window.dataLayer.push(data);
	}
};

/**
 * @description Gets google tag manager JS snippet
 * @see {@link https://developers.google.com/tag-manager/quickstart}
*/
export const getGoogleTagManagerSnippet = (): string =>
	`dataLayer = [];
	(function(w,d,s,l,i){
		w[l]=w[l]||[];
		w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});
		var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
		j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;
		f.parentNode.insertBefore(j,f);
	})(window,document,'script','dataLayer','${GTM_KEY}');`;
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

const fs        = require('fs');
const path      = require('path');
const fetch     = require('node-fetch');
const cheerio   = require('cheerio');
const coroutine = require('co');
const Mocha     = require('mocha');

const HOST = 'https://leetcode.com';
const OUTPUT = path.resolve(__dirname, '../README.md');

const Categories = ['Algorithms']; // Database, Shell
const Difficulties = ['Easy', 'Medium', 'Hard'];

function mochaTest (file) {
  return new Promise((resolve, reject) => {
    const mocha = new Mocha();
    mocha.addFile(file);
    mocha.run(result => {
      resolve(result === 0);
    });
  });
}

coroutine(function * () {

  // 1. http request
  const response = [];
  for (let i = 0; i < Categories.length; i++) {
    const category = Categories[i];
    const url = HOST + '/problemset/' + category.toLowerCase();
    const data = yield fetch(url, { timeout: 10 * 1000 }).then(res => {
      if (res.status !== 200) {
        throw new Error(`request to ${url} failed, status code = ${res.status} (${res.statusText})`);
      }
      return res.text().then(html => new Object({ category, html }));
    });
    response.push(data);
  }

  // 2. response => problem list
  const problemList = response.reduce((list, data) => {
    const $ = cheerio.load(data.html);
    $('#problemList tbody tr').each((index, tr) => {
      const td = $(tr).find('td');
      const no         = Number.parseInt(td.eq(1).text().trim(), 10);
      const title      = td.eq(2).find('a').text().trim();
      const uri        = td.eq(2).find('a').attr('href').trim();
      const lock       = td.eq(2).find('i').attr('class') ? true : false;
      const acceptance = td.eq(3).text().trim();
      const difficulty = td.eq(6).text().trim();
      list[no] = { no, category: data.category, title, uri, lock, acceptance, difficulty };
    });
    return list;
  }, [])
  .filter(problem => problem !== null); // filter the empty item from list

  // 3. generate statistics
  let statistics = {};
  for (let i = 0; i < problemList.length; i++) {
    const name       = problemList[i].uri.split('/')[2];
    const category   = problemList[i].category;
    const difficulty = problemList[i].difficulty;

    // state
    let state = false;
    try {
      state = yield mochaTest(path.resolve(__dirname, '../src', name + '.js'));
    } catch (e) {
      if (e.code !== 'MODULE_NOT_FOUND') {
        throw e;
      }
    }

    // add name and state
    Object.assign(problemList[i], {
      name, state
    });

    // Difficulty Statistics
    if (!statistics.hasOwnProperty(difficulty)) {
      statistics[difficulty] = { total: 0, solve: 0 };
    }
    statistics[difficulty].total += 1;
    statistics[difficulty].solve += state ? 1 : 0;

    // Category Statistics
    if (!statistics.hasOwnProperty(category)) {
      statistics[category] = { total: 0, solve: 0 };
    }
    statistics[category].total += 1;
    statistics[category].solve += state ? 1 : 0;
  }

  // 4. generate markdown
  const difficultyStatistics = Difficulties.map(difficulty => {
    const total = statistics[difficulty].total;
    const solve = statistics[difficulty].solve;

    return `* ${difficulty} (${solve}/${total})`;
  }).join('\n');

  const leetcodeTable = problemList.map(p => {
    return [
      '',
      p.category,
      p.no,
      `[${p.title}](${HOST + p.uri})${p.lock ? ' :blue_book:' : ''}`,
      p.difficulty,
      p.state ? `[✓](src/${p.name}.js)` : '✘',
      ''
    ].join(' | ').trim();
  }).join('\n');

  const markdown = [
    '#LeetCode',
    '',
    '[![][dependency-img]][dependency-url]',
    '[![][travis-img]][travis-url]',
    '',
    difficultyStatistics,
    '',
    '| Category | #     | Title | Difficulty | State |',
    '| :---     | :---: | :---  | :---       | :---: |',
    leetcodeTable,
    '',
    '[dependency-url]: https://david-dm.org/zlargon/leetcode',
    '[dependency-img]: https://img.shields.io/david/zlargon/leetcode.svg',
    '',
    '[travis-url]: https://travis-ci.org/zlargon/leetcode',
    '[travis-img]: https://img.shields.io/travis/zlargon/leetcode/master.svg',
    ''
  ].join('\n');

  // 5. write file
  fs.writeFileSync(OUTPUT, markdown);
  console.log('Save to ' + OUTPUT);
})
.catch(e => console.log(e.stack));
<commit_msg>update script "update_readme.js" for new website<commit_after>#!/usr/bin/env node
'use strict';

const fs = require('fs');
const path = require('path');
const co = require('co');
const fetch = require('node-fetch');
const Mocha = require('mocha');

const HOST = 'https://leetcode.com';
const OUTPUT = path.resolve(__dirname, '../README.md');

const Categories = ['Algorithms']; // Database, Shell
const Difficulties = ['Easy', 'Medium', 'Hard'];

function mochaTest (file) {
  return new Promise((resolve, reject) => {
    const mocha = new Mocha();
    mocha.addFile(file);
    mocha.run(result => {
      resolve(result === 0);
    });
  });
}

co(function * () {

  // 1. http request
  const problemList = [];
  for (let i = 0; i < Categories.length; i++) {
    const category = Categories[i];
    const url = HOST + '/api/problems/' + category.toLowerCase();
    const data = yield fetch(url, { timeout: 10 * 1000 }).then(res => {
      if (res.status !== 200) {
        throw new Error(`request to ${url} failed, status code = ${res.status} (${res.statusText})`);
      }
      return res.json().then(json => {
        json.stat_status_pairs.forEach(x => {
          problemList.unshift({
            id: x.stat.question_id,
            category,
            title: x.stat.question__title,
            name: x.stat.question__title_slug,
            url: HOST + '/problems/' + x.stat.question__title_slug + '/',
            lock: x.paid_only,
            difficulty: x.difficulty.level - 1
          });
        });
      });
    });
  }

  // 3. generate statistics
  const diff_total = [0, 0, 0];
  const diff_solve = [0, 0, 0];

  for (let i = 0; i < problemList.length; i++) {
    const p = problemList[i];
    p.state = false;

    try {
      p.state = yield mochaTest(path.resolve(__dirname, '../src', p.name + '.js'));
    } catch (e) {
      if (e.code !== 'MODULE_NOT_FOUND') {
        throw e;
      }
    }

    // statistics
    diff_total[p.difficulty] += 1;
    if (p.state) {
      diff_solve[p.difficulty] += 1;
    }
  }

  // 4. generate markdown
  const statistics = Difficulties.map((diff, i) => {
    return `* ${diff} (${diff_solve[i]}/${diff_total[i]})`;
  }).join('\n');

  const leetcodeTable = problemList.map(p => {
    return [
      '',
      p.category,
      p.id,
      `[${p.title}](${p.url})${p.lock ? ' :blue_book:' : ''}`,
      Difficulties[p.difficulty],
      p.state ? `[✓](src/${p.name}.js)` : '✘',
      ''
    ].join(' | ').trim();
  }).join('\n');

  const markdown = [
    '# LeetCode',
    '',
    '[![][dependency-img]][dependency-url]',
    '[![][travis-img]][travis-url]',
    '',
    statistics,
    '',
    '| Category | #     | Title | Difficulty | State |',
    '| :---     | :---: | :---  | :---       | :---: |',
    leetcodeTable,
    '',
    '[dependency-url]: https://david-dm.org/zlargon/leetcode',
    '[dependency-img]: https://img.shields.io/david/zlargon/leetcode.svg',
    '',
    '[travis-url]: https://travis-ci.org/zlargon/leetcode',
    '[travis-img]: https://img.shields.io/travis/zlargon/leetcode/master.svg',
    ''
  ].join('\n');

  // 5. write file
  fs.writeFileSync(OUTPUT, markdown);
  console.log('Save to ' + OUTPUT);
})
.catch(e => console.log(e.stack));
<|endoftext|>


<commit_before>const React = require("react");

const fs = require("fs");
const path = require("path");
const CompLibrary = require("../../core/CompLibrary.js");
const Container = CompLibrary.Container;
const MarkdownBlock = CompLibrary.MarkdownBlock;
const siteConfig = require(process.cwd() + "/siteConfig.js");
const setupBabelrc = siteConfig.setupBabelrc;
const toolsMD = siteConfig.toolsMD;

const StepFour = () => {
  return (

        4 Create .babelrc configuration file

      <MarkdownBlock>{setupBabelrc}</MarkdownBlock>

  );
};

const StepSetup = () => {
  const usagesMD = toolsMD.map((tool, index) => (

      <MarkdownBlock key={index}>{tool.usage}</MarkdownBlock>

  ));
  return (

        3 Usage

      {usagesMD}

  );
};

const StepInstall = props => {
  const installsMD = toolsMD.map((tool, index) => (

      <MarkdownBlock key={index}>{tool.install}</MarkdownBlock>

  ));
  return (

        2 Installation

      {installsMD}

  );
};

class Setup extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const tools = siteConfig.tools;
    const time = new Date().getTime();
    const showCase = tools.map((types, i) => {
      const showTools = Object.keys(types.items).map((tool, j) => {
        const isActive = false;
        return (

            {types.items[tool]}

        );
      });
      return (

{types.name}

          {showTools}

      );
    });
    return (

Using Babel

How to use Babel with your tool of choice.

        <Container padding={["bottom"]}>

                1
                {" Choose your tool (try CLI)"}

              {showCase}

            <StepInstall />
            <StepSetup />
            <StepFour />

        </Container>


<commit_before>(function(env) {
    env.ddg_spice_github = function(api_result) {
        "use strict";

        if (!api_result || !api_result.meta.status === '200') {
          return;
        }

        var query = DDG.get_query()
                    .replace(/^\s*github\s+/, "");

        var results = api_result.data.repositories;

        Spice.add({
            id: "gihub",
            name: "Github",
            data: results,
            meta: {
                total: results.length,
                itemType: query + " (GitHub)",
                sourceUrl: 'http://www.github.com/search?q=' +  encodeURIComponent(query),
                sourceName: 'GitHub',
            },
            templates: {
                item: Spice.github.item
            }
        });
    }
}(this));
<commit_msg>github: update api<commit_after>(function(env) {
    env.ddg_spice_github = function(api_result) {
        "use strict";

        if (!api_result || !api_result.meta.status === 200) {
          return;
        }

        var query = DDG.get_query()
                    .replace(/^\s*github\s+/, "");

        var results = api_result.data.repositories;

        Spice.add({
            id: "gihub",
            name: "Github",
            data: results,
            meta: {
                total: results.length,
                itemType: query + " (GitHub)",
                sourceUrl: 'http://www.github.com/search?q=' +  encodeURIComponent(query),
                sourceName: 'GitHub'
            },
            templates: {
                item: Spice.github.item
            }
        });
    }
}(this));
<|endoftext|>


<commit_before>'use babel';

import DevicePanelView from './views/thera-device-panel-view';
import { CompositeDisposable } from 'atom';

module.exports = class DevicePanel{

    activate(state) {
        this.subscriptions = new CompositeDisposable();
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'thera-device-panel:toggle': () => this.toggle()
        }));
    }

    deactivate() {
        this.subscriptions.dispose();
        this.devicePanelView.destroy();
    }

    toggle() {
        this.devicePanel = this.devicePanel || new DevicePanelView()
        console.log(this.devicePanel);
        this.devicePanel.show()
    }

}<commit_msg>change function name<commit_after>'use babel';

import DevicePanelView from './views/thera-device-panel-view';
import { CompositeDisposable } from 'atom';

module.exports = class DevicePanel{

    activate(state) {
        this.subscriptions = new CompositeDisposable();
        this.subscriptions.add(atom.commands.add('atom-workspace', {
            'thera-device-panel:show': () => this.show()
        }));
    }

    deactivate() {
        this.subscriptions.dispose();
        this.devicePanelView.destroy();
    }

    show() {
        this.devicePanel = this.devicePanel || new DevicePanelView()
        console.log(this.devicePanel);
        this.devicePanel.show()
    }

}<|endoftext|>