<commit_before>'use strict';

(function () {
  var EVENT_NAMES = {
    ALL_IDS_COMPLETE: 'allIdsComplete',
    ID_ADDED: 'idAdded',
    ID_RETAINED: 'idRetained'
  };

  CKEDITOR.plugins.add('autoid', {
    init: function (editor) {
      var self = this;

      // This configures the Advanced Content Filter to allow all headings
      // to have id attributes
      editor.addFeature({
        allowedContent: 'h1 h2 h3 h4 h5 h6 *[id]'
      });

      if (editor && !editor.config.autoid) {
        editor.config.autoid = {};
      }
      self.settings = editor.config.autoid;
      if (!self.settings) {
        self.settings = {};
      }

      editor.addCommand('autoid', {
        exec: function (editor) {
          var autoId = editor.getCommand('autoid');
          autoId.toggleState();
          if (autoId.state === CKEDITOR.TRISTATE_ON)
            addAllIds();
        },
        editorFocus: true
      });

      editor.on("instanceReady", function () {
        if (self.settings.autostart !== false) {
          editor.getCommand('autoid').setState(CKEDITOR.TRISTATE_ON);
          addAllIds();
        }
      });

      CKEDITOR.on('dialogDefinition', modifyLinkDialog);

      editor.on('selectionChange', addIdIfNewHeading);

      editor.on('paste', checkPastedContentForHeadings);

      function addAllIds() {
        var headings = findAllHeadings(),
          i, heading;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (heading.hasAttribute('id')) {
            continue;
          }
          addId(heading);
        }
        editor.fire(EVENT_NAMES.ALL_IDS_COMPLETE);
      }

      function findAllHeadings() {
        return editor.document.find('h1, h2, h3, h4, h5, h6');
      }

      function findHeadingIds(headings) {
        var ids = [],
          i, heading, id;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (id = heading.getAttribute('id')) {
            ids.push(id)
          }
        }
        return ids;
      }

      function addId(heading) {
        var uuid = CKEDITOR.tools.getUniqueId();
        heading.setAttributes({ id: uuid });
        editor.fire(EVENT_NAMES.ID_ADDED);
      }

      function addIdIfNewHeading() {
        var element = editor.getSelection().getStartElement();
        if (isHeading(element) && !element.hasAttribute('id')) {
          addId(element);
        }
      }

      function isHeading(element) {
        return element.is('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
      }

      function checkPastedContentForHeadings(ev) {
        var pastedContent = ev.data.dataValue,
          pastedContentAsHtml = CKEDITOR.htmlParser.fragment.fromHtml(pastedContent),
          pastedElements = pastedContentAsHtml.children,
          writer = new CKEDITOR.htmlParser.basicWriter(),
          i, element, id, originalHeading;

        for (i = 0; i < pastedElements.length; i++) {
          element = pastedElements[i];
          if (element.type === CKEDITOR.NODE_ELEMENT) {
            id = element.attributes.id;
            originalHeading = checkForDuplicateId(id);
            if (originalHeading) {
              element = resolveDuplicateIds(element, originalHeading);
            }
          }
        }

        pastedContentAsHtml.writeHtml(writer);
        ev.data.dataValue = writer.getHtml();
      }

      function checkForDuplicateId(id) {
        var headingIds = findHeadingIds(findAllHeadings()),
          i, headingId, originalHeading;

        for (i = 0; i < headingIds.length; i++) {
          headingId = headingIds[i];
          if (id === headingId) {
            return originalHeading = editor.document.getById(headingId);
          }
        }
      }

      function resolveDuplicateIds(newHeading, originalHeading) {
        var newHeadingText = newHeading.children[0].value,
          originalHeadingText = originalHeading.getText();

        // if the original heading has no content (blank or just a line-feed
        // character is left when all the content is cut), the original heading
        // will be removed and the new heading will retain the id
        if ( originalHeadingText.length <= 1 && notWordCharacter(originalHeadingText.charAt(0))) {
          originalHeading.remove();
          editor.fire(EVENT_NAMES.ID_RETAINED);
          return newHeading;
        }

        // if the original heading text is not blank, the original should retain its
        // id and the new heading should get a new one.
        if (originalHeadingText) {
          newHeading.attributes.id = CKEDITOR.tools.getUniqueId();
          editor.fire(EVENT_NAMES.ID_ADDED);
          return newHeading;
        }

      }

      function notWordCharacter(character) {
        if (!character)
          return true;

        return !(/\w/.test(character));
      }

      // This modifies the dialog for the 'link' plugin to allow the option of
      // internal document linking to autoid headings. Original 'link' plugin
      // code can be found at:
      // https://github.com/ckeditor/ckeditor-dev/tree/master/plugins/link

      function modifyLinkDialog(ev) {
        var dialog = ev.data;

        if (dialog.name == 'link') {
          var def = ev.data.definition,
            infoTab = def.contents[0],
            linkTypeTab = infoTab.elements[1];

          // Add option for heading links to linkType dropdown
          linkTypeTab.items.push(['Link to heading in the text', 'heading']);

          // Add additional content to 'Link Info' tab for heading links
          infoTab.elements.push(createHeadingLinkContent());

          // Modify linkType's 'onChange' function to accomodate new heading option
          linkTypeTab.onChange = modifiedLinkTypeChanged;
        }
      }

      function modifiedLinkTypeChanged() {
        var dialog = this.getDialog(),
          partIds = [ 'urlOptions', 'anchorOptions', 'emailOptions', 'headingOptions' ],
          typeValue = this.getValue(),
          uploadTab = dialog.definition.getContents( 'upload' ),
          uploadInitiallyHidden = uploadTab && uploadTab.hidden;

        if ( typeValue == 'url' ) {
          if ( editor.config.linkShowTargetTab )
            dialog.showPage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.showPage( 'upload' );
          } else {
            dialog.hidePage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.hidePage( 'upload' );
        }

        for ( var i = 0; i < partIds.length; i++ ) {
          var element = dialog.getContentElement( 'info', partIds[ i ] );
          if ( !element )
            continue;

          element = element.getElement().getParent().getParent();
          if ( partIds[ i ] == typeValue + 'Options' )
            element.show();
          else
            element.hide();
        }

        dialog.layout();
      }

      function createHeadingLinkContent() {
        var headings;

        return {
          type: 'hbox',
          id: 'headingOptions',
          widths: [ '100%' ],
          children: [ {
            type: 'select',
            id: 'heading',
            label: 'Select a Heading',
            style: 'width : 100%;',
            items: [ [''] ],
            setup: function() {
              headings = findAllHeadings();

              this.getElement()[ headings && headings.count() ? 'show' : 'hide' ]();
            }
          },
          {
            type: 'html',
            id: 'noHeadings',
            style: 'text-align: center;',
            html: '
' + CKEDITOR.tools.htmlEncode( '(No headings available in the document)' ) + '
',
            // Focus the first element defined in above html.
            focus: true,
            setup: function() {
              this.getElement()[ headings && headings.count() ? 'hide' : 'show' ]();
            }
          } ]
        }
      }
    }
  });
})();
<commit_msg>Fix alignment issues<commit_after>'use strict';

(function () {
  var EVENT_NAMES = {
    ALL_IDS_COMPLETE: 'allIdsComplete',
    ID_ADDED: 'idAdded',
    ID_RETAINED: 'idRetained'
  };

  CKEDITOR.plugins.add('autoid', {
    init: function (editor) {
      var self = this;

      // This configures the Advanced Content Filter to allow all headings
      // to have id attributes
      editor.addFeature({
        allowedContent: 'h1 h2 h3 h4 h5 h6 *[id]'
      });

      if (editor && !editor.config.autoid) {
        editor.config.autoid = {};
      }
      self.settings = editor.config.autoid;
      if (!self.settings) {
        self.settings = {};
      }

      editor.addCommand('autoid', {
        exec: function (editor) {
          var autoId = editor.getCommand('autoid');
          autoId.toggleState();
          if (autoId.state === CKEDITOR.TRISTATE_ON)
            addAllIds();
        },
        editorFocus: true
      });

      editor.on("instanceReady", function () {
        if (self.settings.autostart !== false) {
          editor.getCommand('autoid').setState(CKEDITOR.TRISTATE_ON);
          addAllIds();
        }
      });

      CKEDITOR.on('dialogDefinition', modifyLinkDialog);

      editor.on('selectionChange', addIdIfNewHeading);

      editor.on('paste', checkPastedContentForHeadings);

      function addAllIds() {
        var headings = findAllHeadings(),
          i, heading;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (heading.hasAttribute('id')) {
            continue;
          }
          addId(heading);
        }
        editor.fire(EVENT_NAMES.ALL_IDS_COMPLETE);
      }

      function findAllHeadings() {
        return editor.document.find('h1, h2, h3, h4, h5, h6');
      }

      function findHeadingIds(headings) {
        var ids = [],
          i, heading, id;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (id = heading.getAttribute('id')) {
            ids.push(id)
          }
        }
        return ids;
      }

      function addId(heading) {
        var uuid = CKEDITOR.tools.getUniqueId();
        heading.setAttributes({ id: uuid });
        editor.fire(EVENT_NAMES.ID_ADDED);
      }

      function addIdIfNewHeading() {
        var element = editor.getSelection().getStartElement();
        if (isHeading(element) && !element.hasAttribute('id')) {
          addId(element);
        }
      }

      function isHeading(element) {
        return element.is('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
      }

      function checkPastedContentForHeadings(ev) {
        var pastedContent = ev.data.dataValue,
          pastedContentAsHtml = CKEDITOR.htmlParser.fragment.fromHtml(pastedContent),
          pastedElements = pastedContentAsHtml.children,
          writer = new CKEDITOR.htmlParser.basicWriter(),
          i, element, id, originalHeading;

        for (i = 0; i < pastedElements.length; i++) {
          element = pastedElements[i];
          if (element.type === CKEDITOR.NODE_ELEMENT) {
            id = element.attributes.id;
            originalHeading = checkForDuplicateId(id);
            if (originalHeading) {
              element = resolveDuplicateIds(element, originalHeading);
            }
          }
        }

        pastedContentAsHtml.writeHtml(writer);
        ev.data.dataValue = writer.getHtml();
      }

      function checkForDuplicateId(id) {
        var headingIds = findHeadingIds(findAllHeadings()),
          i, headingId, originalHeading;

        for (i = 0; i < headingIds.length; i++) {
          headingId = headingIds[i];
          if (id === headingId) {
            return originalHeading = editor.document.getById(headingId);
          }
        }
      }

      function resolveDuplicateIds(newHeading, originalHeading) {
        var newHeadingText = newHeading.children[0].value,
          originalHeadingText = originalHeading.getText();

        // if the original heading has no content (blank or just a line-feed
        // character is left when all the content is cut), the original heading
        // will be removed and the new heading will retain the id
        if ( originalHeadingText.length <= 1 && notWordCharacter(originalHeadingText.charAt(0))) {
          originalHeading.remove();
          editor.fire(EVENT_NAMES.ID_RETAINED);
          return newHeading;
        }

        // if the original heading text is not blank, the original should retain its
        // id and the new heading should get a new one.
        if (originalHeadingText) {
          newHeading.attributes.id = CKEDITOR.tools.getUniqueId();
          editor.fire(EVENT_NAMES.ID_ADDED);
          return newHeading;
        }

      }

      function notWordCharacter(character) {
        if (!character)
          return true;

        return !(/\w/.test(character));
      }

      // This modifies the dialog for the 'link' plugin to allow the option of
      // internal document linking to autoid headings. Original 'link' plugin
      // code can be found at:
      // https://github.com/ckeditor/ckeditor-dev/tree/master/plugins/link

      function modifyLinkDialog(ev) {
        var dialog = ev.data;

        if (dialog.name == 'link') {
          var def = ev.data.definition,
            infoTab = def.contents[0],
            linkTypeTab = infoTab.elements[1];

          // Add option for heading links to linkType dropdown
          linkTypeTab.items.push(['Link to heading in the text', 'heading']);

          // Add additional content to 'Link Info' tab for heading links
          infoTab.elements.push(createHeadingLinkContent());

          // Modify linkType's 'onChange' function to accomodate new heading option
          linkTypeTab.onChange = modifiedLinkTypeChanged;
        }
      }

      function modifiedLinkTypeChanged() {
        var dialog = this.getDialog(),
          partIds = [ 'urlOptions', 'anchorOptions', 'emailOptions', 'headingOptions' ],
          typeValue = this.getValue(),
          uploadTab = dialog.definition.getContents( 'upload' ),
          uploadInitiallyHidden = uploadTab && uploadTab.hidden;

        if ( typeValue == 'url' ) {
          if ( editor.config.linkShowTargetTab )
            dialog.showPage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.showPage( 'upload' );
          } else {
            dialog.hidePage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.hidePage( 'upload' );
        }

        for ( var i = 0; i < partIds.length; i++ ) {
          var element = dialog.getContentElement( 'info', partIds[ i ] );
          if ( !element )
            continue;

          element = element.getElement().getParent().getParent();
          if ( partIds[ i ] == typeValue + 'Options' )
            element.show();
          else
            element.hide();
        }

        dialog.layout();
      }

      function createHeadingLinkContent() {
        var headings;

        return {
          type: 'vbox',
          id: 'headingOptions',
          children: [ {
            type: 'select',
            id: 'heading',
            label: 'Select a Heading',
            style: 'width : 100%;',
            items: [ [''] ],
            setup: function() {
              headings = findAllHeadings();

              this.getElement()[ headings && headings.count() ? 'show' : 'hide' ]();
            }
          },
          {
            type: 'html',
            id: 'noHeadings',
            style: 'text-align: center;',
            html: '
' + CKEDITOR.tools.htmlEncode( '(No headings available in the document)' ) + '
',
            // Focus the first element defined in above html.
            focus: true,
            setup: function() {
              this.getElement()[ headings && headings.count() ? 'hide' : 'show' ]();
            }
          } ]
        }
      }
    }
  });
})();
<|endoftext|>


<commit_before>var colIndex = 0;

var getRatingClass = function(value) {
    var rc = 0;

    if (value > 80) {
        rc = 4;
    } else if (value > 76 && value < 80) {
        rc = 3;
    } else if (value > 74 && value < 76) {
        rc = 2;
    } else if (value > 70 && value < 74) {
        rc = 1;
    }

    return rc;
};

var tileSource = $("#tile-template").html();
var tiletemplate = Handlebars.compile(tileSource);

function getTrivagoColor() {
    var colors = [
        "rgb(244, 143, 0)",
        "rgb(0, 127, 175)",
        "rgb(201, 74, 56)"
    ]
    if (colIndex < 2) {
        colIndex++;
    } else {
        colIndex = 0;
    }
    return colors[colIndex];
}

function fillColumns() {
    var source = $("#tile-template").html();
    var template = Handlebars.compile(source);
    $.getJSON("http://tripvago.ga/kartoffel/api/search/hotel-collection?path=8514", function function_name(data) {

        //         data.items.forEach(function(item) {
        //     var info = {
        //         hotelName: item.name,
        //         locationName: item.city,
        //         nights: 3,
        //         rating: getRatingClass(item.ratingValue),
        //         imageUrl: item.mainImage.extraLarge,
        //         priceFormatte: item.deals[0].price.formatted,
        //         stars: 'star_' + item.category
        //     };
        //     var $tile = tiletemplate(info);

        //     $('#target').append($tile);
        // });
        console.log(data);
        var context = {
            locationName: "Berlin",
            nights: "2",
            stars: "4",
            rating: "10",
            priceFormat: "100€"
        };
        var html = template(context);

        $("#mainColumns").append(html);
    })

}

$('#startDate').datetimepicker({
    locale: 'en',
    format: 'YYYY-MM-DD'
});

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if ([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);

var fillInital = function() {
    var AMOUNT = 11;
    var ROWS = 3;
    var i = 0;
    var k = 0;
    var source = $('#tile-template').html();
    var emptyTile = Handlebars.compile(source);
    var $item = emptyTile();
    var $tmp = '';

    for(i = 0; i < ROWS; i++) {
        $tmp = $('

');
        for(k = 0; k < AMOUNT; k++) {
            $tmp.append($item);
        }
        $('.hotel-collection-result .slick-wrapper').append($tmp);
    }
    $('.hotel-collection-result .tile:last').removeClass('is-active');
}
fillInital();

//fillColumns();

$('.center').slick({
    centerMode: true,
    centerPadding: '200px',
    slidesToShow: 3,
    focusOnSelect: true,
    slidesToScroll: 1,
    arrows: false,
    infinite: false,
    speed: 100,
    vertical: true,
    verticalSwiping: true
});
<commit_msg>basic implementation of data pulling<commit_after>var colIndex = 0;

var getRatingClass = function(value) {
    var rc = 0;

    if (value > 80) {
        rc = 4;
    } else if (value > 76 && value < 80) {
        rc = 3;
    } else if (value > 74 && value < 76) {
        rc = 2;
    } else if (value > 70 && value < 74) {
        rc = 1;
    }

    return rc;
};

var tileSource = $("#tile-template").html();
var tiletemplate = Handlebars.compile(tileSource);

function getTrivagoColor() {
    var colors = [
        "rgb(244, 143, 0)",
        "rgb(0, 127, 175)",
        "rgb(201, 74, 56)"
    ]
    if (colIndex < 2) {
        colIndex++;
    } else {
        colIndex = 0;
    }
    return colors[colIndex];
}

function fillColumn(locationId, startDate, endDate) {
    var url = "http://tripvago.ga/kartoffel/api/search/hotel-collection?path=" + locationId + "&start_date=" + startDate + "&end_date=" + endDate

    var source = $("#tile-template").html();
    var template = Handlebars.compile(source);

    var $tmp = $('

');
    $.getJSON(url, function function_name(data) {

        data.items.forEach(function(item) {
            var info = {
                hotelName: item.name,
                locationName: item.city,
                nights: 3,
                rating: getRatingClass(item.ratingValue),
                imageUrl: item.mainImage.extraLarge,
                priceFormatte: item.deals[0].price.formatted,
                stars: 'star_' + item.category
            };

            var context = {
                locationName: "Berlin",
                nights: "2",
                stars: "4",
                rating: "10",
                priceFormat: "100€"
            };
            var html = template(info);

            $tmp.append(html);
        });
        $('.hotel-collection-result').append($tmp);
    });
}

$('#startDate').datetimepicker({
    locale: 'en',
    format: 'YYYY-MM-DD'
});

window.addEventListener("keydown", function(e) {
    // space and arrow keys
    if ([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);

var fillInital = function() {
    var AMOUNT = 11;
    var ROWS = 2;
    var i = 0;
    var k = 0;

    var source = $('#tile-template-empty').html();
    var emptyTile = Handlebars.compile(source);
    var $item = emptyTile();
    var $tmp = '';

    for (i = 0; i < ROWS; i++) {
        $tmp = $('

');
        for (k = 0; k < AMOUNT; k++) {
            $tmp.append($item);
        }
        $('.hotel-collection-result .slick-wrapper').append($tmp);
    }
    $('.hotel-collection-result .tile:last').removeClass('is-active');
};
fillColumn("8514", "2016-08-20", "2016-08-25");
fillInital();

$('.center').slick({
    centerMode: true,
    centerPadding: '200px',
    slidesToShow: 3,
    focusOnSelect: true,
    slidesToScroll: 1,
    arrows: false,
    infinite: false,
    speed: 100,
    vertical: true,
    verticalSwiping: true
});<|endoftext|>


<commit_before>'use babel';
import fs from 'fs';
import path from 'path';
import {CompositeDisposable} from 'atom';
import resolve from 'resolve';
import mkdirp from 'mkdirp';
import stylusFallback from 'stylus';
import {initView, deinitView, showView} from './stylus-autocompile-view.js';

export var config = {
  statusBarMessageTimeout: {
    description: 'Timeout before the status bar message disappears',
    type: 'integer',
    default: '5000',
    minimum: 0,
  },
};

var disposable;

export function activate() {
  disposable = new CompositeDisposable(
    atom.commands.add('atom-text-editor', 'core:save', ({currentTarget}) =>
      handleSave(currentTarget)
    )
  );
}

export function deactivate() {
  disposable.dispose();
  disposable = null;
  deinitView();
}

export function consumeStatusBar(statusBar) {
  initView(statusBar);
}

const stylusGrammar = ['source.css.stylus', 'source.stylus']
  .map((scopeName) => atom.grammars.grammarForScopeName(scopeName))
  .find(x => x);

function handleSave(textEditorElement) {
  var textEditor;
  if (typeof textEditorElement.getModel != 'function') return;
  textEditor = textEditorElement.getModel();
  if (typeof textEditor.getGrammar != 'function') return;
  if (textEditor.getGrammar() == stylusGrammar) {
    compile(textEditor.getText(), textEditor.getURI());
  }
}

function compile(source, URI) {
  var params = getParams(source);

  if (params == null) return;

  if (params.main) {
    var mainPath = path.resolve(path.dirname(URI), `${params.main}`);
    fs.readFile(mainPath, 'utf8', (err, mainSource) => {
      if (err) return atom.notifications.addError(`Error while reading file: ${mainPath}`);
      compile(mainSource, mainPath);
    });
  }

  if (params.out) {
    params.inPath = URI;
    params.outPath = path.resolve(path.dirname(URI), `${params.out}`);
    render(source, params);
  }
}

function render(source, params) {
  var {inPath, compress, sourcemap, outPath, libs} = params;
  var fileDir = path.dirname(path.resolve(inPath));
  getStylusExecutable(fileDir).then(stylus =>
    stylus(source)
      .set('paths', [fileDir])
      .set('filename', path.basename(inPath))
      .set('dest', outPath)
      .set('compress', compress)
      .set('sourcemap', sourcemap)
  ).then(renderer =>
    includeLibs(fileDir, renderer, libs)
  ).then(renderer =>
    renderer.render((error, css) => {
      if (error) return showView('error', error.message, `${error.filename}: ${error.line}`);

      writeFile(css, outPath);
      if (renderer.sourcemap) {
        writeFile(JSON.stringify(renderer.sourcemap), `${outPath}.map`);
      }
    })
  ).catch(error =>
    showView('error', error.message)
  );
}

function getStylusExecutable(basedir) {
  return getModulePath(basedir, 'stylus').then(filename => {
    try {
      return require(filename);
    } catch (e) {
      return stylusFallback;
    }
  });
}

function includeLibs(basedir, renderer, libs) {
  return Promise.all(libs.map(lib =>
    getModulePath(basedir, lib).then(filename =>
      renderer.use(require(filename)())
    )
  )).then(([renderer]) => renderer);
}

function getModulePath(basedir, module) {
  return new Promise((accept, reject) =>
    resolve(module, {basedir}, (error, filename) => {
      error ? reject(error) : accept(filename);
    })
  );
}

function writeFile(content, filePath) {
  mkdirp(path.dirname(filePath), error => {
    if (error) return showView('error', error.message);

    fs.writeFile(filePath, content, error => {
      if (error) return showView('error', error.message);

      showView('success', getRelativePath(filePath));
    });
  });
}

function getProjectPath(filePath) {
  for (let projectPath of atom.project.getPaths()) {
    if (filePath.match(projectPath)) return projectPath;
  }
}

function getRelativePath(filePath) {
  var regex = new RegExp(`^${getProjectPath(filePath)}/?`);
  return filePath.replace(regex, '');
}

// match the first comment in the file
function getParams(source) {
  var [, paramString] = source.match(/^\s*\/\/(.*)$/m) || [];
  if (!paramString) return;

  paramString = paramString.trim();
  var main = getParam(paramString, 'main');
  var out = getParam(paramString, 'out');
  if (!out) return main ? {main} : null;

  var compress = parseBool(getParam(paramString, 'compress', true));
  var sourcemap = parseBool(getParam(paramString, 'sourcemap', true));
  var libs = parseArray(getParam(paramString, 'libs', false));
  return {main, out, compress, sourcemap, libs};
}

function getParam(paramString, key) {
  var regex = new RegExp(`${key}\s*:\s*([^,]+)`);
  var [, value] = paramString.match(regex) || [, ''];
  return value.trim();
}

function parseBool(value) {
  return value == 'false' ?  false : !!value;
}

function parseArray(value) {
  return value.split(/\s/).filter(x => x);
}
<commit_msg>fix issue when no libs specified<commit_after>'use babel';
import fs from 'fs';
import path from 'path';
import {CompositeDisposable} from 'atom';
import resolve from 'resolve';
import mkdirp from 'mkdirp';
import stylusFallback from 'stylus';
import {initView, deinitView, showView} from './stylus-autocompile-view.js';

export var config = {
  statusBarMessageTimeout: {
    description: 'Timeout before the status bar message disappears',
    type: 'integer',
    default: '5000',
    minimum: 0,
  },
};

var disposable;

export function activate() {
  disposable = new CompositeDisposable(
    atom.commands.add('atom-text-editor', 'core:save', ({currentTarget}) =>
      handleSave(currentTarget)
    )
  );
}

export function deactivate() {
  disposable.dispose();
  disposable = null;
  deinitView();
}

export function consumeStatusBar(statusBar) {
  initView(statusBar);
}

const stylusGrammar = ['source.css.stylus', 'source.stylus']
  .map((scopeName) => atom.grammars.grammarForScopeName(scopeName))
  .find(x => x);

function handleSave(textEditorElement) {
  var textEditor;
  if (typeof textEditorElement.getModel != 'function') return;
  textEditor = textEditorElement.getModel();
  if (typeof textEditor.getGrammar != 'function') return;
  if (textEditor.getGrammar() == stylusGrammar) {
    compile(textEditor.getText(), textEditor.getURI());
  }
}

function compile(source, URI) {
  var params = getParams(source);

  if (params == null) return;

  if (params.main) {
    var mainPath = path.resolve(path.dirname(URI), `${params.main}`);
    fs.readFile(mainPath, 'utf8', (err, mainSource) => {
      if (err) return atom.notifications.addError(`Error while reading file: ${mainPath}`);
      compile(mainSource, mainPath);
    });
  }

  if (params.out) {
    params.inPath = URI;
    params.outPath = path.resolve(path.dirname(URI), `${params.out}`);
    render(source, params);
  }
}

function render(source, params) {
  var {inPath, compress, sourcemap, outPath, libs} = params;
  var fileDir = path.dirname(path.resolve(inPath));
  getStylusExecutable(fileDir).then(stylus =>
    stylus(source)
      .set('paths', [fileDir])
      .set('filename', path.basename(inPath))
      .set('dest', outPath)
      .set('compress', compress)
      .set('sourcemap', sourcemap)
  ).then(renderer =>
    includeLibs(fileDir, renderer, libs)
  ).then(renderer =>
    renderer.render((error, css) => {
      if (error) return showView('error', error.message, `${error.filename}: ${error.line}`);

      writeFile(css, outPath);
      if (renderer.sourcemap) {
        writeFile(JSON.stringify(renderer.sourcemap), `${outPath}.map`);
      }
    })
  ).catch(error =>
    showView('error', error.message)
  );
}

function getStylusExecutable(basedir) {
  return getModulePath(basedir, 'stylus').then(filename => {
    try {
      return require(filename);
    } catch (e) {
      return stylusFallback;
    }
  });
}

function includeLibs(basedir, renderer, libs) {
  return !libs.length ? renderer : Promise.all(libs.map(lib =>
    getModulePath(basedir, lib).then(filename =>
      renderer.use(require(filename)())
    )
  )).then(([renderer]) => renderer);
}

function getModulePath(basedir, module) {
  return new Promise((accept, reject) =>
    resolve(module, {basedir}, (error, filename) => {
      error ? reject(error) : accept(filename);
    })
  );
}

function writeFile(content, filePath) {
  mkdirp(path.dirname(filePath), error => {
    if (error) return showView('error', error.message);

    fs.writeFile(filePath, content, error => {
      if (error) return showView('error', error.message);

      showView('success', getRelativePath(filePath));
    });
  });
}

function getProjectPath(filePath) {
  for (let projectPath of atom.project.getPaths()) {
    if (filePath.match(projectPath)) return projectPath;
  }
}

function getRelativePath(filePath) {
  var regex = new RegExp(`^${getProjectPath(filePath)}/?`);
  return filePath.replace(regex, '');
}

// match the first comment in the file
function getParams(source) {
  var [, paramString] = source.match(/^\s*\/\/(.*)$/m) || [];
  if (!paramString) return;

  paramString = paramString.trim();
  var main = getParam(paramString, 'main');
  var out = getParam(paramString, 'out');
  if (!out) return main ? {main} : null;

  var compress = parseBool(getParam(paramString, 'compress', true));
  var sourcemap = parseBool(getParam(paramString, 'sourcemap', true));
  var libs = parseArray(getParam(paramString, 'libs', false));
  return {main, out, compress, sourcemap, libs};
}

function getParam(paramString, key) {
  var regex = new RegExp(`${key}\s*:\s*([^,]+)`);
  var [, value] = paramString.match(regex) || [, ''];
  return value.trim();
}

function parseBool(value) {
  return value == 'false' ?  false : !!value;
}

function parseArray(value) {
  return value.split(/\s/).filter(x => x);
}
<|endoftext|>


<commit_before>
function TwiddlersCount() {
	this.baseUrl = '';
	this.title = undefined;
	this.currentUser = tiddlyweb.status.username;
	this.targetURI = window.location.href.match(/tiddlyspace/) ?
		'replanadu' : 'replanadu.html';
	this._init();
}

TwiddlersCount.prototype.search = function() {
	this._getFollowers();
};

TwiddlersCount.prototype._init = function() {
	this.title = $('#title').text();;
}

TwiddlersCount.prototype._getFollowers = function() {
	var context = this;
	var success = function(data, status, xhr) {
		var followers = data.split('\n');
		context._search(followers);
	};
	var url = '/search.txt?q=bag:' + this.currentUser + '_public%20tag:follow';
	this._doGET(url, success, this._ajaxError);
};

TwiddlersCount.prototype.addButton = function(value) {
	var button = $("Twiddlers");
	button.attr('id', '#twiddlers');
	button.attr('target', '_blank');
	button.attr('data-twiddlerall', value);
	button.attr('href', '/' + this.targetURI + '#'
			+ encodeURIComponent(this.title));
	button.addClass('twiddlers');
	button.addClass('twiddlerall');
	$('#container').append(button);
}

TwiddlersCount.prototype.updateButton = function(value) {
	var button = $('#twiddlers');
	button.attr('data-tiddlerfollow', value);
	button.addClass('twiddlerfollow');
};

TwiddlersCount.prototype._followSearch = function(followers) {
	var context = this;
	var followSuccess = function(data, status, xhr) {
		context.updateButton(data.split('\n').length);
	};
	var followUrl = '/search.txt?q=title:"' + encodeURIComponent(this.title) +
		'"%20' + followers.join('%20OR%20');
	this._doGET(followUrl, followSuccess, this._ajaxError);
};

TwiddlersCount.prototype._search = function(followers) {
	var context = this;
	var allSuccess = function(data, status, xhr) {
		context.addButton(data.split('\n').length);
		context._followSearch(followers);
	};
	var allUrl = '/search.txt?q=title:"' + encodeURIComponent(this.title) +
		'"';
	this._doGET(allUrl, allSuccess, this._ajaxError);
};

TwiddlersCount.prototype._doGET = function(url, success, error) {
	$.ajax({
	    url: url,
        type: 'GET',
        success: success,
        error: error,
        headers: { 'X-ControlView': 'false' },
        contentType: 'text/plain',
        dataType: 'text'
	});
};

TwiddlersCount.prototype._ajaxError = function(xhr, err, exc) {
	console.log('Error', err, exc);
};

$(document).ready(function () {
	new TwiddlersCount().search();
});
<commit_msg>Changed search handling to do two searches<commit_after>
function TwiddlersCount() {
	this.baseUrl = '';
	this.title = undefined;
	this.currentUser = tiddlyweb.status.username;
	this.targetURI = window.location.href.match(/tiddlyspace/) ?
		'replanadu' : 'replanadu.html';
	this._init();
}

TwiddlersCount.prototype.search = function() {
	this._getFollowers();
};

TwiddlersCount.prototype._init = function() {
	this.title = $('#title').text();;
}

TwiddlersCount.prototype._getFollowers = function() {
	var context = this;
	var success = function(data, status, xhr) {
		var followers = $.trim(data).split('\n');
		followers = $.map(followers, function(item) {
			return item.replace(/^@/, '');
		});
		context._search(followers);
	};
	var url = '/search.txt?q=bag:' + this.currentUser
		+ '_public%20tag:follow'
		+ '%20_limit:999';
	this._doGET(url, success, this._ajaxError);
};

TwiddlersCount.prototype.addButton = function(value) {
	var button = $("Twiddlers");
	button.attr('id', '#twiddlers');
	button.attr('target', '_blank');
	button.attr('data-twiddlerall', value);
	button.attr('href', '/' + this.targetURI + '#'
			+ encodeURIComponent(this.title));
	button.addClass('twiddlers');
	button.addClass('twiddlerall');
	$('#container').append(button);
}

TwiddlersCount.prototype.updateButton = function(value) {
	var button = $('#twiddlers');
	button.attr('data-tiddlerfollow', value);
	button.addClass('twiddlerfollow');
};

TwiddlersCount.prototype._followSearch = function(followers) {
	var context = this;
	var followSuccess = function(data, status, xhr) {
		context.updateButton($.trim(data).split('\n').length);
	};
	var followUrl = '/search.txt?q=title:"' + encodeURIComponent(this.title) +
		'"%20' + 'modifier:' + followers.join('%20OR%20modifier:');
	this._doGET(followUrl, followSuccess, this._ajaxError);
};

TwiddlersCount.prototype._search = function(followers) {
	var context = this;
	var allSuccess = function(data, status, xhr) {
		context.addButton($.trim(data).split('\n').length);
		context._followSearch(followers);
	};
	var allUrl = '/search.txt?q=title:"' + encodeURIComponent(this.title) +
		'"';
	this._doGET(allUrl, allSuccess, this._ajaxError);
};

TwiddlersCount.prototype._doGET = function(url, success, error) {
	$.ajax({
	    url: url,
        type: 'GET',
        success: success,
        error: error,
        headers: { 'X-ControlView': 'false' },
        contentType: 'text/plain',
        dataType: 'text'
	});
};

TwiddlersCount.prototype._ajaxError = function(xhr, err, exc) {
	console.log('Error', err, exc);
};

$(document).ready(function () {
	new TwiddlersCount().search();
});
<|endoftext|>


<commit_before>'use strict';

(function () {
  var EVENT_NAMES = {
    ALL_IDS_COMPLETE: 'allIdsComplete',
    ID_ADDED: 'idAdded',
    ID_RETAINED: 'idRetained'
  };

  CKEDITOR.plugins.add('autoid', {
    init: function (editor) {
      var self = this;

      // This configures the Advanced Content Filter to allow all headings
      // to have id attributes
      editor.addFeature({
        allowedContent: 'h1 h2 h3 h4 h5 h6 *[id]'
      });

      if (editor && !editor.config.autoid) {
        editor.config.autoid = {};
      }
      self.settings = editor.config.autoid;
      if (!self.settings) {
        self.settings = {};
      }

      editor.addCommand('autoid', {
        exec: function (editor) {
          var autoId = editor.getCommand('autoid');
          autoId.toggleState();
          if (autoId.state === CKEDITOR.TRISTATE_ON)
            addAllIds();
        },
        editorFocus: true
      });

      editor.on("instanceReady", function () {
        if (self.settings.autostart !== false) {
          editor.getCommand('autoid').setState(CKEDITOR.TRISTATE_ON);
          addAllIds();
        }
      });

      CKEDITOR.on('dialogDefinition', modifyLinkDialog);

      editor.on('selectionChange', addIdIfNewHeading);

      editor.on('paste', checkPastedContentForHeadings);

      function addAllIds() {
        var headings = findAllHeadings(),
          i, heading;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (heading.hasAttribute('id')) {
            continue;
          }
          addId(heading);
        }
        editor.fire(EVENT_NAMES.ALL_IDS_COMPLETE);
      }

      function findAllHeadings() {
        return editor.document.find('h1, h2, h3, h4, h5, h6');
      }

      function findHeadingIds(headings) {
        var ids = [],
          i, heading, id;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (id = heading.getAttribute('id')) {
            ids.push(id)
          }
        }
        return ids;
      }

      function addId(heading) {
        var uuid = CKEDITOR.tools.getUniqueId();
        heading.setAttributes({ id: uuid });
        editor.fire(EVENT_NAMES.ID_ADDED);
      }

      function addIdIfNewHeading() {
        var element = editor.getSelection().getStartElement();
        if (isHeading(element) && !element.hasAttribute('id')) {
          addId(element);
        }
      }

      function isHeading(element) {
        return element.is('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
      }

      function checkPastedContentForHeadings(ev) {
        var pastedContent = ev.data.dataValue,
          pastedContentAsHtml = CKEDITOR.htmlParser.fragment.fromHtml(pastedContent),
          pastedElements = pastedContentAsHtml.children,
          writer = new CKEDITOR.htmlParser.basicWriter(),
          i, element, id, originalHeading;

        for (i = 0; i < pastedElements.length; i++) {
          element = pastedElements[i];
          if (element.type === CKEDITOR.NODE_ELEMENT) {
            id = element.attributes.id;
            originalHeading = checkForDuplicateId(id);
            if (originalHeading) {
              element = resolveDuplicateIds(element, originalHeading);
            }
          }
        }

        pastedContentAsHtml.writeHtml(writer);
        ev.data.dataValue = writer.getHtml();
      }

      function checkForDuplicateId(id) {
        var headingIds = findHeadingIds(findAllHeadings()),
          i, headingId, originalHeading;

        for (i = 0; i < headingIds.length; i++) {
          headingId = headingIds[i];
          if (id === headingId) {
            return originalHeading = editor.document.getById(headingId);
          }
        }
      }

      function resolveDuplicateIds(newHeading, originalHeading) {
        var newHeadingText = newHeading.children[0].value,
          originalHeadingText = originalHeading.getText();

        // if the original heading has no content (blank or just a line-feed
        // character is left when all the content is cut), the original heading
        // will be removed and the new heading will retain the id
        if ( originalHeadingText.length <= 1 && notWordCharacter(originalHeadingText.charAt(0))) {
          originalHeading.remove();
          editor.fire(EVENT_NAMES.ID_RETAINED);
          return newHeading;
        }

        // if the original heading text is not blank, the original should retain its
        // id and the new heading should get a new one.
        if (originalHeadingText) {
          newHeading.attributes.id = CKEDITOR.tools.getUniqueId();
          editor.fire(EVENT_NAMES.ID_ADDED);
          return newHeading;
        }

      }

      function notWordCharacter(character) {
        if (!character)
          return true;

        return !(/\w/.test(character));
      }

      // This modifies the dialog for the 'link' plugin to allow the option of
      // internal document linking to autoid headings. Original 'link' plugin
      // code can be found at:
      // https://github.com/ckeditor/ckeditor-dev/tree/master/plugins/link

      function modifyLinkDialog(ev) {
        var dialog = ev.data;

        if (dialog.name == 'link') {
          var def = ev.data.definition,
            infoTab = def.contents[0],
            linkTypeTab = infoTab.elements[1];

          // Add option for heading links to linkType dropdown
          linkTypeTab.items.push(['Link to heading in the text', 'heading']);

          // Add additional content to 'Link Info' tab for heading links
          infoTab.elements.push(createHeadingLinkContent());

          // Modify linkType's 'onChange' function to accomodate new heading option
          linkTypeTab.onChange = modifiedLinkTypeChanged;
        }
      }

      function modifiedLinkTypeChanged() {
        var dialog = this.getDialog(),
          partIds = [ 'urlOptions', 'anchorOptions', 'emailOptions', 'headingOptions' ],
          typeValue = this.getValue(),
          uploadTab = dialog.definition.getContents( 'upload' ),
          uploadInitiallyHidden = uploadTab && uploadTab.hidden;

        if ( typeValue == 'url' ) {
          if ( editor.config.linkShowTargetTab )
            dialog.showPage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.showPage( 'upload' );
          } else {
            dialog.hidePage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.hidePage( 'upload' );
        }

        for ( var i = 0; i < partIds.length; i++ ) {
          var element = dialog.getContentElement( 'info', partIds[ i ] );
          if ( !element )
            continue;

          element = element.getElement().getParent().getParent();
          if ( partIds[ i ] == typeValue + 'Options' )
            element.show();
          else
            element.hide();
        }

        dialog.layout();
      }

      function createHeadingLinkContent() {
        var headings;

        return {
          type: 'vbox',
          id: 'headingOptions',
          children: [ {
            type: 'select',
            id: 'heading',
            label: 'Select a Heading',
            style: 'width : 100%;',
            items: [ [''] ],
            setup: function() {
              headings = findAllHeadings();

              this.getElement()[ headings && headings.count() ? 'show' : 'hide' ]();
            }
          },
          {
            type: 'html',
            id: 'noHeadings',
            style: 'text-align: center;',
            html: '
' + CKEDITOR.tools.htmlEncode( '(No headings available in the document)' ) + '
',
            // Focus the first element defined in above html.
            focus: true,
            setup: function() {
              this.getElement()[ headings && headings.count() ? 'hide' : 'show' ]();
            }
          } ]
        }
      }
    }
  });
})();
<commit_msg>Add headings and heading id values to the select dropdown<commit_after>'use strict';

(function () {
  var EVENT_NAMES = {
    ALL_IDS_COMPLETE: 'allIdsComplete',
    ID_ADDED: 'idAdded',
    ID_RETAINED: 'idRetained'
  };

  CKEDITOR.plugins.add('autoid', {
    init: function (editor) {
      var self = this;

      // This configures the Advanced Content Filter to allow all headings
      // to have id attributes
      editor.addFeature({
        allowedContent: 'h1 h2 h3 h4 h5 h6 *[id]'
      });

      if (editor && !editor.config.autoid) {
        editor.config.autoid = {};
      }
      self.settings = editor.config.autoid;
      if (!self.settings) {
        self.settings = {};
      }

      editor.addCommand('autoid', {
        exec: function (editor) {
          var autoId = editor.getCommand('autoid');
          autoId.toggleState();
          if (autoId.state === CKEDITOR.TRISTATE_ON)
            addAllIds();
        },
        editorFocus: true
      });

      editor.on("instanceReady", function () {
        if (self.settings.autostart !== false) {
          editor.getCommand('autoid').setState(CKEDITOR.TRISTATE_ON);
          addAllIds();
        }
      });

      CKEDITOR.on('dialogDefinition', modifyLinkDialog);

      editor.on('selectionChange', addIdIfNewHeading);

      editor.on('paste', checkPastedContentForHeadings);

      function addAllIds() {
        var headings = findAllHeadings(),
          i, heading;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (heading.hasAttribute('id')) {
            continue;
          }
          addId(heading);
        }
        editor.fire(EVENT_NAMES.ALL_IDS_COMPLETE);
      }

      function findAllHeadings() {
        return editor.document.find('h1, h2, h3, h4, h5, h6');
      }

      function findHeadingIds(headings) {
        var ids = [],
          i, heading, id;

        for (i = 0; i < headings.count(); i++) {
          heading = headings.getItem(i);
          if (id = heading.getAttribute('id')) {
            ids.push(id)
          }
        }
        return ids;
      }

      function addId(heading) {
        var uuid = CKEDITOR.tools.getUniqueId();
        heading.setAttributes({ id: uuid });
        editor.fire(EVENT_NAMES.ID_ADDED);
      }

      function addIdIfNewHeading() {
        var element = editor.getSelection().getStartElement();
        if (isHeading(element) && !element.hasAttribute('id')) {
          addId(element);
        }
      }

      function isHeading(element) {
        return element.is('h1', 'h2', 'h3', 'h4', 'h5', 'h6');
      }

      function checkPastedContentForHeadings(ev) {
        var pastedContent = ev.data.dataValue,
          pastedContentAsHtml = CKEDITOR.htmlParser.fragment.fromHtml(pastedContent),
          pastedElements = pastedContentAsHtml.children,
          writer = new CKEDITOR.htmlParser.basicWriter(),
          i, element, id, originalHeading;

        for (i = 0; i < pastedElements.length; i++) {
          element = pastedElements[i];
          if (element.type === CKEDITOR.NODE_ELEMENT) {
            id = element.attributes.id;
            originalHeading = checkForDuplicateId(id);
            if (originalHeading) {
              element = resolveDuplicateIds(element, originalHeading);
            }
          }
        }

        pastedContentAsHtml.writeHtml(writer);
        ev.data.dataValue = writer.getHtml();
      }

      function checkForDuplicateId(id) {
        var headingIds = findHeadingIds(findAllHeadings()),
          i, headingId, originalHeading;

        for (i = 0; i < headingIds.length; i++) {
          headingId = headingIds[i];
          if (id === headingId) {
            return originalHeading = editor.document.getById(headingId);
          }
        }
      }

      function resolveDuplicateIds(newHeading, originalHeading) {
        var newHeadingText = newHeading.children[0].value,
          originalHeadingText = originalHeading.getText();

        // if the original heading has no content (blank or just a line-feed
        // character is left when all the content is cut), the original heading
        // will be removed and the new heading will retain the id
        if ( originalHeadingText.length <= 1 && notWordCharacter(originalHeadingText.charAt(0))) {
          originalHeading.remove();
          editor.fire(EVENT_NAMES.ID_RETAINED);
          return newHeading;
        }

        // if the original heading text is not blank, the original should retain its
        // id and the new heading should get a new one.
        if (originalHeadingText) {
          newHeading.attributes.id = CKEDITOR.tools.getUniqueId();
          editor.fire(EVENT_NAMES.ID_ADDED);
          return newHeading;
        }

      }

      function notWordCharacter(character) {
        if (!character)
          return true;

        return !(/\w/.test(character));
      }

      // This modifies the dialog for the 'link' plugin to allow the option of
      // internal document linking to autoid headings. Original 'link' plugin
      // code can be found at:
      // https://github.com/ckeditor/ckeditor-dev/tree/master/plugins/link

      function modifyLinkDialog(ev) {
        var dialog = ev.data;

        if (dialog.name == 'link') {
          var def = ev.data.definition,
            infoTab = def.contents[0],
            linkTypeTab = infoTab.elements[1];

          // Add option for heading links to linkType dropdown
          linkTypeTab.items.push(['Link to heading in the text', 'heading']);

          // Add additional content to 'Link Info' tab for heading links
          infoTab.elements.push(createHeadingLinkContent());

          // Modify linkType's 'onChange' function to accomodate new heading option
          linkTypeTab.onChange = modifiedLinkTypeChanged;
        }
      }

      function modifiedLinkTypeChanged() {
        var dialog = this.getDialog(),
          partIds = [ 'urlOptions', 'anchorOptions', 'emailOptions', 'headingOptions' ],
          typeValue = this.getValue(),
          uploadTab = dialog.definition.getContents( 'upload' ),
          uploadInitiallyHidden = uploadTab && uploadTab.hidden;

        if ( typeValue == 'url' ) {
          if ( editor.config.linkShowTargetTab )
            dialog.showPage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.showPage( 'upload' );
          } else {
            dialog.hidePage( 'target' );
          if ( !uploadInitiallyHidden )
            dialog.hidePage( 'upload' );
        }

        for ( var i = 0; i < partIds.length; i++ ) {
          var element = dialog.getContentElement( 'info', partIds[ i ] );
          if ( !element )
            continue;

          element = element.getElement().getParent().getParent();
          if ( partIds[ i ] == typeValue + 'Options' )
            element.show();
          else
            element.hide();
        }

        dialog.layout();
      }

      function createHeadingLinkContent() {
        var headings;

        return {
          type: 'vbox',
          id: 'headingOptions',
          children: [ {
            type: 'select',
            id: 'heading',
            label: 'Select a Heading',
            style: 'width : 100%;',
            items: [ [ '' ] ],
            setup: function() {
              this.clear();
              this.add( [ '' ] );

              headings = findAllHeadings();

              if (headings && headings.count()) {
                this.getElement().show();

                for (var i = 0; i < headings.count(); i++) {
                  var heading = headings.getItem(i);
                  this.add( heading.getText(), heading.getId() );
                }
              }
              else {
                this.getElement().hide();
              }
            }
          },
          {
            type: 'html',
            id: 'noHeadings',
            style: 'text-align: center;',
            html: '
' + CKEDITOR.tools.htmlEncode( '(No headings available in the document)' ) + '
',
            // Focus the first element defined in above html.
            focus: true,
            setup: function() {
              this.getElement()[ headings && headings.count() ? 'hide' : 'show' ]();
            }
          } ]
        }
      }
    }
  });
})();
<|endoftext|>


<commit_before>// Start server cluster
//
// In cluster mode it forks N http workers + N queue workers.
//
// In single mode it emits `init:server.worker-http` and
// `init:server.worker-queue` events instead
//
'use strict';

const _            = require('lodash');
const cluster      = require('cluster');
const co           = require('co');
const execFile     = require('mz/child_process').execFile;
const os           = require('os');
const inherits     = require('util').inherits;
const EventEmitter = require('events').EventEmitter;
const StateMachine = require('javascript-state-machine');

////////////////////////////////////////////////////////////////////////////////

function WorkerPool(size, worker) {
  if (!(this instanceof WorkerPool)) return new WorkerPool(size, worker);

  EventEmitter.call(this);

  this.__workers = [];
  this.__wClass  = worker;
  this.__size    = 0;

  this.update = _.debounce(() => {
    process.nextTick(() => {
      this.resize();
      this.gc();
    });
  }, 100, { maxWait: 200 });

  this.resize(size);
}

WorkerPool.prototype = {
  log() {
    /*eslint-disable no-console*/
    console.log.apply(null, arguments);
  },

  resize(count) {
    // Use current value if no params
    if (!count && count !== 0) {
      count = this.__size;
    }

    let alive = this.get([ 'INIT', 'START', 'RUN' ]),
        delta = count - alive.length,
        prev_size = this.__size;

    this.__size = count;

    if (delta === 0) return;

    if (delta > 0) {
      while (delta--) {
        let w = this.__wClass(this);
        this.__workers.push(w);
        // Force immediate start for the first run
        if (prev_size === 0 && w.can('start')) w.start();
      }
      return;
    }

    alive.slice(0, -delta).forEach(w => { w.shutdown(); });
  },

  terminate() {
    // prevent workers from being respawned
    this.__size = 0;

    this.__workers.forEach(w => { w.terminate(); });
  },

  reload() {
    this.__workers.forEach(w => {
      if (w.can('freeze')) w.freeze();
    });
  },

  get(state) {
    if (!Array.isArray(state)) {
      return this.__workers.filter(w => w.current === state);
    }
    return state.reduce((a, s) => a.concat(this.get(s)), []);
  },

  gc() {
    // Shutdown pending workers when not needed
    let excess = Math.max((this.get('PEND').length + this.get('RUN').length - this.__size), 0);

    this.get('PEND').slice(0, excess).forEach(w => { w.shutdown(); });

    // Drop dead workers
    this.__workers = this.__workers.filter(w => w.current !== 'DEAD');
  }
};

Object.setPrototypeOf(WorkerPool.prototype, EventEmitter.prototype);

////////////////////////////////////////////////////////////////////////////////

function Worker(pool) {
  if (!(this instanceof Worker)) return new Worker(pool);
  this.__pool          = pool;
  this.__w             = null;
  this.__start_timeout = 0;
  this.__exit_code     = null;

  this.begin();
}

Worker.prototype = {
  create() {
    throw new Error('This method should be overriden');
  },

  terminate() {
    if (this.__w) this.__w.kill('SIGKILL');
    else this.die();
  },

  onchangestate() {
    this.__pool.update();
  },

  onINIT() {
    setTimeout(() => {
      if (this.can('start')) this.start();
    }, 2000);
  },

  onSTART() {
    let w = this.__w = this.fork();
    let rcvd_startup_message = false;

    this.__pool.log.info(`Worker ${w.process.pid} spawned`);
    this.__pool.emit('spawn', w.process.pid);

    w.on('error', err => {
      this.__pool.log.error(err);
      this.die();
    });

    w.on('exit', (code, signal) => {
      this.__exit_code = signal || code;
      this.die();
    });

    w.on('message', msg => {
      if (msg === 'worker.running') {
        rcvd_startup_message = true;
        if (this.can('run')) this.run();
      }
    });

    setTimeout(() => {
      if (!rcvd_startup_message) this.terminate();
    }, 30000);
  },

  onSTOP() {
    this.__w.kill('SIGTERM');
    setTimeout(() => this.terminate(), 15000);
  },

  onRUN() {
    let w = this.__w;
    this.__pool.log.info(`Worker ${w.process.pid} is running`);
    this.__pool.emit('running', w.process.pid);
  },

  onDEAD() {
    let w = this.__w;

    // We can come here if process did not started.
    if (w) {
      this.__pool.log.info(`Worker ${w.process.pid} exited with status ${this.__exit_code}`);
      this.__pool.emit('exit', w.process.pid);
    }

    w.removeAllListeners();
    this.__w = null;
  }
};

StateMachine.create({
  events: [
    { name: 'begin',     from: 'none',   to: 'INIT'  },
    { name: 'start',     from: 'INIT',   to: 'START' },
    { name: 'run',       from: 'START',  to: 'RUN'   },

    { name: 'freeze',    from: 'RUN',    to: 'PEND'  },
    { name: 'freeze',    from: 'START',  to: 'DEAD'  },

    { name: 'shutdown',  from: 'RUN',    to: 'STOP'  },
    { name: 'shutdown',  from: 'PEND',   to: 'STOP'  },

    { name: 'die',       from: '*',      to: 'DEAD'  }
  ]
}, Worker.prototype);

////////////////////////////////////////////////////////////////////////////////

function WorkerQueue(pool) {
  if (!(this instanceof WorkerQueue)) return new WorkerQueue(pool);
  Worker.call(this, pool);
}

inherits(WorkerQueue, Worker);

WorkerQueue.prototype.fork = function () {
  cluster.setupMaster({ args: [ 'worker-queue' ] });

  let worker = cluster.fork(),
      log = this.__pool.log;

  worker.on('online', co.wrap(function* () {
    try {
      // Set scheduling policy to SCHED_IDLE (`-i` flag);
      // `0` is only possible value for priority ('cause this policy doesn't allow to set it)
      yield execFile('chrt', [ '-i', '-p', '0', worker.process.pid ]);
    } catch (__) {
      // If `chrt` not exists, try fallback to `renice`.
      try {
        yield execFile('renice', [ '-n', '19', '-p', worker.process.pid ]);
        log.warn('Cannot set scheduling policy for queue using `chrt`, falling back to `renice`');
      } catch (___) {
        log.error('Cannot lower priority for queue ' +
          '(both `renice` and `chrt` have failed), continuing with default priority');
      }
    }
  }));

  return worker;
};

////////////////////////////////////////////////////////////////////////////////

function WorkerHttp(pool) {
  if (!(this instanceof WorkerHttp)) return new WorkerHttp(pool);
  Worker.call(this, pool);
}

inherits(WorkerHttp, Worker);

WorkerHttp.prototype.fork = function () {
  cluster.setupMaster({ args: [ 'worker-http' ] });
  return cluster.fork();
};

////////////////////////////////////////////////////////////////////////////////

module.exports = function (N) {

  N.wire.on('init:server', function* cluster_init(N) {
    let fork = N.config.fork;

    if (fork === 'auto' || fork === true || _.isUndefined(fork)) {
      fork = os.cpus().length;
    } else {
      fork = +fork || 0;
    }

    if (cluster.isMaster && (fork >= 1)) {
      WorkerPool.prototype.log = N.logger;

      /*eslint-disable new-cap*/
      let pools = [
        WorkerPool(fork, WorkerQueue),
        WorkerPool(fork, WorkerHttp)
      ];

      let shutting_down = false;

      N.wire.on('shutdown', function* shutdown_workers() {
        shutting_down = true;

        yield pools.map(pool => new Promise(resolve => {
          function on_exit() {
            // check workers in every state except DEAD
            if (pool.get([ 'INIT', 'START', 'RUN', 'PEND', 'STOP' ]).length === 0) {
              pool.removeListener('exit', on_exit);
              resolve();
            }
          }

          pool.on('exit', on_exit);
          pool.terminate();
        }));
      });

      N.wire.on('reload', function reload_workers() {
        pools.forEach(pool => pool.reload());
      });

      yield pools.map(pool => new Promise((resolve, reject) => {
        let on_exit, on_running;

        on_running = function () {
          if (pool.get('RUN').length >= fork) {
            pool.removeListener('running', on_running);
            pool.removeListener('exit', on_exit);
            resolve();
          }
        };

        on_exit = function () {
          pool.removeListener('running', on_running);
          pool.removeListener('exit', on_exit);

          if (!shutting_down) {
            reject('Cannot start workers');
          } else {
            // don't throw if user pressed ctrl+c when workers start
            resolve();
          }
        };

        pool.on('running', on_running);
        pool.on('exit', on_exit);
      }));

      if (!shutting_down) {
        N.logger.info('All workers started successfully');
      }
      return;
    }

    // If we are here - need worker deals
    yield N.wire.emit('init:server.worker-http', N);
    yield N.wire.emit('init:server.worker-queue', N);
  });
};
<commit_msg>Should send signals via process.kill<commit_after>// Start server cluster
//
// In cluster mode it forks N http workers + N queue workers.
//
// In single mode it emits `init:server.worker-http` and
// `init:server.worker-queue` events instead
//
'use strict';

const _            = require('lodash');
const cluster      = require('cluster');
const co           = require('co');
const execFile     = require('mz/child_process').execFile;
const os           = require('os');
const inherits     = require('util').inherits;
const EventEmitter = require('events').EventEmitter;
const StateMachine = require('javascript-state-machine');

////////////////////////////////////////////////////////////////////////////////

function WorkerPool(size, worker) {
  if (!(this instanceof WorkerPool)) return new WorkerPool(size, worker);

  EventEmitter.call(this);

  this.__workers = [];
  this.__wClass  = worker;
  this.__size    = 0;

  this.update = _.debounce(() => {
    process.nextTick(() => {
      this.resize();
      this.gc();
    });
  }, 100, { maxWait: 200 });

  this.resize(size);
}

WorkerPool.prototype = {
  log() {
    /*eslint-disable no-console*/
    console.log.apply(null, arguments);
  },

  resize(count) {
    // Use current value if no params
    if (!count && count !== 0) {
      count = this.__size;
    }

    let alive = this.get([ 'INIT', 'START', 'RUN' ]),
        delta = count - alive.length,
        prev_size = this.__size;

    this.__size = count;

    if (delta === 0) return;

    if (delta > 0) {
      while (delta--) {
        let w = this.__wClass(this);
        this.__workers.push(w);
        // Force immediate start for the first run
        if (prev_size === 0 && w.can('start')) w.start();
      }
      return;
    }

    alive.slice(0, -delta).forEach(w => { w.shutdown(); });
  },

  terminate() {
    // prevent workers from being respawned
    this.__size = 0;

    this.__workers.forEach(w => { w.terminate(); });
  },

  reload() {
    this.__workers.forEach(w => {
      if (w.can('freeze')) w.freeze();
    });
  },

  get(state) {
    if (!Array.isArray(state)) {
      return this.__workers.filter(w => w.current === state);
    }
    return state.reduce((a, s) => a.concat(this.get(s)), []);
  },

  gc() {
    // Shutdown pending workers when not needed
    let excess = Math.max((this.get('PEND').length + this.get('RUN').length - this.__size), 0);

    this.get('PEND').slice(0, excess).forEach(w => { w.shutdown(); });

    // Drop dead workers
    this.__workers = this.__workers.filter(w => w.current !== 'DEAD');
  }
};

Object.setPrototypeOf(WorkerPool.prototype, EventEmitter.prototype);

////////////////////////////////////////////////////////////////////////////////

function Worker(pool) {
  if (!(this instanceof Worker)) return new Worker(pool);
  this.__pool          = pool;
  this.__w             = null;
  this.__start_timeout = 0;
  this.__exit_code     = null;

  this.begin();
}

Worker.prototype = {
  create() {
    throw new Error('This method should be overriden');
  },

  terminate() {
    // Don't use child's .kill() because it disconnects
    // child immediately and breaks logger in worker
    if (this.__w) process.kill(this.__w.process.pid, 'SIGKILL');
    else this.die();
  },

  onchangestate() {
    this.__pool.update();
  },

  onINIT() {
    setTimeout(() => {
      if (this.can('start')) this.start();
    }, 2000);
  },

  onSTART() {
    let w = this.__w = this.fork();
    let rcvd_startup_message = false;

    this.__pool.log.info(`Worker ${w.process.pid} spawned`);
    this.__pool.emit('spawn', w.process.pid);

    w.on('error', err => {
      this.__pool.log.error(err);
      this.die();
    });

    w.on('exit', (code, signal) => {
      this.__exit_code = signal || code;
      this.die();
    });

    w.on('message', msg => {
      if (msg === 'worker.running') {
        rcvd_startup_message = true;
        if (this.can('run')) this.run();
      }
    });

    setTimeout(() => {
      if (!rcvd_startup_message) this.terminate();
    }, 30000);
  },

  onSTOP() {
    // Don't use child's .kill() because it disconnects
    // child immediately and breaks logger in worker
    process.kill(this.__w.process.pid, 'SIGTERM');
    setTimeout(() => this.terminate(), 15000);
  },

  onRUN() {
    let w = this.__w;
    this.__pool.log.info(`Worker ${w.process.pid} is running`);
    this.__pool.emit('running', w.process.pid);
  },

  onDEAD() {
    let w = this.__w;

    // We can come here if process did not started.
    if (w) {
      this.__pool.log.info(`Worker ${w.process.pid} exited with status ${this.__exit_code}`);
      this.__pool.emit('exit', w.process.pid);
    }

    w.removeAllListeners();
    this.__w = null;
  }
};

StateMachine.create({
  events: [
    { name: 'begin',     from: 'none',   to: 'INIT'  },
    { name: 'start',     from: 'INIT',   to: 'START' },
    { name: 'run',       from: 'START',  to: 'RUN'   },

    { name: 'freeze',    from: 'RUN',    to: 'PEND'  },
    { name: 'freeze',    from: 'START',  to: 'DEAD'  },

    { name: 'shutdown',  from: 'RUN',    to: 'STOP'  },
    { name: 'shutdown',  from: 'PEND',   to: 'STOP'  },

    { name: 'die',       from: '*',      to: 'DEAD'  }
  ]
}, Worker.prototype);

////////////////////////////////////////////////////////////////////////////////

function WorkerQueue(pool) {
  if (!(this instanceof WorkerQueue)) return new WorkerQueue(pool);
  Worker.call(this, pool);
}

inherits(WorkerQueue, Worker);

WorkerQueue.prototype.fork = function () {
  cluster.setupMaster({ args: [ 'worker-queue' ] });

  let worker = cluster.fork(),
      log = this.__pool.log;

  worker.on('online', co.wrap(function* () {
    try {
      // Set scheduling policy to SCHED_IDLE (`-i` flag);
      // `0` is only possible value for priority ('cause this policy doesn't allow to set it)
      yield execFile('chrt', [ '-i', '-p', '0', worker.process.pid ]);
    } catch (__) {
      // If `chrt` not exists, try fallback to `renice`.
      try {
        yield execFile('renice', [ '-n', '19', '-p', worker.process.pid ]);
        log.warn('Cannot set scheduling policy for queue using `chrt`, falling back to `renice`');
      } catch (___) {
        log.error('Cannot lower priority for queue ' +
          '(both `renice` and `chrt` have failed), continuing with default priority');
      }
    }
  }));

  return worker;
};

////////////////////////////////////////////////////////////////////////////////

function WorkerHttp(pool) {
  if (!(this instanceof WorkerHttp)) return new WorkerHttp(pool);
  Worker.call(this, pool);
}

inherits(WorkerHttp, Worker);

WorkerHttp.prototype.fork = function () {
  cluster.setupMaster({ args: [ 'worker-http' ] });
  return cluster.fork();
};

////////////////////////////////////////////////////////////////////////////////

module.exports = function (N) {

  N.wire.on('init:server', function* cluster_init(N) {
    let fork = N.config.fork;

    if (fork === 'auto' || fork === true || _.isUndefined(fork)) {
      fork = os.cpus().length;
    } else {
      fork = +fork || 0;
    }

    if (cluster.isMaster && (fork >= 1)) {
      WorkerPool.prototype.log = N.logger;

      /*eslint-disable new-cap*/
      let pools = [
        WorkerPool(fork, WorkerQueue),
        WorkerPool(fork, WorkerHttp)
      ];

      let shutting_down = false;

      N.wire.on('shutdown', function* shutdown_workers() {
        shutting_down = true;

        yield pools.map(pool => new Promise(resolve => {
          function on_exit() {
            // check workers in every state except DEAD
            if (pool.get([ 'INIT', 'START', 'RUN', 'PEND', 'STOP' ]).length === 0) {
              pool.removeListener('exit', on_exit);
              resolve();
            }
          }

          pool.on('exit', on_exit);
          pool.terminate();
        }));
      });

      N.wire.on('reload', function reload_workers() {
        pools.forEach(pool => pool.reload());
      });

      yield pools.map(pool => new Promise((resolve, reject) => {
        let on_exit, on_running;

        on_running = function () {
          if (pool.get('RUN').length >= fork) {
            pool.removeListener('running', on_running);
            pool.removeListener('exit', on_exit);
            resolve();
          }
        };

        on_exit = function () {
          pool.removeListener('running', on_running);
          pool.removeListener('exit', on_exit);

          if (!shutting_down) {
            reject('Cannot start workers');
          } else {
            // don't throw if user pressed ctrl+c when workers start
            resolve();
          }
        };

        pool.on('running', on_running);
        pool.on('exit', on_exit);
      }));

      if (!shutting_down) {
        N.logger.info('All workers started successfully');
      }
      return;
    }

    // If we are here - need worker deals
    yield N.wire.emit('init:server.worker-http', N);
    yield N.wire.emit('init:server.worker-queue', N);
  });
};
<|endoftext|>


<commit_before>class MaxHeap {
	constructor() {
		this.heap = []
	}

	insert(key) {
		this.heap.push(key)
		this.swim(this.heap.length - 1)
	}

	delMax() {
		let max = this.heap[0]

		if(this.heap.length > 0) {
			this.swap(0, this.heap.length - 1)
		    this.heap.pop()
		    this.sink(0)

		    return max
		} else {
			console.log('Heap is empty')

			return false
		}
	}

	swim(k) {
        while(k > 0 && this.less(Math.floor(k/2), k)) {
        	this.swap(Math.floor(k/2), k)
        	k = Math.floor(k/2)
        }
	}

	sink(k) {
		let j

        while(2 * k <= this.size()) {
        	j = 2 * k
        	j = j === 0 ? 1 : j
        	if(this.less(j, j + 1)) { j++ }
        	if(!this.less(k, j)) { break }
        	this.swap(k, j)
            k = j
        }
	}

	less(i, j) {
        return this.heap[i] < this.heap[j]
	}

	swap(i, j) {
        let temp = this.heap[i]
        this.heap[i] = this.heap[j]
        this.heap[j] = temp
	}

	size() {
		return this.heap.length
	}

	isEmpty() {
		return this.size() === 0
	}

	toString() {
		console.log(this.heap)
	}
}

// 堆排序
function HeapSort(arr) {
    let heap = new MaxHeap()
    let len = arr.length
    let result = []

    for(let item of arr) {
    	heap.insert(item)
    }

    for(let i = 0; i < len; i++) {
    	result.push(heap.delMax())
    }

    return result.reverse()
}

HeapSort([2,4,3,5,1,8,3,9,15])<commit_msg>add: new item<commit_after>// 大根堆
class MaxHeap {
	constructor() {
		this.heap = []
	}

	insert(key) {
		this.heap.push(key)
		this.swim(this.heap.length - 1)
	}

	delMax() {
		let max = this.heap[0]

		if(this.heap.length > 0) {
			this.swap(0, this.heap.length - 1)
		    this.heap.pop()
		    this.sink(0)

		    return max
		} else {
			console.log('Heap is empty')

			return false
		}
	}

	swim(k) {
        while(k > 0 && this.less(Math.floor(k/2), k)) {
        	this.swap(Math.floor(k/2), k)
        	k = Math.floor(k/2)
        }
	}

	sink(k) {
		let j

        while(2 * k <= this.size()) {
        	j = 2 * k
        	j = j === 0 ? 1 : j
        	if(this.less(j, j + 1)) { j++ }
        	if(!this.less(k, j)) { break }
        	this.swap(k, j)
            k = j
        }
	}

	less(i, j) {
        return this.heap[i] < this.heap[j]
	}

	swap(i, j) {
        let temp = this.heap[i]
        this.heap[i] = this.heap[j]
        this.heap[j] = temp
	}

	size() {
		return this.heap.length
	}

	isEmpty() {
		return this.size() === 0
	}

	toString() {
		console.log(this.heap)
	}
}

// 堆排序
function HeapSort(arr) {
    let heap = new MaxHeap()
    let len = arr.length
    let result = []

    // 构造大根堆
    for(let item of arr) {
    	heap.insert(item)
    }

    // 依次将堆顶元素（最大元素）push进result
    for(let i = 0; i < len; i++) {
    	result.push(heap.delMax())
    }

    // 逆转数组，从小到大排序
    return result.reverse()
}

HeapSort([2])
HeapSort([2,1])
HeapSort([2,4,3,5,1,8,3,9,15])
<|endoftext|>


<commit_before>/**
 * Yii validation module.
 *
 * This JavaScript module provides the validation methods for the built-in validators.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */

yii.validation = (function ($) {
    var pub = {
        isEmpty: function (value) {
            return value === null || value === undefined || value == [] || value === '';
        },

        addMessage: function (messages, message, value) {
            messages.push(message.replace(/\{value\}/g, value));
        },

        required: function (value, messages, options) {
            var valid = false;
            if (options.requiredValue === undefined) {
                var isString = typeof value == 'string' || value instanceof String;
                if (options.strict && value !== undefined || !options.strict && !pub.isEmpty(isString ? $.trim(value) : value)) {
                    valid = true;
                }
            } else if (!options.strict && value == options.requiredValue || options.strict && value === options.requiredValue) {
                valid = true;
            }

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        },

        boolean: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }
            var valid = !options.strict && (value == options.trueValue || value == options.falseValue)
                || options.strict && (value === options.trueValue || value === options.falseValue);

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        },

        string: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (typeof value !== 'string') {
                pub.addMessage(messages, options.message, value);
                return;
            }

            if (options.min !== undefined && value.length < options.min) {
                pub.addMessage(messages, options.tooShort, value);
            }
            if (options.max !== undefined && value.length > options.max) {
                pub.addMessage(messages, options.tooLong, value);
            }
            if (options.is !== undefined && value.length != options.is) {
                pub.addMessage(messages, options.is, value);
            }
        },

        number: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (typeof value === 'string' && !value.match(options.pattern)) {
                pub.addMessage(messages, options.message, value);
                return;
            }

            if (options.min !== undefined && value < options.min) {
                pub.addMessage(messages, options.tooSmall, value);
            }
            if (options.max !== undefined && value > options.max) {
                pub.addMessage(messages, options.tooBig, value);
            }
        },

        range: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }
            var valid = !options.not && $.inArray(value, options.range) > -1
                || options.not && $.inArray(value, options.range) == -1;

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        },

        regularExpression: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (!options.not && !value.match(options.pattern) || options.not && value.match(options.pattern)) {
                pub.addMessage(messages, options.message, value);
            }
        },

        email: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            var valid = true;

            if (options.enableIDN) {
                var regexp = /^(.*<?)(.*)@(.*)(>?)$/,
                    matches = regexp.exec(value);
                if (matches === null) {
                    valid = false;
                } else {
                    value = matches[1] + punycode.toASCII(matches[2]) + '@' + punycode.toASCII(matches[3]) + matches[4];
                }
            }

            if (!valid || !(value.match(options.pattern) || (options.allowName && value.match(options.fullPattern)))) {
                pub.addMessage(messages, options.message, value);
            }
        },

        url: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (options.defaultScheme && !value.match(/:\/\//)) {
                value = options.defaultScheme + '://' + value;
            }

            var valid = true;

            if (options.enableIDN) {
                var regexp = /^([^:]+):\/\/([^\/]+)(.*)$/,
                    matches = regexp.exec(value);
                if (matches === null) {
                    valid = false;
                } else {
                    value = matches[1] + '://' + punycode.toASCII(matches[2]) + matches[3];
                }
            }

            if (!valid || !value.match(options.pattern)) {
                pub.addMessage(messages, options.message, value);
            }
        },

        captcha: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            // CAPTCHA may be updated via AJAX and the updated hash is stored in body data
            var hash = $('body').data(options.hashKey);
            if (hash == null) {
                hash = options.hash;
            } else {
                hash = hash[options.caseSensitive ? 0 : 1];
            }
            var v = options.caseSensitive ? value : value.toLowerCase();
            for (var i = v.length - 1, h = 0; i >= 0; --i) {
                h += v.charCodeAt(i);
            }
            if (h != hash) {
                pub.addMessage(messages, options.message, value);
            }
        },

        compare: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            var compareValue, valid = true;
            if (options.compareAttribute === undefined) {
                compareValue = options.compareValue;
            } else {
                compareValue = $('#' + options.compareAttribute).val();
            }
            switch (options.operator) {
                case '==':
                    valid = value == compareValue;
                    break;
                case '===':
                    valid = value === compareValue;
                    break;
                case '!=':
                    valid = value != compareValue;
                    break;
                case '!==':
                    valid = value !== compareValue;
                    break;
                case '>':
                    valid = value > compareValue;
                    break;
                case '>=':
                    valid = value >= compareValue;
                    break;
                case '<':
                    valid = value < compareValue;
                    break;
                case '<=':
                    valid = value <= compareValue;
                    break;
                default:
                    valid = false;
                    break;
            }

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        }
    };
    return pub;
})(jQuery);
<commit_msg>Update yii.validation.js<commit_after>/**
 * Yii validation module.
 *
 * This JavaScript module provides the validation methods for the built-in validators.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */

yii.validation = (function ($) {
    var pub = {
        isEmpty: function (value) {
            return value === null || value === undefined || value == [] || value === '';
        },

        addMessage: function (messages, message, value) {
            messages.push(message.replace(/\{value\}/g, value));
        },

        required: function (value, messages, options) {
            var valid = false;
            if (options.requiredValue === undefined) {
                var isString = typeof value == 'string' || value instanceof String;
                if (options.strict && value !== undefined || !options.strict && !pub.isEmpty(isString ? $.trim(value) : value)) {
                    valid = true;
                }
            } else if (!options.strict && value == options.requiredValue || options.strict && value === options.requiredValue) {
                valid = true;
            }

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        },

        boolean: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }
            var valid = !options.strict && (value == options.trueValue || value == options.falseValue)
                || options.strict && (value === options.trueValue || value === options.falseValue);

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        },

        string: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (typeof value !== 'string') {
                pub.addMessage(messages, options.message, value);
                return;
            }

            if (options.min !== undefined && value.length < options.min) {
                pub.addMessage(messages, options.tooShort, value);
            }
            if (options.max !== undefined && value.length > options.max) {
                pub.addMessage(messages, options.tooLong, value);
            }
            if (options.is !== undefined && value.length != options.is) {
                pub.addMessage(messages, options.notEqual, value);
            }
        },

        number: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (typeof value === 'string' && !value.match(options.pattern)) {
                pub.addMessage(messages, options.message, value);
                return;
            }

            if (options.min !== undefined && value < options.min) {
                pub.addMessage(messages, options.tooSmall, value);
            }
            if (options.max !== undefined && value > options.max) {
                pub.addMessage(messages, options.tooBig, value);
            }
        },

        range: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }
            var valid = !options.not && $.inArray(value, options.range) > -1
                || options.not && $.inArray(value, options.range) == -1;

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        },

        regularExpression: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (!options.not && !value.match(options.pattern) || options.not && value.match(options.pattern)) {
                pub.addMessage(messages, options.message, value);
            }
        },

        email: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            var valid = true;

            if (options.enableIDN) {
                var regexp = /^(.*<?)(.*)@(.*)(>?)$/,
                    matches = regexp.exec(value);
                if (matches === null) {
                    valid = false;
                } else {
                    value = matches[1] + punycode.toASCII(matches[2]) + '@' + punycode.toASCII(matches[3]) + matches[4];
                }
            }

            if (!valid || !(value.match(options.pattern) || (options.allowName && value.match(options.fullPattern)))) {
                pub.addMessage(messages, options.message, value);
            }
        },

        url: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            if (options.defaultScheme && !value.match(/:\/\//)) {
                value = options.defaultScheme + '://' + value;
            }

            var valid = true;

            if (options.enableIDN) {
                var regexp = /^([^:]+):\/\/([^\/]+)(.*)$/,
                    matches = regexp.exec(value);
                if (matches === null) {
                    valid = false;
                } else {
                    value = matches[1] + '://' + punycode.toASCII(matches[2]) + matches[3];
                }
            }

            if (!valid || !value.match(options.pattern)) {
                pub.addMessage(messages, options.message, value);
            }
        },

        captcha: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            // CAPTCHA may be updated via AJAX and the updated hash is stored in body data
            var hash = $('body').data(options.hashKey);
            if (hash == null) {
                hash = options.hash;
            } else {
                hash = hash[options.caseSensitive ? 0 : 1];
            }
            var v = options.caseSensitive ? value : value.toLowerCase();
            for (var i = v.length - 1, h = 0; i >= 0; --i) {
                h += v.charCodeAt(i);
            }
            if (h != hash) {
                pub.addMessage(messages, options.message, value);
            }
        },

        compare: function (value, messages, options) {
            if (options.skipOnEmpty && pub.isEmpty(value)) {
                return;
            }

            var compareValue, valid = true;
            if (options.compareAttribute === undefined) {
                compareValue = options.compareValue;
            } else {
                compareValue = $('#' + options.compareAttribute).val();
            }
            switch (options.operator) {
                case '==':
                    valid = value == compareValue;
                    break;
                case '===':
                    valid = value === compareValue;
                    break;
                case '!=':
                    valid = value != compareValue;
                    break;
                case '!==':
                    valid = value !== compareValue;
                    break;
                case '>':
                    valid = value > compareValue;
                    break;
                case '>=':
                    valid = value >= compareValue;
                    break;
                case '<':
                    valid = value < compareValue;
                    break;
                case '<=':
                    valid = value <= compareValue;
                    break;
                default:
                    valid = false;
                    break;
            }

            if (!valid) {
                pub.addMessage(messages, options.message, value);
            }
        }
    };
    return pub;
})(jQuery);
<|endoftext|>


<commit_before>import {Graphics, Point} from 'pixi.js';
import {toCanvasCoordinates} from './CoordinatesMapper';
import {LEFT, RIGHT, UP, DOWN} from './Direction';

/**
 * Draws the direction an Entity wants to go.
 */
export class DirectionGraphics extends Graphics {
	constructor(rotation, x, y) {
		super();

		const triangleScale = .5;

		this.rotation = rotation;
		const [cellWidth, cellHeight] = toCanvasCoordinates(1, 1);
		//this.scale = new Point(triangleScale * cellWidth, triangleScale * cellHeight);
		this.alpha = .5;
		this.x = (x + .5) * cellWidth;
		this.y = (y + .5) * cellHeight;

		// drawing the graphics
		this.beginFill(0x6BF76B);
		this.drawPolygon([0, -1/2, 1/6, 1/2, -1/6, 1/2]);
		this.endFill();

		this.width = cellWidth;
		this.height = cellHeight;
	}
}

/**
 * Returns the DirectionGraphics belonging to the given Direction
 */
export function directionGraphics(direction) {
	switch(direction) {
		case UP: return new DirectionGraphics(0, 0, -1);
		case RIGHT: return new DirectionGraphics(.5 * Math.PI, 1, 0);
		case DOWN: return new DirectionGraphics(Math.PI, 0, 1);
		case LEFT: return new DirectionGraphics(1.5 * Math.PI, -1, 0);
	}
}
<commit_msg>Update look and view of direction triangle<commit_after>import {Graphics, Point} from 'pixi.js';
import {toCanvasCoordinates} from './CoordinatesMapper';
import {LEFT, RIGHT, UP, DOWN} from './Direction';

/**
 * Draws the direction an Entity wants to go.
 */
export class DirectionGraphics extends Graphics {
	constructor(rotation, x, y) {
		super();

		const triangleScale = .5;

		this.rotation = rotation;
		const [cellWidth, cellHeight] = toCanvasCoordinates(1, 1);
		this.scale = new Point(triangleScale * cellWidth, triangleScale * cellHeight);
		this.alpha = .7;
		this.x = (x + .5) * cellWidth;
		this.y = (y + .5) * cellHeight;

		// drawing the graphics
		this.beginFill(0x6BF76B);
		this.drawPolygon([0, -1/2, 1/2, 1/2, -1/2, 1/2]);
		this.endFill();
	}
}

/**
 * Returns the DirectionGraphics belonging to the given Direction
 */
export function directionGraphics(direction) {
	switch(direction) {
		case UP: return new DirectionGraphics(0, 0, -1);
		case RIGHT: return new DirectionGraphics(.5 * Math.PI, 1, 0);
		case DOWN: return new DirectionGraphics(Math.PI, 0, 1);
		case LEFT: return new DirectionGraphics(1.5 * Math.PI, -1, 0);
	}
}
<|endoftext|>