<commit_before>import instance from './instance';
<% if(data.response_model.error){ %>
export default(opts) => {
    return instance({
        method: '<%- data.method %>',
        url: '<%- data.url %>',
        opts: opts
    });
}
<% }else{ %>
<% _.mapKeys(data.response_model, function(value, key){ %>
<% if(value.type === 'array'){ %>
class <%- value.modelType %>Array {
    constructor(data) {
        return data.map(value => new <%- value.modelType %>(value));
    }
}
<% } %>
  <% if(key !== 'data'){ %>
class <%- key %> {
    <% _.mapKeys(value, function(cellValue, cellKey){ %>
      <% if(cellKey !== '_id_'){ %>
          <% if(cellValue.description){ %>
           // <%- cellValue.description %>
           // type @<%- cellValue.type %>
          <% } %>
          <%- cellKey %>;
       <% } %>
    <% }) %>
    constructor(data) {
        <% _.mapKeys(value, function(cellValue, cellKey){ %>
          <% if(cellKey !== '_id_'){ %>
            this.<%- $$.getMethodName(cellKey) %>(data.<%- cellKey %>);
          <% } %>
        <% }) %>
    }

    <% _.mapKeys(value, function(cellValue, cellKey){ %>
          <% if(cellKey !== '_id_'){ %>
              <%- $$.getMethodName(cellKey) %>() (value) {
                if(typeof value !== 'string') {
                    console.log('error');
                }
                this.<%- cellKey %> = value;
             }
          <% } %>
    <% }) %>
}
  <% } %>
<% }) %>
export default(opts) => {
    return instance({
        method: '<%- data.method %>',
        url: '<%- data.url %>',
        opts: opts
    }).then(data => {
        return new
        <% _.mapKeys(data.response_model, function(value, key){ %>
            <% if(key === 'data') %>
                <% if(value.type === 'array'){ %>
                    return new <%- value.modelType %>Array(data);
                <% }else{ %>
                    return new <%- value.modelType %>(data);
                <% } %>
            <% } %>
        <% }) %>
    });
}
<% } %><commit_msg>feat: change model<commit_after>import instance from './instance';
<% if(data.response_model.error){ %>
export default(opts) => {
    return instance({
        method: '<%- data.method %>',
        url: '<%- data.url %>',
        opts: opts
    });
}
<% }else{ %>
<% _.mapKeys(data.response_model, function(value, key){ %>
<% if(value.type === 'array'){ %>
class <%- value.modelType %>Array {
    constructor(data) {
        return data.map(value => new <%- value.modelType %>(value));
    }
}
<% } %>
  <% if(key !== 'data'){ %>
class <%- key %> {
    <% _.mapKeys(value, function(cellValue, cellKey){ %>
      <% if(cellKey !== '_id_'){ %>
          <% if(cellValue.description){ %>
           // <%- cellValue.description %>
           // type @<%- cellValue.type %>
          <% } %>
          <%- cellKey %>;
       <% } %>
    <% }) %>
    constructor(data) {
        <% _.mapKeys(value, function(cellValue, cellKey){ %>
          <% if(cellKey !== '_id_'){ %>
            this.<%- $$.getMethodName(cellKey) %>(data.<%- cellKey %>);
          <% } %>
        <% }) %>
    }

    <% _.mapKeys(value, function(cellValue, cellKey){ %>
          <% if(cellKey !== '_id_'){ %>
              <%- $$.getMethodName(cellKey) %>() (value) {
                if(typeof value !== 'string') {
                    console.log('error');
                }
                this.<%- cellKey %> = value;
             }
          <% } %>
    <% }) %>
}
  <% } %>
<% }) %>
export default(opts) => {
    return instance({
        method: '<%- data.method %>',
        url: '<%- data.url %>',
        opts: opts
    }).then(data => {
        return new
        <% _.mapKeys(data.response_model, function(value, key){ %>
            <% if(key === 'data'){ %>
                <% if(value.type === 'array'){ %>
                    return new <%- value.modelType %>Array(data);
                <% }else{ %>
                    return new <%- value.modelType %>(data);
                <% } %>
            <% } %>
        <% }) %>
    });
}
<% } %><|endoftext|>


<commit_before>module.exports = function (grunt) {
	'use strict';
	// Project configuration
	grunt.initConfig({
		pkg:    grunt.file.readJSON('package.json'),<% if ( remoteDatabase ) { %>
		http: {
			remoteDatabases: {
				options: {
					url: '<%= remoteDatabase.url %>'
				},
				dest: 'config/data/<%= remoteDatabase.url.match(/([^\/]*)$/)[0] %>'
			}
		},<% } %>
		gitPull: {
			dependencies: {
				repos: [
					{
						path: [],
						dir: 'deps',
						repo: '<%= dependencies %>'
					}
				]
			}<% if ( repos ) { %>,
<% }
			if ( repos ) {
%>			themes: {
				repos: [
<%					var i, length;
					for (i = 0, length = repos.theme.length; i < length; i++) {
%>					{
						path: ['src', 'themes'],
						repo: '<%= repos.theme[i] %>'
					}<% if((i + 1) !== length) { %>,<% } %>
<% } %>				]
			},
			plugins: {
				repos: [
<%					for (i = 0, length = repos.plugin.length; i < length; i++) {
%>					{
						path: ['src', 'plugins'],
						repo: '<%= repos.plugin[i] %>'
					}<% if((i + 1) !== length) { %>,<% } %>
<% } %>				]
			}<% } %>
		},
		vagrant_commands: {
			restart: {
				commands: [
					['up'],
					['provision']
				]
			},<% if ( 'trunk' === wordpress.version ) { %>
			svn_up: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %>/htdocs && svn up']
				]
			},
<% } %>			import_db: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/import-sql.sh']
				]
			},
			install_plugins: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/plugins.sh']
				]
			},
			install_themes: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/themes.sh']
				]
			},
			symlinks: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/clear-links.sh'],
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/dependencies.sh'],
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/src.sh']
				]
			},
			proxy_on: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/proxy_on.sh']
				]
			},
			proxy_off: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/proxy_off.sh']
				]
			},
			cleanup: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/cleanup.sh']
				]
			}
		}
	});

	// Load tasks
	require('load-grunt-tasks')(grunt);

	// Register tasks
	grunt.registerTask('default', [<% if ( remoteDatabase ) { %>'http', <% } %>'gitPull', 'vagrant_commands:restart']);<% if ( 'trunk' === wordpress.version ) { %>
	grunt.registerTask('trunk', ['vagrant_commands:svn_up']);<% } %>
	grunt.registerTask('provision', ['vagrant_commands:restart']);
	grunt.registerTask('db', ['vagrant_commands:import_db']);<% if ( remoteDatabase ) { %>
	grunt.registerTask('remoteDB', ['http:remoteDatabases', 'vagrant_commands:import_db']);<% } %>
	grunt.registerTask('plugins', ['vagrant_commands:install_plugins']);
	grunt.registerTask('themes', ['vagrant_commands:install_themes']);
	grunt.registerTask('relink', ['gitPull:dependencies', 'vagrant_commands:symlinks']);
	grunt.registerTask('proxy_on', ['vagrant_commands:proxy_on']);
	grunt.registerTask('proxy_off', ['vagrant_commands:proxy_off']);
	grunt.registerTask('cleanup', ['vagrant_commands:cleanup']);

	grunt.util.linefeed = '\n';
};
<commit_msg>Accept a different folder name for plugin and theme repos than their repo name<commit_after>module.exports = function (grunt) {
	'use strict';
	// Project configuration
	grunt.initConfig({
		pkg:    grunt.file.readJSON('package.json'),<% if ( remoteDatabase ) { %>
		http: {
			remoteDatabases: {
				options: {
					url: '<%= remoteDatabase.url %>'
				},
				dest: 'config/data/<%= remoteDatabase.url.match(/([^\/]*)$/)[0] %>'
			}
		},<% } %>
		gitPull: {
			dependencies: {
				repos: [
					{
						path: [],
						dir: 'deps',
						repo: '<%= dependencies %>'
					}
				]
			}<% if ( repos ) { %>,
<% }
			if ( repos ) {
%>			themes: {
				repos: [
<%					var i, length;
					for (i = 0, length = repos.theme.length; i < length; i++) {
						if ( 'object' === typeof repos.theme[i] ) {
%>					{
						path: ['src', 'themes'],
						dir: '<%= repos.theme[i].dir %>',
						repo: '<%= repos.theme[i].repo %>'
					}<% if((i + 1) !== length) { %>,<% } %>
<%						} else {
%>					{
						path: ['src', 'themes'],
						repo: '<%= repos.theme[i] %>'
					}<% if((i + 1) !== length) { %>,<% } %>
<% } }
%>				]
			},
			plugins: {
				repos: [
<%					for (i = 0, length = repos.plugin.length; i < length; i++) {
						if ( 'object' === typeof repos.plugin[i] ) {
%>					{
						path: ['src', 'plugins'],
						dir: '<%= repos.plugin[i].dir %>',
						repo: '<%= repos.plugin[i].repo %>'
					}<% if((i + 1) !== length) { %>,<% } %>
<% } else {
%>					{
						path: ['src', 'plugins'],
						repo: '<%= repos.plugin[i] %>'
					}<% if((i + 1) !== length) { %>,<% } %>
<% } }
%>				]
			}<% } %>
		},
		vagrant_commands: {
			restart: {
				commands: [
					['up'],
					['provision']
				]
			},<% if ( 'trunk' === wordpress.version ) { %>
			svn_up: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %>/htdocs && svn up']
				]
			},
<% } %>			import_db: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/import-sql.sh']
				]
			},
			install_plugins: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/plugins.sh']
				]
			},
			install_themes: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/themes.sh']
				]
			},
			symlinks: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/clear-links.sh'],
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/dependencies.sh'],
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/src.sh']
				]
			},
			proxy_on: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/proxy_on.sh']
				]
			},
			proxy_off: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/proxy_off.sh']
				]
			},
			cleanup: {
				commands: [
					['ssh', '--command=cd /var/sites/<%= site.id %> && bash scripts/cleanup.sh']
				]
			}
		}
	});

	// Load tasks
	require('load-grunt-tasks')(grunt);

	// Register tasks
	grunt.registerTask('default', [<% if ( remoteDatabase ) { %>'http', <% } %>'gitPull', 'vagrant_commands:restart']);<% if ( 'trunk' === wordpress.version ) { %>
	grunt.registerTask('trunk', ['vagrant_commands:svn_up']);<% } %>
	grunt.registerTask('provision', ['vagrant_commands:restart']);
	grunt.registerTask('db', ['vagrant_commands:import_db']);<% if ( remoteDatabase ) { %>
	grunt.registerTask('remoteDB', ['http:remoteDatabases', 'vagrant_commands:import_db']);<% } %>
	grunt.registerTask('plugins', ['vagrant_commands:install_plugins']);
	grunt.registerTask('themes', ['vagrant_commands:install_themes']);
	grunt.registerTask('relink', ['gitPull:dependencies', 'vagrant_commands:symlinks']);
	grunt.registerTask('proxy_on', ['vagrant_commands:proxy_on']);
	grunt.registerTask('proxy_off', ['vagrant_commands:proxy_off']);
	grunt.registerTask('cleanup', ['vagrant_commands:cleanup']);

	grunt.util.linefeed = '\n';
};
<|endoftext|>


<commit_before>import Morph from "./Morph.js"

import { Graph } from 'src/client/triples/triples.js';
import lively from 'src/client/lively.js';

export default class AddTriple extends Morph {
  async initialize() {
    this.windowTitle = "Add Triple";

    let input = this.get("#inputSubject");
    this.selectors.forEach(({ input }) => this.get(input).addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        this.save();
      }
    }));

    let button = this.get('#save');
    button.addEventListener('click', event => this.save());

    this.selectors.forEach(({ list }) => this.prepareDatalist(list));
  }

  /** subject, predicate, object */
  get spo() { return this.selectors; }

  get selectors() {
    return [{
      input: '#inputSubject',
      list: '#subject',
      debugLabel: 'subject'
    }, {
      input: '#inputPredicate',
      list: '#predicate',
      debugLabel: 'predicate'
    }, {
      input: '#inputObject',
      list: '#object',
      debugLabel: 'object'
    }]
  }

  async prepareDatalist(listSelector) {
    let graph = Graph.getInstance();
    await graph.loadFromDir('https://lively4/dropbox/');

    let selection = this.get(listSelector);
    graph.getKnots().forEach(knot => {
      let option = document.createElement('option');

      option.innerHTML = knot.label();
      option.value = knot.url;
      option.dataset.url = knot.url;

      selection.appendChild(option);
    });
  }

  // https://derickbailey.com/2016/03/23/get-a-data-attribute-value-from-the-selected-datalist-option/
  getURLFor(inputSelector, listSelector) {
    let input = this.get(inputSelector);
    let list = this.get(listSelector);

    var value = input.value;
    lively.notify('input value: ' + value);
    // TODO: check for empty value ('')
    // TODO: value could be a literal or a url
    var option = this.get(`${listSelector} [value='${value}']`);
    // value could also be an external url
    if(!option) return;
    lively.notify(option.innerHTML)
    let url = option.dataset.url;
    lively.notify('url: ' + url);
    return url;
  }

  async save() {
    let graph = Graph.getInstance();

    this.spo.forEach(({ input, debugLabel }) => {
      if(this.get(input).value === '') {
        lively.notify(`${debugLabel} not specified!`, null, 2000, null, 'red');
        throw new RangeError(`No ${debugLabel} specified in Add Triple.`);
      }
    })
    const subjectURL = this.getURLFor('#inputSubject', '#subject');
    const predicateURL = this.getURLFor('#inputPredicate', '#predicate');
    const objectURL = this.getURLFor('#inputObject', '#object');

    graph.createTriple(
      subjectURL,
      predicateURL,
      objectURL
    );
  }
}
<commit_msg>AUTO-COMMIT templates/add-triple.js<commit_after>import Morph from "./Morph.js"

import { Graph } from 'src/client/triples/triples.js';
import lively from 'src/client/lively.js';

export default class AddTriple extends Morph {
  async initialize() {
    this.windowTitle = "Add Triple";

    let input = this.get("#inputSubject");
    this.selectors.forEach(({ input }) => this.get(input).addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        this.save();
      }
    }));

    let button = this.get('#save');
    button.addEventListener('click', event => this.save());

    this.selectors.forEach(({ list }) => this.prepareDatalist(list));
  }

  /** subject, predicate, object */
  get spo() { return this.selectors; }

  get selectors() {
    return [{
      input: '#inputSubject',
      list: '#subject',
      debugLabel: 'subject'
    }, {
      input: '#inputPredicate',
      list: '#predicate',
      debugLabel: 'predicate'
    }, {
      input: '#inputObject',
      list: '#object',
      debugLabel: 'object'
    }]
  }

  async prepareDatalist(listSelector) {
    let graph = Graph.getInstance();
    await graph.loadFromDir('https://lively4/dropbox/');

    let selection = this.get(listSelector);
    graph.getKnots().forEach(knot => {
      let option = document.createElement('option');

      option.innerHTML = knot.label();
      option.value = knot.url;
      option.dataset.url = knot.url;

      selection.appendChild(option);
    });
  }

  // https://derickbailey.com/2016/03/23/get-a-data-attribute-value-from-the-selected-datalist-option/
  getURLFor(inputSelector, listSelector) {
    let input = this.get(inputSelector);
    let list = this.get(listSelector);

    var value = input.value;
    lively.notify('input value: ' + value);
    // TODO: check for empty value ('')
    // TODO: value could be a literal or a url
    var option = this.get(`${listSelector} [value='${value}']`);
    // value could also be an external url
    if(!option) return;
    lively.notify(option.innerHTML)
    let url = option.dataset.url;
    lively.notify('url: ' + url);
    return url;
  }

  async save() {
    let graph = Graph.getInstance();

    this.spo.forEach(({ input, debugLabel }) => {
      if(this.get(input).value === '') {
        lively.notify(`${debugLabel} not specified!`, null, 2, null, 'red');
        throw new RangeError(`No ${debugLabel} specified in Add Triple.`);
      }
    })
    const subjectURL = this.getURLFor('#inputSubject', '#subject');
    const predicateURL = this.getURLFor('#inputPredicate', '#predicate');
    const objectURL = this.getURLFor('#inputObject', '#object');

    graph.createTriple(
      subjectURL,
      predicateURL,
      objectURL
    );
  }
}
<|endoftext|>


<commit_before>import {pickBy, isEmpty, isNil} from 'ramda';
import {formatPrefix} from 'd3-format';

/**
 * Truncate marks if they are out of Slider interval
 */
const truncateMarks = (min, max, marks) =>
    pickBy((k, mark) => mark >= min && mark <= max, marks);

const truncateNumber = num =>
    parseInt(num.toString().match(/^-?\d+(?:\.\d{0,0})?/)[0], 10);

const decimalCount = d =>
    String(d).split('.').length > 1 ? String(d).split('.')[1].length : 0;
const alignIntValue = (v, d) =>
    d < 10
        ? v
        : parseInt((truncateNumber(v / d) * d).toFixed(decimalCount(d)), 10);
const alignDecimalValue = (v, d) =>
    d < 10
        ? parseFloat(v.toFixed(decimalCount(d)))
        : parseFloat(((v / d).toFixed(0) * d).toFixed(decimalCount(d)));

const alignValue = (v, d) =>
    decimalCount(d) < 1 ? alignIntValue(v, d) : alignDecimalValue(v, d);

const log = v => Math.floor(Math.log10(v));

const getNearByStep = v =>
    v < 10
        ? [v]
        : [
              Math.pow(10, Math.floor(Math.log10(v))),
              Math.pow(10, Math.ceil(Math.log10(v))) / 2,
              alignValue(v, Math.pow(10, log(v))),
              Math.pow(10, Math.ceil(Math.log10(v))),
          ].sort((a, b) => Math.abs(a - v) - Math.abs(b - v));

const estimateBestSteps = (minValue, maxValue, stepValue) => {
    const desiredCountMin = 2 + (maxValue / stepValue <= 10 ? 3 : 3); // including start, end
    const desiredCountMax = 2 + (maxValue / stepValue <= 10 ? 4 : 6);

    const min = minValue / stepValue;
    const max = maxValue / stepValue;

    const rangeLength = max - min;

    const leastMarksInterval = Math.max(
        Math.round(rangeLength / (desiredCountMin - 1)),
        1
    );
    const possibleValues = getNearByStep(leastMarksInterval);

    const finalStep =
        possibleValues.find(step => {
            const expectedSteps = Math.ceil(rangeLength / step) + 1;
            return (
                expectedSteps >= desiredCountMin - 1 &&
                expectedSteps <= desiredCountMax + 1
            );
        }) || possibleValues[0];
    return [
        alignValue(min, finalStep) * stepValue,
        alignValue(finalStep * stepValue, stepValue),
        stepValue,
    ];
};

/**
 * Calculate default step if not defined
 */
export const calcStep = (min, max, step) => {
    if (step) {
        return step;
    }

    const diff = max > min ? max - min : min - max;

    const v = (Math.abs(diff) + Number.EPSILON) / 100;
    const N = Math.floor(Math.log10(v));
    return [
        Number(Math.pow(10, N)),
        2 * Math.pow(10, N),
        5 * Math.pow(10, N),
    ].sort((a, b) => Math.abs(a - v) - Math.abs(b - v))[0];
};

/**
 * Set min and max if they are undefined and marks are defined
 */
export const setUndefined = (min, max, marks) => {
    const definedMarks = {min_mark: min, max_mark: max};
    const marksObject = Object.keys(marks).map(Number);

    if (isNil(min)) {
        definedMarks.min_mark = Math.min(...marksObject);
    }

    if (isNil(max)) {
        definedMarks.max_mark = Math.max(...marksObject);
    }

    return definedMarks;
};

export const applyD3Format = (mark, min, max) => {
    const mu_ten_factor = -3;
    const k_ten_factor = 3;

    const ten_factor = Math.log10(Math.abs(mark));
    if (
        mark === 0 ||
        (ten_factor > mu_ten_factor && ten_factor < k_ten_factor)
    ) {
        return String(mark);
    }
    const max_min_mean = (Math.abs(max) + Math.abs(min)) / 2;
    const si_formatter = formatPrefix(',.0', max_min_mean);
    return String(si_formatter(mark));
};

export const autoGenerateMarks = (min, max, step) => {
    const marks = [];
    const [start, interval, chosenStep] = step
        ? [min, step, step]
        : estimateBestSteps(min, max, calcStep(min, max, step));
    let cursor = start + interval;

    // make sure we don't step into infinite loop
    if ((max - cursor) / interval > 0) {
        do {
            marks.push(alignValue(cursor, chosenStep));
            cursor += interval;
        } while (cursor < max);

        // do some cosmetic
        const discardThreshold = 1.5;
        if (
            marks.length >= 2 &&
            max - marks[marks.length - 2] <= interval * discardThreshold
        ) {
            marks.pop();
        }
    }
    const marksObject = {};
    marks.forEach(mark => {
        marksObject[mark] = applyD3Format(mark, min, max);
    });
    marksObject[min] = applyD3Format(min, min, max);
    marksObject[max] = applyD3Format(max, min, max);
    return marksObject;
};

/**
 * - Auto generate marks if not given,
 * - Not generate anything at all when explicit null is given to marks
 * - Then truncate marks so no out of range marks
 */
export const sanitizeMarks = ({min, max, marks, step}) => {
    if (isNil(marks)) {
        return undefined;
    }

    const [min_mark, max_mark] = Object.values(setUndefined(min, max, marks));

    const truncated_marks =
        marks && isEmpty(marks) === false
            ? truncateMarks(min_mark, max_mark, marks)
            : marks;

    if (truncated_marks && isEmpty(truncated_marks) === false) {
        return truncated_marks;
    }
    return autoGenerateMarks(min_mark, max_mark, step);
};

/**
 * Calculate default value if not defined
 */
export const calcValue = (min, max, value) => {
    if (value !== undefined) {
        return value;
    }

    return [min, max];
};
<commit_msg>Fixing undefined marks check<commit_after>import {pickBy, isEmpty, isNil} from 'ramda';
import {formatPrefix} from 'd3-format';

/**
 * Truncate marks if they are out of Slider interval
 */
const truncateMarks = (min, max, marks) =>
    pickBy((k, mark) => mark >= min && mark <= max, marks);

const truncateNumber = num =>
    parseInt(num.toString().match(/^-?\d+(?:\.\d{0,0})?/)[0], 10);

const decimalCount = d =>
    String(d).split('.').length > 1 ? String(d).split('.')[1].length : 0;
const alignIntValue = (v, d) =>
    d < 10
        ? v
        : parseInt((truncateNumber(v / d) * d).toFixed(decimalCount(d)), 10);
const alignDecimalValue = (v, d) =>
    d < 10
        ? parseFloat(v.toFixed(decimalCount(d)))
        : parseFloat(((v / d).toFixed(0) * d).toFixed(decimalCount(d)));

const alignValue = (v, d) =>
    decimalCount(d) < 1 ? alignIntValue(v, d) : alignDecimalValue(v, d);

const log = v => Math.floor(Math.log10(v));

const getNearByStep = v =>
    v < 10
        ? [v]
        : [
              Math.pow(10, Math.floor(Math.log10(v))),
              Math.pow(10, Math.ceil(Math.log10(v))) / 2,
              alignValue(v, Math.pow(10, log(v))),
              Math.pow(10, Math.ceil(Math.log10(v))),
          ].sort((a, b) => Math.abs(a - v) - Math.abs(b - v));

const estimateBestSteps = (minValue, maxValue, stepValue) => {
    const desiredCountMin = 2 + (maxValue / stepValue <= 10 ? 3 : 3); // including start, end
    const desiredCountMax = 2 + (maxValue / stepValue <= 10 ? 4 : 6);

    const min = minValue / stepValue;
    const max = maxValue / stepValue;

    const rangeLength = max - min;

    const leastMarksInterval = Math.max(
        Math.round(rangeLength / (desiredCountMin - 1)),
        1
    );
    const possibleValues = getNearByStep(leastMarksInterval);

    const finalStep =
        possibleValues.find(step => {
            const expectedSteps = Math.ceil(rangeLength / step) + 1;
            return (
                expectedSteps >= desiredCountMin - 1 &&
                expectedSteps <= desiredCountMax + 1
            );
        }) || possibleValues[0];
    return [
        alignValue(min, finalStep) * stepValue,
        alignValue(finalStep * stepValue, stepValue),
        stepValue,
    ];
};

/**
 * Calculate default step if not defined
 */
export const calcStep = (min, max, step) => {
    if (step) {
        return step;
    }

    const diff = max > min ? max - min : min - max;

    const v = (Math.abs(diff) + Number.EPSILON) / 100;
    const N = Math.floor(Math.log10(v));
    return [
        Number(Math.pow(10, N)),
        2 * Math.pow(10, N),
        5 * Math.pow(10, N),
    ].sort((a, b) => Math.abs(a - v) - Math.abs(b - v))[0];
};

/**
 * Set min and max if they are undefined and marks are defined
 */
export const setUndefined = (min, max, marks) => {
    const definedMarks = {min_mark: min, max_mark: max};

    if (isNil(marks)) {
        return definedMarks;
    }

    const marksObject = Object.keys(marks).map(Number);

    if (isNil(min)) {
        definedMarks.min_mark = Math.min(...marksObject);
    }

    if (isNil(max)) {
        definedMarks.max_mark = Math.max(...marksObject);
    }

    return definedMarks;
};

export const applyD3Format = (mark, min, max) => {
    const mu_ten_factor = -3;
    const k_ten_factor = 3;

    const ten_factor = Math.log10(Math.abs(mark));
    if (
        mark === 0 ||
        (ten_factor > mu_ten_factor && ten_factor < k_ten_factor)
    ) {
        return String(mark);
    }
    const max_min_mean = (Math.abs(max) + Math.abs(min)) / 2;
    const si_formatter = formatPrefix(',.0', max_min_mean);
    return String(si_formatter(mark));
};

export const autoGenerateMarks = (min, max, step) => {
    const marks = [];
    const [start, interval, chosenStep] = step
        ? [min, step, step]
        : estimateBestSteps(min, max, calcStep(min, max, step));
    let cursor = start + interval;

    // make sure we don't step into infinite loop
    if ((max - cursor) / interval > 0) {
        do {
            marks.push(alignValue(cursor, chosenStep));
            cursor += interval;
        } while (cursor < max);

        // do some cosmetic
        const discardThreshold = 1.5;
        if (
            marks.length >= 2 &&
            max - marks[marks.length - 2] <= interval * discardThreshold
        ) {
            marks.pop();
        }
    }
    const marksObject = {};
    marks.forEach(mark => {
        marksObject[mark] = applyD3Format(mark, min, max);
    });
    marksObject[min] = applyD3Format(min, min, max);
    marksObject[max] = applyD3Format(max, min, max);
    return marksObject;
};

/**
 * - Auto generate marks if not given,
 * - Not generate anything at all when explicit null is given to marks
 * - Then truncate marks so no out of range marks
 */
export const sanitizeMarks = ({min, max, marks, step}) => {
    if (marks === null) {
        return undefined;
    }

    const [min_mark, max_mark] = Object.values(setUndefined(min, max, marks));

    const truncated_marks =
        marks && isEmpty(marks) === false
            ? truncateMarks(min_mark, max_mark, marks)
            : marks;

    if (truncated_marks && isEmpty(truncated_marks) === false) {
        return truncated_marks;
    }
    return autoGenerateMarks(min_mark, max_mark, step);
};

/**
 * Calculate default value if not defined
 */
export const calcValue = (min, max, value) => {
    if (value !== undefined) {
        return value;
    }

    return [min, max];
};
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _events = require('events');

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _omxinstance = require('./omxinstance');

var _omxinstance2 = _interopRequireDefault(_omxinstance);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var URI_REGEX = /^(.+):\/\//g;

var OmxManager = function (_EventEmitter) {
  _inherits(OmxManager, _EventEmitter);

  function OmxManager() {
    _classCallCheck(this, OmxManager);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(OmxManager).call(this));

    _this._videosDirectory = './';
    _this._videosExtension = '';
    _this._spawnCommand = 'omxplayer';
    _this._nativeLoop = false;
    return _this;
  }

  _createClass(OmxManager, [{
    key: 'setVideosDirectory',
    value: function setVideosDirectory(path) {
      this._videosDirectory = path;
    }
  }, {
    key: 'setVideosExtension',
    value: function setVideosExtension(ext) {
      this._videosExtension = ext;
    }
  }, {
    key: 'setOmxCommand',
    value: function setOmxCommand(cmd) {
      this._spawnCommand = cmd;
    }
  }, {
    key: 'enableNativeLoop',
    value: function enableNativeLoop() {
      this._nativeLoop = true;
    }
  }, {
    key: '_resolveVideosPath',
    value: function _resolveVideosPath(videos) {
      var ret = [];
      for (var i = 0; i < videos.length; i++) {
        var video = videos[i];

        if (video.match(URI_REGEX)) {
          ret.push(video);
        } else {
          var realPath = _path2.default.resolve(this._videosDirectory, video + this._videosExtension);

          if (_fs2.default.existsSync(realPath)) {
            ret.push(realPath);
          } else {
            var err = {
              error: new Error('File not found: ' + realPath)
            };

            this.emit('error', err);
          }
        }
      }

      return ret;
    }
  }, {
    key: 'create',
    value: function create(videos) {
      var args = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

      if (typeof videos === 'string') {
        videos = [videos];
      }

      videos = this._resolveVideosPath(videos);

      if (videos.length === 0) {
        return null;
      }

      var instance = new _omxinstance2.default(this, this._spawnCommand, videos, args, this._nativeLoop);

      return instance;
    }
  }]);

  return OmxManager;
}(_events.EventEmitter);

exports.default = OmxManager;<commit_msg>Return implemented code not abstract class<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _events = require('events');

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _omxinstance = require('./omxinstance');

var _omxinstance2 = _interopRequireDefault(_omxinstance);

var _keyboardcontroller = require('./keyboardcontroller');

var _keyboardcontroller2 = _interopRequireDefault(_keyboardcontroller);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var URI_REGEX = /^(.+):\/\//g;

var OmxManager = function (_EventEmitter) {
  _inherits(OmxManager, _EventEmitter);

  function OmxManager() {
    _classCallCheck(this, OmxManager);

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(OmxManager).call(this));

    _this._videosDirectory = './';
    _this._videosExtension = '';
    _this._spawnCommand = 'omxplayer';
    _this._nativeLoop = false;
    return _this;
  }

  _createClass(OmxManager, [{
    key: 'setVideosDirectory',
    value: function setVideosDirectory(path) {
      this._videosDirectory = path;
    }
  }, {
    key: 'setVideosExtension',
    value: function setVideosExtension(ext) {
      this._videosExtension = ext;
    }
  }, {
    key: 'setOmxCommand',
    value: function setOmxCommand(cmd) {
      this._spawnCommand = cmd;
    }
  }, {
    key: 'enableNativeLoop',
    value: function enableNativeLoop() {
      this._nativeLoop = true;
    }
  }, {
    key: '_resolveVideosPath',
    value: function _resolveVideosPath(videos) {
      var ret = [];
      for (var i = 0; i < videos.length; i++) {
        var video = videos[i];

        if (video.match(URI_REGEX)) {
          ret.push(video);
        } else {
          var realPath = _path2.default.resolve(this._videosDirectory, video + this._videosExtension);

          if (_fs2.default.existsSync(realPath)) {
            ret.push(realPath);
          } else {
            var err = {
              error: new Error('File not found: ' + realPath)
            };

            this.emit('error', err);
          }
        }
      }

      return ret;
    }
  }, {
    key: 'create',
    value: function create(videos) {
      var args = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];

      if (typeof videos === 'string') {
        videos = [videos];
      }

      videos = this._resolveVideosPath(videos);

      if (videos.length === 0) {
        return null;
      }

      var instance = new _keyboardcontroller2.default(this, this._spawnCommand, videos, args, this._nativeLoop);

      return instance;
    }
  }]);

  return OmxManager;
}(_events.EventEmitter);

exports.default = OmxManager;<|endoftext|>


<commit_before>export default class XhrPromise {
  constructor(url) {
    this._url = url;
  }

  set data(data) {
    this._data = data;
  }

  post() {
    return new Promise((resolve, reject) => {
      let req = new XMLHttpRequest();

      req.addEventListener("onreadystatechange", reqListener);
      req.addEventListener("load", () => { resolve(); });
      req.addEventListener("error", () => { reject("error"); });
      req.addEventListener("abort", () => { reject("abort"); });
      req.addEventListener("timeout", () => { reject("timeout"); });
      req.open("POST", this._url);
      req.withCredentials = true;
      req.setRequestHeader("Content-type", "application/json");

      if (this._data) {
        req.send(JSON.stringify(this._data));
      }
    });
  }

  get() {
    return new Promise((resolve, reject) => {
      let req = new XMLHttpRequest();

      req.addEventListener("onreadystatechange", reqListener);
      req.addEventListener("load", () => { resolve(); });
      req.addEventListener("error", () => { reject("error"); });
      req.addEventListener("abort", () => { reject("abort"); });
      req.addEventListener("timeout", () => { reject("timeout"); });
      req.open("GET", this._url);
      req.withCredentials = true;
      req.setRequestHeader("Content-type", "application/json");

      if (this._data) {
        req.send(JSON.stringify(this._data));
      }
    });
  }
}
<commit_msg>debugging<commit_after>export default class XhrPromise {
  constructor(url) {
    this._url = url;
  }

  set data(data) {
    this._data = data;
  }

  post() {
    return new Promise((resolve, reject) => {
      let req = new XMLHttpRequest();

      req.addEventListener("load", () => { resolve(); });
      req.addEventListener("error", () => { reject("error"); });
      req.addEventListener("abort", () => { reject("abort"); });
      req.addEventListener("timeout", () => { reject("timeout"); });
      req.open("POST", this._url);
      req.withCredentials = true;
      req.setRequestHeader("Content-type", "application/json");

      if (this._data) {
        req.send(JSON.stringify(this._data));
      }
    });
  }

  get() {
    return new Promise((resolve, reject) => {
      let req = new XMLHttpRequest();

      req.addEventListener("load", () => { resolve(); });
      req.addEventListener("error", () => { reject("error"); });
      req.addEventListener("abort", () => { reject("abort"); });
      req.addEventListener("timeout", () => { reject("timeout"); });
      req.open("GET", this._url);
      req.withCredentials = true;
      req.setRequestHeader("Content-type", "application/json");

      if (this._data) {
        req.send(JSON.stringify(this._data));
      }
    });
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * A brief overview of this source file: what is its purpose.
 */

module.exports = {
	add: add,
	modify: modify,
	del: del
};

var ldap = require('ldapjs');

/**
 * Creates a changes object from the parsed array in the changelog object
 */
function changesObject(array) {
	var i;
	var changes = [];

	for (i = 0; i < array.length; i++) {
		var change = new ldap.Change({
			operation: array[i].operation,
            modification: new ldap.Attribute({
                type: array[i].modification.type,
                vals: array[i].modification.vals
            })
        });

        changes.push(change);
	}

    return changes;
}

/**
 * Tests if replication filters match an entry
 */
function matches(replicator, parsedChanges) {

	for (var i = 0; i < replicator.queries.length; i++) {
		var query = replicator.queries[i];

		if (query.filter.matches(parsedChanges)) {
			return true;
		}
	}

	return false;
}

/**
 * Loads the entry from the local UFDS. When entry doesn't exist locally it
 * means that we just need to add it
 */
function getLocalEntry(replicator, entry, callback) {
	var log = replicator.log;
	var ufds = replicator.localUfds;

	var localEntry;
	var opts = { scope: 'base' };
	var targetdn = entry.object.targetdn;

	ufds.search(targetdn, opts, onSearch);

	function onSearch(err, res) {
		if (err) {
			return callback(err);
		}

		res.on('error', onErr);
		res.on('searchEntry', onSearchEntry);
		res.on('end', onSearchEnd);

		function onErr(err) {
            if (err.code === ldap.LDAP_NO_SUCH_OBJECT) {
                return callback();
            }

            log.fatal(err, 'Error searching for local entry');
			return callback(err);
		}

		function onSearchEntry(obj) {
			localEntry = obj;
		}

		function onSearchEnd(res) {
			if (!localEntry) {
				var err = new Error('No local entry but filter matched?');
				return callback(err);
			} else {
				return callback(null, localEntry);
			}
		}
	}
}

/**
 * If a local entry already exists we ignore it
 */
function add(replicator, entry, callback) {
	var log = replicator.log;
	var ufds = replicator.localUfds;

	// TODO: targetdn needs to take replication suffix into account
	var targetdn = entry.object.targetdn;

	// If it's a modify the entry is in parsedEntry
	var theEntry = entry.parsedEntry || entry.parsedChanges;

	ufds.add(targetdn, theEntry, function (err, res) {
		// Ignore existing entries?
		if (err && err.name != 'EntryAlreadyExistsError') {
			log.fatal(err, 'Could not add entry %s', targetdn, theEntry);
			return callback(err);
		}

		log.debug('Entry added %s', targetdn);
		return callback();
	});
}

/**
 * There are 5 scenarios:
 *
 * 1. Both modified and unmodified entries match the filter.
 *   - ufds.modify(targetdn, entry.parsedChanges)
 *
 * 2. Neither entry matches the filter.
 *   - ignore
 *
 * 3. The modified entry doesn't match the filter, but the unmodified entry does.
 *   - ufds.del(targetdn)
 *
 * 4. The modified entry matches the filter, but the unmodified entry does not.
 *   - replace, global entry overrides local entry
 *   - ufds.modify(targetdn, entry.parsedChanges)
 *
 * 5. The entry does not exist locally, but the modified entry matches the filter.
 *   - new entry that matches the replication filter
 *   - ufds.add(targetdn, entry.parsedEntry)
 */
function modify(replicator, entry, callback) {
	var log = replicator.log;
	var targetdn = entry.object.targetdn;

	getLocalEntry(replicator, entry, onLocalEntry);

	function onLocalEntry(err, localEntry) {
		if (err) {
			return callback(err);
		}

		var remoteMatch = matches(replicator, entry.parsedEntry);

		if (!localEntry) {
			// Scenario 5
			if (remoteMatch) {
				return add(replicator, entry, callback);
			// No local entry and replication filter doesn't match remote entry
			} else {
				return callback();
			}

		} else {

			var localMatch = matches(replicator, localEntry.object);

			// Scenario 1. Simple modify
			if (localMatch && remoteMatch) {
				log.debug('Local match and remote match for %s', targetdn);
				return modEntry(replicator, entry, callback);

			// Scenario 3. Entry used to match, we need to delete it
			} else if (localMatch && !remoteMatch) {
				log.debug('Local match and no remote match for %s', targetdn);
				return delEntry(replicator, entry, callback);

			// Scenario 4. Local entry doesn't match, remote has been updated
			} else if (!localMatch && remoteMatch) {
				log.debug('No local match and remote match for %s', targetdn);
				return modEntry(replicator, entry, callback);

			// Scenario 2. Skip
			} else {
				return callback();
			}
		}
	}
}

/*
 * Raw LDAP modify operation. Gets called by ops.mod when a targetdn matches
 * replication
 */
function modEntry(replicator, entry, callback) {
	var log = replicator.log;
	var ufds = replicator.localUfds;

	var targetdn = entry.object.targetdn;
	var changes = changesObject(entry.parsedChanges);

	ufds.modify(targetdn, changes, function (err, res) {
		if (err) {
			return callback(err);
		}

		log.debug('Replicated entry modified %s', targetdn, changes);
		return callback();
	});
}

/*
 * Raw LDAP delete operation. Gets called by ops.del when a targetdn matches
 * replication
 */
function delEntry(replicator, entry, callback) {
	var log = replicator.log;
	var ufds = replicator.localUfds;

	var targetdn = entry.object.targetdn;

	ufds.del(targetdn, function (err, res) {
		if (err) {
			return callback(err);
		}

		log.debug('Replicated entry deleted %s', targetdn);
		return callback();
	});
}

/**
 * There are 3 scenarios:
 *
 * 1. The entry exists locally and matches the replication filter.
 *   - ufds.del(targetdn)
 *
 * 2. The entry doesn't exist locally.
 *   - ignore
 *
 * 3. The entry exists locally and doesn't match the replication filter.
 *   - ignore
 */
function del(replicator, entry, callback) {
	var log = replicator.log;
	var targetdn = entry.object.targetdn;

	getLocalEntry(replicator, entry, onLocalEntry);

	function onLocalEntry(err, localEntry) {
		if (err) {
			return callback(err);
		}

		// Scenario 2. No local entry, why bother
		if (!localEntry) {
			return callback();
		} else {
			var localMatch = matches(replicator, localEntry.object);

			// Scenario 1. Delete
			if (localMatch) {
				log.debug('Local match for deleting %s', targetdn);
				return delEntry(replicator, entry, callback);

			// Scenario 3. Doesn't match replication filter, ignore
			} else {
				return callback();
			}
		}
	}
}
<commit_msg>CAPI-215: Ignore LDAP_NOT_ALLOWED_ON_NON_LEAF for delete operations<commit_after>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * A brief overview of this source file: what is its purpose.
 */

module.exports = {
	add: add,
	modify: modify,
	del: del
};

var ldap = require('ldapjs');

/**
 * Creates a changes object from the parsed array in the changelog object
 */
function changesObject(array) {
	var i;
	var changes = [];

	for (i = 0; i < array.length; i++) {
		var change = new ldap.Change({
			operation: array[i].operation,
            modification: new ldap.Attribute({
                type: array[i].modification.type,
                vals: array[i].modification.vals
            })
        });

        changes.push(change);
	}

    return changes;
}

/**
 * Tests if replication filters match an entry
 */
function matches(replicator, parsedChanges) {

	for (var i = 0; i < replicator.queries.length; i++) {
		var query = replicator.queries[i];

		if (query.filter.matches(parsedChanges)) {
			return true;
		}
	}

	return false;
}

/**
 * Loads the entry from the local UFDS. When entry doesn't exist locally it
 * means that we just need to add it
 */
function getLocalEntry(replicator, entry, callback) {
	var log = replicator.log;
	var ufds = replicator.localUfds;

	var localEntry;
	var opts = { scope: 'base' };
	var targetdn = entry.object.targetdn;

	ufds.search(targetdn, opts, onSearch);

	function onSearch(err, res) {
		if (err) {
			return callback(err);
		}

		res.on('error', onErr);
		res.on('searchEntry', onSearchEntry);
		res.on('end', onSearchEnd);

		function onErr(err) {
            if (err.code === ldap.LDAP_NO_SUCH_OBJECT) {
                return callback();
            }

            log.fatal(err, 'Error searching for local entry');
			return callback(err);
		}

		function onSearchEntry(obj) {
			localEntry = obj;
		}

		function onSearchEnd(res) {
			if (!localEntry) {
				var err = new Error('No local entry but filter matched?');
				return callback(err);
			} else {
				return callback(null, localEntry);
			}
		}
	}
}

/**
 * If a local entry already exists we ignore it
 */
function add(replicator, entry, callback) {
	var log = replicator.log;
	var ufds = replicator.localUfds;

	// TODO: targetdn needs to take replication suffix into account
	var targetdn = entry.object.targetdn;

	// If it's a modify the entry is in parsedEntry
	var theEntry = entry.parsedEntry || entry.parsedChanges;

	ufds.add(targetdn, theEntry, function (err, res) {
		// Ignore existing entries?
		if (err && err.name != 'EntryAlreadyExistsError') {
			log.fatal(err, 'Could not add entry %s', targetdn, theEntry);
			return callback(err);
		}

		log.debug('Entry added %s', targetdn);
		return callback();
	});
}

/**
 * There are 5 scenarios:
 *
 * 1. Both modified and unmodified entries match the filter.
 *   - ufds.modify(targetdn, entry.parsedChanges)
 *
 * 2. Neither entry matches the filter.
 *   - ignore
 *
 * 3. The modified entry doesn't match the filter, but the unmodified entry does.
 *   - ufds.del(targetdn)
 *
 * 4. The modified entry matches the filter, but the unmodified entry does not.
 *   - replace, global entry overrides local entry
 *   - ufds.modify(targetdn, entry.parsedChanges)
 *
 * 5. The entry does not exist locally, but the modified entry matches the filter.
 *   - new entry that matches the replication filter
 *   - ufds.add(targetdn, entry.parsedEntry)
 */
function modify(replicator, entry, callback) {
	var log = replicator.log;
	var targetdn = entry.object.targetdn;

	getLocalEntry(replicator, entry, onLocalEntry);

	function onLocalEntry(err, localEntry) {
		if (err) {
			return callback(err);
		}

		var remoteMatch = matches(replicator, entry.parsedEntry);

		if (!localEntry) {
			// Scenario 5
			if (remoteMatch) {
				return add(replicator, entry, callback);
			// No local entry and replication filter doesn't match remote entry
			} else {
				return callback();
			}

		} else {

			var localMatch = matches(replicator, localEntry.object);

			// Scenario 1. Simple modify
			if (localMatch && remoteMatch) {
				log.debug('Local match and remote match for %s', targetdn);
				return modEntry(replicator, entry, callback);

			// Scenario 3. Entry used to match, we need to delete it
			} else if (localMatch && !remoteMatch) {
				log.debug('Local match and no remote match for %s', targetdn);
				return delEntry(replicator, entry, callback);

			// Scenario 4. Local entry doesn't match, remote has been updated
			} else if (!localMatch && remoteMatch) {
				log.debug('No local match and remote match for %s', targetdn);
				return modEntry(replicator, entry, callback);

			// Scenario 2. Skip
			} else {
				return callback();
			}
		}
	}
}

/*
 * Raw LDAP modify operation. Gets called by ops.mod when a targetdn matches
 * replication
 */
function modEntry(replicator, entry, callback) {
	var log = replicator.log;
	var ufds = replicator.localUfds;

	var targetdn = entry.object.targetdn;
	var changes = changesObject(entry.parsedChanges);

	ufds.modify(targetdn, changes, function (err, res) {
		if (err) {
			return callback(err);
		}

		log.debug('Replicated entry modified %s', targetdn, changes);
		return callback();
	});
}

/*
 * Raw LDAP delete operation. Gets called by ops.del when a targetdn matches
 * replication
 */
function delEntry(replicator, entry, callback) {
	var log = replicator.log;
	var ufds = replicator.localUfds;

	var targetdn = entry.object.targetdn;

	ufds.del(targetdn, function (err, res) {
		if (err) {
			if (err.code && (err.code === ldap.LDAP_NOT_ALLOWED_ON_NON_LEAF)) {
				log.warn('Local entry %s has child entries and cannot be ' +
					'deleted because of an LDAP_NOT_ALLOWED_ON_NON_LEAF ' +
					'error, ignoring local delete operation', targetdn);
				return callback();
			} else {
				return callback(err);
			}
		}

		log.debug('Replicated entry deleted %s', targetdn);
		return callback();
	});
}

/**
 * There are 3 scenarios:
 *
 * 1. The entry exists locally and matches the replication filter.
 *   - ufds.del(targetdn)
 *
 * 2. The entry doesn't exist locally.
 *   - ignore
 *
 * 3. The entry exists locally and doesn't match the replication filter.
 *   - ignore
 */
function del(replicator, entry, callback) {
	var log = replicator.log;
	var targetdn = entry.object.targetdn;

	getLocalEntry(replicator, entry, onLocalEntry);

	function onLocalEntry(err, localEntry) {
		if (err) {
			return callback(err);
		}

		// Scenario 2. No local entry, why bother
		if (!localEntry) {
			return callback();
		} else {
			var localMatch = matches(replicator, localEntry.object);

			// Scenario 1. Delete
			if (localMatch) {
				log.debug('Local match for deleting %s', targetdn);
				return delEntry(replicator, entry, callback);

			// Scenario 3. Doesn't match replication filter, ignore
			} else {
				return callback();
			}
		}
	}
}
<|endoftext|>


<commit_before>var Stream = require("./stream.js").Stream;
var Lexer  = require("./lexer.js").Lexer;
var Node   = require("./node.js").Node;

function Parser() {
  this.inlineParser = new InlineParser();
}

Parser.prototype = {
  initStatus: function (stream) {
    if (typeof stream === "string")
      stream = new Stream(stream);
    this.lexer = new Lexer(stream);
    this.nodes = [];
  },

  parse: function (stream) {
    this.initStatus(stream);
    this.parseDocument();
    return {
      nodes  : this.nodes,
      title  : this.title,
      author : this.author
    };
  },

  skipBlank: function () {
    var blankToken = null;
    while (this.lexer.peekNextToken().type === Lexer.tokens.blank)
      blankToken = this.lexer.getNextToken();
    return blankToken;
  },

  // ------------------------------------------------------------
  // <Document> ::= <Element>*
  // ------------------------------------------------------------

  parseDocument: function () {
    this.parseTitle();

    while (this.lexer.hasNext()) {
      var element = this.parseElement();
      if (element) this.nodes.push(element);
    }
  },

  parseTitle: function () {
    this.skipBlank();

    if (this.lexer.hasNext() &&
        this.lexer.peekNextToken().type === Lexer.tokens.line)
      this.title = this.createTextNode(this.lexer.getNextToken().content);
    else
      this.title = null;

    this.lexer.pushDummyTokenByType(Lexer.tokens.blank);
  },

  // ------------------------------------------------------------
  // <Element> ::= (<Header> | <List>
  //              | <Preformatted> | <Paragraph>
  //              | <Table>)*
  // ------------------------------------------------------------

  parseElement: function () {
    var element = null;

    switch (this.lexer.peekNextToken().type) {
    case Lexer.tokens.header:
      element = this.parseHeader();
      break;
    case Lexer.tokens.preformatted:
      element = this.parsePreformatted();
      break;
    case Lexer.tokens.orderedListElement:
    case Lexer.tokens.unorderedListElement:
      element = this.parseList();
      break;
    case Lexer.tokens.line:
      element = this.parseText();
      break;
    case Lexer.tokens.tableRow:
    case Lexer.tokens.tableSeparator:
      element = this.parseTable();
      break;
    case Lexer.tokens.blank:
      this.skipBlank();
      if (this.lexer.hasNext()) {
        if (this.lexer.peekNextToken().type === Lexer.tokens.line)
          element = this.parseParagraph();
        else
          element = this.parseElement();
      }
      break;
    case Lexer.tokens.horizontalRule:
      this.lexer.getNextToken();
      element = Node.createHorizontalRule();
      break;
    case Lexer.tokens.comment:
      // Skip
      this.lexer.getNextToken();
      break;
    default:
      throw new Error("Unhandled token: " + this.lexer.peekNextToken().type);
    }

    return element;
  },

  // ------------------------------------------------------------
  // <Header>
  //
  // : preformatted
  // : block
  // ------------------------------------------------------------

  parseHeader: function () {
    var headerToken = this.lexer.getNextToken();
    var header = Node.createHeader([
      this.createTextNode(headerToken.content) // TODO: Parse inline markups
    ], { level: headerToken.level });

    return header;
  },

  // ------------------------------------------------------------
  // <Preformatted>
  //
  // : preformatted
  // : block
  // ------------------------------------------------------------

  parsePreformatted: function () {
    var preformattedFirstToken = this.lexer.peekNextToken();
    var preformatted = Node.createPreformatted([]);

    var textContents = [];

    while (this.lexer.hasNext()) {
      var token = this.lexer.peekNextToken();
      if (token.type !== Lexer.tokens.preformatted ||
          token.indentation < preformattedFirstToken.indentation)
        break;
      this.lexer.getNextToken();
      textContents.push(token.content);
    }

    preformatted.children.push(this.createTextNode(textContents.join("\n")));

    return preformatted;
  },

  // ------------------------------------------------------------
  // <List>
  //
  //  - foo
  //    1. bar
  //    2. baz
  // ------------------------------------------------------------

  // XXX: not consider codes (e.g., =Foo::Bar=)
  definitionPattern: /^(.*?) :: *(.*)$/,

  parseList: function () {
    var rootToken = this.lexer.peekNextToken();
    var list;
    var isDefinitionList = false;

    if (this.definitionPattern.test(rootToken.content)) {
      list = Node.createDefinitionList([]);
      isDefinitionList = true;
    } else {
      list = rootToken.type === Lexer.tokens.unorderedListElement ?
        Node.createUnorderedList([]) : Node.createOrderedList([]);
    }

    while (this.lexer.hasNext()) {
      var nextToken = this.lexer.peekNextToken();
      if (!nextToken.isListElement() || nextToken.indentation !== rootToken.indentation)
        break;
      list.children.push(this.parseListElement(rootToken.indentation, isDefinitionList));
    }

    return list;
  },

  unknownDefinitionTerm: "???",

  parseListElement: function (rootIndentation, isDefinitionList) {
    var listElementToken = this.lexer.getNextToken();
    var listElement = Node.createListElement([]);

    listElement.isDefinitionList = isDefinitionList;

    if (isDefinitionList) {
      var match = this.definitionPattern.exec(listElementToken.content);
      listElement.term = [
        this.createTextNode(match && match[1] ? match[1] : this.unknownDefinitionTerm)
      ];
      listElement.children.push(this.createTextNode(match ? match[2] : listElementToken.content));
    } else {
      listElement.children.push(this.createTextNode(listElementToken.content));
    }

    while (this.lexer.hasNext()) {
      var blankToken = this.skipBlank();
      if (!this.lexer.hasNext())
        break;

      var notBlankNextToken = this.lexer.peekNextToken();
      if (blankToken && !notBlankNextToken.isListElement())
        this.lexer.pushToken(blankToken); // Recover blank token only when next line is not listElement.
      if (notBlankNextToken.indentation <= rootIndentation)
        break;                  // end of the list

      var element = this.parseElement(); // recursive
      if (element)
        listElement.children.push(element);
    }

    return listElement;
  },

  // ------------------------------------------------------------
  // <Table> ::= <TableRow>+
  // ------------------------------------------------------------

  parseTable: function () {
    var table = Node.createTable([]);
    var nextToken;
    var sawSeparator = false;

    while (this.lexer.hasNext() &&
           (nextToken = this.lexer.peekNextToken()).isTableElement()) {
      if (nextToken.type === Lexer.tokens.tableRow) {
        var tableRow = this.parseTableRow();
        table.children.push(tableRow);
      } else {
        sawSeparator = true;
        this.lexer.getNextToken();
      }
    }

    if (sawSeparator && table.children.length) {
      table.children[0].children.forEach(function (cell) {
        cell.isHeader = true;
      });
    }

    return table;
  },

  // ------------------------------------------------------------
  // <TableRow> ::= <TableCell>+
  // ------------------------------------------------------------

  parseTableRow: function () {
    var tableRowToken = this.lexer.getNextToken();

    // XXX: Low performance
    return Node.createTableRow(
      tableRowToken.content
        .split("|")
        .map(function (text) {
          return Node.createTableCell([
            this.createTextNode(text)
          ]);
        }, this)
    );
  },

  // ------------------------------------------------------------
  // <Paragraph> ::= <Blank> <Line>*
  // ------------------------------------------------------------

  parseParagraph: function () {
    var paragraphFisrtToken = this.lexer.peekNextToken();
    var paragraph = Node.createParagraph([]);

    var textContents = [];

    while (this.lexer.hasNext()) {
      var nextToken = this.lexer.peekNextToken();
      if (nextToken.type !== Lexer.tokens.line
          || nextToken.indentation < paragraphFisrtToken.indentation)
        break;
      this.lexer.getNextToken();
      textContents.push(nextToken.content);
    }

    paragraph.children.push(this.createTextNode(textContents.join("\n")));

    return paragraph;
  },

  parseText: function () {
    var lineToken = this.lexer.getNextToken();
    return this.createTextNode(lineToken.content);
  },

  // ------------------------------------------------------------
  // <Text> (DOM Like)
  // ------------------------------------------------------------

  createTextNode: function (text) {
    return this.inlineParser.parseEmphasis(text);
  }
};

// ------------------------------------------------------------
// Parser for Inline Elements
//
// @refs org-emphasis-regexp-components
// ------------------------------------------------------------

function InlineParser() {
  this.preEmphasis     = " \t\\('\"";
  this.postEmphasis    = "- \t.,:!?;'\"\\)";
  this.borderForbidden = " \t\r\n,\"'";
  this.bodyRegexp      = "[\\s\\S]*?";
  this.markers         = "*/_=~+";

  this.imageExtensions = [
    "bmp", "png", "jpeg", "jpg", "gif", "tiff",
    "tif", "xbm", "xpm", "pbm", "pgm", "ppm"
  ].join("|");

  this.emphasisPattern = this.buildEmphasisPattern();
  this.linkPattern = /\[\[([^\]]*)\](?:\[([^\]]*)\])?\]/g; // \1 => link, \2 => text
}

InlineParser.prototype = {
  parseEmphasis: function (text) {
    var emphasisPattern = this.emphasisPattern;
    emphasisPattern.lastIndex = 0;

    var result = [],
        match,
        previousLast = 0,
        savedLastIndex;

    while ((match = emphasisPattern.exec(text))) {
      var whole  = match[0];
      var pre    = match[1];
      var marker = match[2];
      var body   = match[3];
      var post   = match[4];

      {
        // parse links
        var matchBegin = emphasisPattern.lastIndex - whole.length;
        var beforeContent = text.substring(previousLast, matchBegin + pre.length);
        savedLastIndex = emphasisPattern.lastIndex;
        result.push(this.parseLink(beforeContent));
        emphasisPattern.lastIndex = savedLastIndex;
      }

      var bodyNode = [Node.createText(null, { value: body })];
      var bodyContainer = this.emphasizeElementByMarker(bodyNode, marker);
      result.push(bodyContainer);

      previousLast = emphasisPattern.lastIndex - post.length;
    }

    if (emphasisPattern.lastIndex === 0 ||
        emphasisPattern.lastIndex !== text.length - 1)
      result.push(this.parseLink(text.substring(previousLast)));

    return Node.createInlineContainer(result);
  },

  depth: 0,
  parseLink: function (text) {
    var linkPattern = this.linkPattern;
    linkPattern.lastIndex = 0;

    var match,
        result = [],
        previousLast = 0,
        savedLastIndex;

    while ((match = linkPattern.exec(text))) {
      var whole = match[0];
      var src   = match[1];
      var title = match[2];

      // parse before content
      var matchBegin = linkPattern.lastIndex - whole.length;
      var beforeContent = text.substring(previousLast, matchBegin);
      result.push(Node.createText(null, { value: beforeContent }));

      // parse link
      var link = Node.createLink([]);
      link.src = src;
      if (title) {
        savedLastIndex = linkPattern.lastIndex;
        link.children.push(this.parseEmphasis(title));
        linkPattern.lastIndex = savedLastIndex;
      } else {
        link.children.push(Node.createText(null, { value: src }));
      }
      result.push(link);

      previousLast = linkPattern.lastIndex;
    }

    if (linkPattern.lastIndex === 0 ||
        linkPattern.lastIndex !== text.length - 1)
      result.push(Node.createText(null, { value: text.substring(previousLast) }));

    return Node.createInlineContainer(result);
  },

  emphasizeElementByMarker: function (element, marker) {
    switch (marker) {
    case "*":
      return Node.createBold(element);
    case "/":
      return Node.createItalic(element);
    case "_":
      return Node.createUnderline(element);
    case "=":
    case "~":
      return Node.createCode(element);
    case "+":
      return Node.createDashed(element);
    }
  },

  buildEmphasisPattern: function () {
    return new RegExp(
      "([" + this.preEmphasis + "]|^)" +                     // \1 => pre
        "([" + this.markers + "])" +                         // \2 => marker
        "([^" + this.borderForbidden + "]|" +                // \3 => body
        "[^" + this.borderForbidden + "]" +
        this.bodyRegexp +
        "[^" + this.borderForbidden + "])" +
        "\\2" +
        "([" + this.postEmphasis +"]|$)",                    // \4 => post
        // flags
        "g"
    );
  }
};

if (typeof exports !== "undefined") {
  exports.Parser = Parser;
  exports.InlineParser = InlineParser;
}
<commit_msg>Do not emphasize pre-formatted texts<commit_after>var Stream = require("./stream.js").Stream;
var Lexer  = require("./lexer.js").Lexer;
var Node   = require("./node.js").Node;

function Parser() {
  this.inlineParser = new InlineParser();
}

Parser.prototype = {
  initStatus: function (stream) {
    if (typeof stream === "string")
      stream = new Stream(stream);
    this.lexer = new Lexer(stream);
    this.nodes = [];
  },

  parse: function (stream) {
    this.initStatus(stream);
    this.parseDocument();
    return {
      nodes  : this.nodes,
      title  : this.title,
      author : this.author
    };
  },

  skipBlank: function () {
    var blankToken = null;
    while (this.lexer.peekNextToken().type === Lexer.tokens.blank)
      blankToken = this.lexer.getNextToken();
    return blankToken;
  },

  // ------------------------------------------------------------
  // <Document> ::= <Element>*
  // ------------------------------------------------------------

  parseDocument: function () {
    this.parseTitle();

    while (this.lexer.hasNext()) {
      var element = this.parseElement();
      if (element) this.nodes.push(element);
    }
  },

  parseTitle: function () {
    this.skipBlank();

    if (this.lexer.hasNext() &&
        this.lexer.peekNextToken().type === Lexer.tokens.line)
      this.title = this.createTextNode(this.lexer.getNextToken().content);
    else
      this.title = null;

    this.lexer.pushDummyTokenByType(Lexer.tokens.blank);
  },

  // ------------------------------------------------------------
  // <Element> ::= (<Header> | <List>
  //              | <Preformatted> | <Paragraph>
  //              | <Table>)*
  // ------------------------------------------------------------

  parseElement: function () {
    var element = null;

    switch (this.lexer.peekNextToken().type) {
    case Lexer.tokens.header:
      element = this.parseHeader();
      break;
    case Lexer.tokens.preformatted:
      element = this.parsePreformatted();
      break;
    case Lexer.tokens.orderedListElement:
    case Lexer.tokens.unorderedListElement:
      element = this.parseList();
      break;
    case Lexer.tokens.line:
      element = this.parseText();
      break;
    case Lexer.tokens.tableRow:
    case Lexer.tokens.tableSeparator:
      element = this.parseTable();
      break;
    case Lexer.tokens.blank:
      this.skipBlank();
      if (this.lexer.hasNext()) {
        if (this.lexer.peekNextToken().type === Lexer.tokens.line)
          element = this.parseParagraph();
        else
          element = this.parseElement();
      }
      break;
    case Lexer.tokens.horizontalRule:
      this.lexer.getNextToken();
      element = Node.createHorizontalRule();
      break;
    case Lexer.tokens.comment:
      // Skip
      this.lexer.getNextToken();
      break;
    default:
      throw new Error("Unhandled token: " + this.lexer.peekNextToken().type);
    }

    return element;
  },

  // ------------------------------------------------------------
  // <Header>
  //
  // : preformatted
  // : block
  // ------------------------------------------------------------

  parseHeader: function () {
    var headerToken = this.lexer.getNextToken();
    var header = Node.createHeader([
      this.createTextNode(headerToken.content) // TODO: Parse inline markups
    ], { level: headerToken.level });

    return header;
  },

  // ------------------------------------------------------------
  // <Preformatted>
  //
  // : preformatted
  // : block
  // ------------------------------------------------------------

  parsePreformatted: function () {
    var preformattedFirstToken = this.lexer.peekNextToken();
    var preformatted = Node.createPreformatted([]);

    var textContents = [];

    while (this.lexer.hasNext()) {
      var token = this.lexer.peekNextToken();
      if (token.type !== Lexer.tokens.preformatted ||
          token.indentation < preformattedFirstToken.indentation)
        break;
      this.lexer.getNextToken();
      textContents.push(token.content);
    }

    preformatted.children.push(this.createTextNode(textContents.join("\n"), true /* no emphasis */));

    return preformatted;
  },

  // ------------------------------------------------------------
  // <List>
  //
  //  - foo
  //    1. bar
  //    2. baz
  // ------------------------------------------------------------

  // XXX: not consider codes (e.g., =Foo::Bar=)
  definitionPattern: /^(.*?) :: *(.*)$/,

  parseList: function () {
    var rootToken = this.lexer.peekNextToken();
    var list;
    var isDefinitionList = false;

    if (this.definitionPattern.test(rootToken.content)) {
      list = Node.createDefinitionList([]);
      isDefinitionList = true;
    } else {
      list = rootToken.type === Lexer.tokens.unorderedListElement ?
        Node.createUnorderedList([]) : Node.createOrderedList([]);
    }

    while (this.lexer.hasNext()) {
      var nextToken = this.lexer.peekNextToken();
      if (!nextToken.isListElement() || nextToken.indentation !== rootToken.indentation)
        break;
      list.children.push(this.parseListElement(rootToken.indentation, isDefinitionList));
    }

    return list;
  },

  unknownDefinitionTerm: "???",

  parseListElement: function (rootIndentation, isDefinitionList) {
    var listElementToken = this.lexer.getNextToken();
    var listElement = Node.createListElement([]);

    listElement.isDefinitionList = isDefinitionList;

    if (isDefinitionList) {
      var match = this.definitionPattern.exec(listElementToken.content);
      listElement.term = [
        this.createTextNode(match && match[1] ? match[1] : this.unknownDefinitionTerm)
      ];
      listElement.children.push(this.createTextNode(match ? match[2] : listElementToken.content));
    } else {
      listElement.children.push(this.createTextNode(listElementToken.content));
    }

    while (this.lexer.hasNext()) {
      var blankToken = this.skipBlank();
      if (!this.lexer.hasNext())
        break;

      var notBlankNextToken = this.lexer.peekNextToken();
      if (blankToken && !notBlankNextToken.isListElement())
        this.lexer.pushToken(blankToken); // Recover blank token only when next line is not listElement.
      if (notBlankNextToken.indentation <= rootIndentation)
        break;                  // end of the list

      var element = this.parseElement(); // recursive
      if (element)
        listElement.children.push(element);
    }

    return listElement;
  },

  // ------------------------------------------------------------
  // <Table> ::= <TableRow>+
  // ------------------------------------------------------------

  parseTable: function () {
    var table = Node.createTable([]);
    var nextToken;
    var sawSeparator = false;

    while (this.lexer.hasNext() &&
           (nextToken = this.lexer.peekNextToken()).isTableElement()) {
      if (nextToken.type === Lexer.tokens.tableRow) {
        var tableRow = this.parseTableRow();
        table.children.push(tableRow);
      } else {
        sawSeparator = true;
        this.lexer.getNextToken();
      }
    }

    if (sawSeparator && table.children.length) {
      table.children[0].children.forEach(function (cell) {
        cell.isHeader = true;
      });
    }

    return table;
  },

  // ------------------------------------------------------------
  // <TableRow> ::= <TableCell>+
  // ------------------------------------------------------------

  parseTableRow: function () {
    var tableRowToken = this.lexer.getNextToken();

    // XXX: Low performance
    return Node.createTableRow(
      tableRowToken.content
        .split("|")
        .map(function (text) {
          return Node.createTableCell([
            this.createTextNode(text)
          ]);
        }, this)
    );
  },

  // ------------------------------------------------------------
  // <Paragraph> ::= <Blank> <Line>*
  // ------------------------------------------------------------

  parseParagraph: function () {
    var paragraphFisrtToken = this.lexer.peekNextToken();
    var paragraph = Node.createParagraph([]);

    var textContents = [];

    while (this.lexer.hasNext()) {
      var nextToken = this.lexer.peekNextToken();
      if (nextToken.type !== Lexer.tokens.line
          || nextToken.indentation < paragraphFisrtToken.indentation)
        break;
      this.lexer.getNextToken();
      textContents.push(nextToken.content);
    }

    paragraph.children.push(this.createTextNode(textContents.join("\n")));

    return paragraph;
  },

  parseText: function (noEmpasis) {
    var lineToken = this.lexer.getNextToken();
    return this.createTextNode(lineToken.content, noEmpasis);
  },

  // ------------------------------------------------------------
  // <Text> (DOM Like)
  // ------------------------------------------------------------

  createTextNode: function (text, noEmpasis) {
    return noEmpasis ? Node.createText(null, { value: text })
      : this.inlineParser.parseEmphasis(text);
  }
};

// ------------------------------------------------------------
// Parser for Inline Elements
//
// @refs org-emphasis-regexp-components
// ------------------------------------------------------------

function InlineParser() {
  this.preEmphasis     = " \t\\('\"";
  this.postEmphasis    = "- \t.,:!?;'\"\\)";
  this.borderForbidden = " \t\r\n,\"'";
  this.bodyRegexp      = "[\\s\\S]*?";
  this.markers         = "*/_=~+";

  this.imageExtensions = [
    "bmp", "png", "jpeg", "jpg", "gif", "tiff",
    "tif", "xbm", "xpm", "pbm", "pgm", "ppm"
  ].join("|");

  this.emphasisPattern = this.buildEmphasisPattern();
  this.linkPattern = /\[\[([^\]]*)\](?:\[([^\]]*)\])?\]/g; // \1 => link, \2 => text
}

InlineParser.prototype = {
  parseEmphasis: function (text) {
    var emphasisPattern = this.emphasisPattern;
    emphasisPattern.lastIndex = 0;

    var result = [],
        match,
        previousLast = 0,
        savedLastIndex;

    while ((match = emphasisPattern.exec(text))) {
      var whole  = match[0];
      var pre    = match[1];
      var marker = match[2];
      var body   = match[3];
      var post   = match[4];

      {
        // parse links
        var matchBegin = emphasisPattern.lastIndex - whole.length;
        var beforeContent = text.substring(previousLast, matchBegin + pre.length);
        savedLastIndex = emphasisPattern.lastIndex;
        result.push(this.parseLink(beforeContent));
        emphasisPattern.lastIndex = savedLastIndex;
      }

      var bodyNode = [Node.createText(null, { value: body })];
      var bodyContainer = this.emphasizeElementByMarker(bodyNode, marker);
      result.push(bodyContainer);

      previousLast = emphasisPattern.lastIndex - post.length;
    }

    if (emphasisPattern.lastIndex === 0 ||
        emphasisPattern.lastIndex !== text.length - 1)
      result.push(this.parseLink(text.substring(previousLast)));

    return Node.createInlineContainer(result);
  },

  depth: 0,
  parseLink: function (text) {
    var linkPattern = this.linkPattern;
    linkPattern.lastIndex = 0;

    var match,
        result = [],
        previousLast = 0,
        savedLastIndex;

    while ((match = linkPattern.exec(text))) {
      var whole = match[0];
      var src   = match[1];
      var title = match[2];

      // parse before content
      var matchBegin = linkPattern.lastIndex - whole.length;
      var beforeContent = text.substring(previousLast, matchBegin);
      result.push(Node.createText(null, { value: beforeContent }));

      // parse link
      var link = Node.createLink([]);
      link.src = src;
      if (title) {
        savedLastIndex = linkPattern.lastIndex;
        link.children.push(this.parseEmphasis(title));
        linkPattern.lastIndex = savedLastIndex;
      } else {
        link.children.push(Node.createText(null, { value: src }));
      }
      result.push(link);

      previousLast = linkPattern.lastIndex;
    }

    if (linkPattern.lastIndex === 0 ||
        linkPattern.lastIndex !== text.length - 1)
      result.push(Node.createText(null, { value: text.substring(previousLast) }));

    return Node.createInlineContainer(result);
  },

  emphasizeElementByMarker: function (element, marker) {
    switch (marker) {
    case "*":
      return Node.createBold(element);
    case "/":
      return Node.createItalic(element);
    case "_":
      return Node.createUnderline(element);
    case "=":
    case "~":
      return Node.createCode(element);
    case "+":
      return Node.createDashed(element);
    }
  },

  buildEmphasisPattern: function () {
    return new RegExp(
      "([" + this.preEmphasis + "]|^)" +                     // \1 => pre
        "([" + this.markers + "])" +                         // \2 => marker
        "([^" + this.borderForbidden + "]|" +                // \3 => body
        "[^" + this.borderForbidden + "]" +
        this.bodyRegexp +
        "[^" + this.borderForbidden + "])" +
        "\\2" +
        "([" + this.postEmphasis +"]|$)",                    // \4 => post
        // flags
        "g"
    );
  }
};

if (typeof exports !== "undefined") {
  exports.Parser = Parser;
  exports.InlineParser = InlineParser;
}
<|endoftext|>


<commit_before>/**
 * User class
 *
 * @returns {Users}
 */
function Users() {

    var selfObj = this;
    var baseUrl = null;

    /**
     * Set the error merge file message.
     * @param {string} merge_msg
     *
     */
    this.setBaseUrl = function (base_url) {
        baseUrl = base_url;
    }

    /**
     *
     * @returns {undefined}
     */
    this.bindAll = function () {
        selfObj.onChangeRole();
//        selfObj.applyChosen();
        selfObj.getOrganizationProjects();
    }
    /**
     *
     * @returns {undefined}
     */
    this.onChangeRole = function () {
        $('#roles').change(function () {
            var selectedRole = $(this).val();
            if (selectedRole != 'ROLE_SUPER_ADMIN') {
                $('#userOrganization').attr('required', 'required');
                $('#orgDiv').show();
            } else {
                $('#userOrganization').removeAttr('required');
                $('#orgDiv').hide();
            }
            if (selectedRole == 'ROLE_CATALOGER' || selectedRole == 'ROLE_USER') {
                $('.projectsDiv').show();
                $('#userProjects').attr('required', 'required');
                $("#userProjects").chosen();
            } else {
                $('#userProjects').removeAttr('required');
                $('.projectsDiv').hide();
            }
        }).change();
    }
    /**
     *
     * @returns {undefined}
     */
    this.applyChosen = function () {
        $("#userProjects").chosen();
    }

    this.getOrganizationProjects = function () {
        $('#userOrganization').change(function () {
            if ($(this).val()) {
                url = baseUrl + 'getOrganizationProjects/' + $(this).val();
                $.ajax({
                    type: "GET",
                    url: url,
                    success: function (response) {
                        if (response != "") {
                            $("#userProjects").html(response);
                            $("#userProjects").trigger("chosen:updated");
                        }else{
                            $("#userProjects").html("");
                            $("#userProjects").trigger("chosen:updated");
                        }
                    }

                }); // Ajax Call
            }
        });
    }
}<commit_msg>organization dropdown<commit_after>/**
 * User class
 *
 * @returns {Users}
 */
function Users() {

    var selfObj = this;
    var baseUrl = null;

    /**
     * Set the error merge file message.
     * @param {string} merge_msg
     *
     */
    this.setBaseUrl = function (base_url) {
        baseUrl = base_url;
    }

    /**
     *
     * @returns {undefined}
     */
    this.bindAll = function () {
        selfObj.onChangeRole();
//        selfObj.applyChosen();
        selfObj.getOrganizationProjects();
    }
    /**
     *
     * @returns {undefined}
     */
    this.onChangeRole = function () {
        $('#roles').change(function () {
            var selectedRole = $(this).val();
            if (selectedRole != 'ROLE_SUPER_ADMIN') {
                $('#userOrganization').attr('required', 'required');
                $('#orgDiv').show();
            } else {
                $('#userOrganization').removeAttr('required');
                $('#orgDiv').hide();
            }
            if (selectedRole == 'ROLE_CATALOGER' || selectedRole == 'ROLE_USER') {
                $('.projectsDiv').show();
                $('#userProjects').attr('required', 'required');
                $("#userProjects").chosen();
                $('#orgDiv').show();
            } else {
                $('#userProjects').removeAttr('required');
                $('.projectsDiv').hide();
            }
        }).change();
    }
    /**
     *
     * @returns {undefined}
     */
    this.applyChosen = function () {
        $("#userProjects").chosen();
    }

    this.getOrganizationProjects = function () {
        $('#userOrganization').change(function () {
            if ($(this).val()) {
                url = baseUrl + 'getOrganizationProjects/' + $(this).val();
                $.ajax({
                    type: "GET",
                    url: url,
                    success: function (response) {
                        if (response != "") {
                            $("#userProjects").html(response);
                            $("#userProjects").trigger("chosen:updated");
                        }else{
                            $("#userProjects").html("");
                            $("#userProjects").trigger("chosen:updated");
                        }
                    }

                }); // Ajax Call
            }
        });
    }
}<|endoftext|>


<commit_before>var lob = require('lob-enc');
var util = require('util')
var events = require('events');
var countListeners = events.EventEmitter.listenerCount;

util.inherits(Pipe, events.EventEmitter)

var uids = 0;
function Pipe(type, keepalive)
{
  this.type = type;
  this.isPipe = true;
  this.uid = uids++;
  this.cloaked = false;

  if(keepalive)
    this.keepalive(keepalive);
}

Pipe.prototype.keepalive = function Pipe_keepalive(timeout)
{
  clearInterval(this.timer);
  if(typeof timeout === 'number'){
    this.timer = setInterval(function keepalive_interval(pipe){
      if (!pipe.emit('keepalive'))
        clearInterval(pipe.timer);
    }, timeout, this);
  }
}

Pipe.prototype.send = function Pipe_send()
{
  this.keepalive();
  this.sentAt = Date.now();
  if(!countListeners(this,'send') && !this.onSend)
    return console.log((new Error('internal error, no pipe.onSend')).stack  ,this);
  // automatically add cloaking
  if(this.cloaked && lob.isPacket(arguments[0]))
    arguments[0] = lob.cloak(arguments[0]);

  if (!this.onSend)
    this.emit('send',this,arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
  else
    this.onSend.apply(this, arguments)
},

module.exports = Pipe;
<commit_msg>add docs for pipes<commit_after>var lob = require('lob-enc');
var util = require('util')
var events = require('events');
var countListeners = events.EventEmitter.listenerCount;

util.inherits(Pipe, events.EventEmitter)

var uids = 0;

/** A Pipe is a simple eventemmiter that bridges between telehash transports and {TLink}s
 * @class Pipe
 * @constructor
 * @param {string} type - 'udp4', 'tcp4', 'http-client' etc.
 * @param {number} keepalive - the amaount of time between keepalive events
 * @return {Pipe}
 */
function Pipe(type, keepalive)
{
  this.type = type;
  this.isPipe = true;
  this.uid = uids++;
  this.cloaked = false;

  if(keepalive)
    this.keepalive(keepalive);
  return this;
}

/** Clear the previous keepalive interval and set a new one (or just clear it)
 * @param {number=} timeout - the interval
 * @fires Pipe#keepalive
 */

Pipe.prototype.keepalive = function Pipe_keepalive(timeout)
{
  clearInterval(this.timer);
  /**
   * keepalive event. used by Link to manage connectivity over multiple pipes
   *
   * @event Pipe#keepalive
   * @type {null}
   */
  if(typeof timeout === 'number'){
    this.timer = setInterval(function keepalive_interval(pipe){
      if (!pipe.emit('keepalive'))
        clearInterval(pipe.timer);
    }, timeout, this);
  }
}

/** this triggers the send mechanism of the underlying transport.
 * @param {Buffer=} packet - handshake, open, or an ordinary packet...
 * @param {TLink=} link -
 * @param {function=} callback - called after the packet is sent
 * @fires Pipe#send
 */
Pipe.prototype.send = function Pipe_send()
{
  this.keepalive();
  this.sentAt = Date.now();
  if(!countListeners(this,'send') && !this.onSend)
    return console.log((new Error('internal error, no pipe.onSend')).stack  ,this);
  // automatically add cloaking
  if(this.cloaked && lob.isPacket(arguments[0]))
    arguments[0] = lob.cloak(arguments[0]);

  if (!this.onSend)
    this.emit('send',this,arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
  else
    this.onSend.apply(this, arguments)
},

module.exports = Pipe;
<|endoftext|>


<commit_before>/*
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.
 */

import React from 'react';

const Light = ({ imageUrl, ...rest }) => {
  return (

  );
};

export default Light;
<commit_msg>fixed license quote convention<commit_after>/*
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.
 */

import React from 'react';

const Light = ({ imageUrl, ...rest }) => {
  return (

  );
};

export default Light;
<|endoftext|>


<commit_before>//@auth
//@req(url, name)

import com.hivext.api.core.utils.Transport;

//reading script from URL
var body = new Transport().get(url)

//delete the script if it exists already
jelastic.dev.scripting.DeleteScript(name);

//create a new script
return jelastic.dev.scripting.CreateScript(name, 'js', body);
<commit_msg>Update create-service.js<commit_after>//@auth
//@req(url, name, cron)

import com.hivext.api.core.utils.Transport;

//reading script from URL
var body = new Transport().get(url)

//delete the script if it exists already
jelastic.dev.scripting.DeleteScript(name);

//create a new script
var resp = jelastic.dev.scripting.CreateScript(name, 'js', body);
if (resp.result != 0) return resp;

var tasks = jelastic.utils.scheduler.GetTasks().objects;
var description = "start-stop-scheduler";

for (var i = 0, l = tasks.length; i < l; i++){
    var t = tasks[i];
    //if (t.description == description)
      jelastic.utils.scheduler.RemoveTask(t.id);
}

var resp = jelastic.utils.scheduler.AddTask(script, "cron:" + cron, description, "{action: 'start'}");
return resp;
<|endoftext|>


<commit_before>/**
 * @author Tzuyang Tsai (shiyou0130011)
 * @license Apache-2.0
 */

/**
 * @constructor
 * @param variables {String|Object} An url string or an object
 */
function URLVariables(variables) {
	if (!(this instanceof URLVariables)) {
		return new URLVariables(variables)
	}
	this.decode(variables)
}
/**
 * Converts the url string or object to the specified URLVariables object.
 * @param {String|Object}	An url string or an object
 * @example var u = new URLVariables;
 *          u.decode("a=1&b=2&c=3&a=2")
 *          u.decode({a: [1, 2], b: 2, c: 3})
 * @return {URLVariables}	this
 */
URLVariables.prototype.decode = function (source) {
	switch (typeof source) {
		case "string":
			var url = source.split("?")
			var urlvar = url[url.length-1].split("&")
			for (var i in urlvar) {
				var data = urlvar[i].split("=")
				var name = decodeURIComponent(data[0]), value = decodeURIComponent(data[1])
				if (!(this[name] instanceof Array)) {
					if (this[name]) {
						this[name] = [this[name]]
					}
					this[name] = [value]

				}else{
					this[name].push(value)
				}
			}
			break
		case "object":
			for(var i in source) {
				if (this[i] != undefined) {
					if (!(this[i] instanceof Array)) {
						this[i] = [this[i]]
					}
				}else{
					this[i] = []
				}

				if (source[i] instanceof Array) {
					[].push.apply(this[i], source[i])
				}else{
					this[i].push(source[i])
				}
			}
	}
	return this
}

/**
 * @return {String} The string containing all variables, in the MIME content encoding application/x-www-form-urlencoded.
 */
URLVariables.prototype.toString = function () {
	var urlvar_keys = []
	for(var i in this) {
		if (typeof this[i] != "function" && !URLVariables.prototype[i])
			urlvar_keys.push(i)
	}
	urlvar_keys.sort()

	var l = []
	for (i in urlvar_keys) {
		var key = urlvar_keys[i]
		if (!(this[key] instanceof Array)){
			this[key] = [this[key]]
		}

		this[key].sort()
		this[key].forEach(function(val, index, array) {
			l.push(encodeURIComponent(key) + "=" + encodeURIComponent(val))
		})
	}
	return l.join("&")
}<commit_msg>修正 url 取得 query 的 bug<commit_after>/**
 * @author Tzuyang Tsai (shiyou0130011)
 * @license Apache-2.0
 */

/**
 * @constructor
 * @param variables {String|Object} An url string or an object
 */
function URLVariables(variables) {
	if (!(this instanceof URLVariables)) {
		return new URLVariables(variables)
	}
	this.decode(variables)
}
/**
 * Converts the url string or object to the specified URLVariables object.
 * @param {String|Object}	An url string or an object
 * @example var u = new URLVariables;
 *          u.decode("a=1&b=2&c=3&a=2")
 *          u.decode({a: [1, 2], b: 2, c: 3})
 * @return {URLVariables}	this
 */
URLVariables.prototype.decode = function (source) {
	switch (typeof source) {
		case "string":
			var url = source
			if(url.indexOf("?") >= 0){
				url = url.substr(url.indexOf("?") + 1)
			}

			var urlvar = url[url.length-1].split("&")
			for (var i in urlvar) {
				var data = urlvar[i].split("=")
				var name = decodeURIComponent(data[0]),
				value = decodeURIComponent(data[1])
				if (!(this[name] instanceof Array)) {
					if (this[name]) {
						this[name] = [this[name]]
					}
					this[name] = [value]

				}else{
					this[name].push(value)
				}
			}
			break
		case "object":
			for(var i in source) {
				if (this[i] != undefined) {
					if (!(this[i] instanceof Array)) {
						this[i] = [this[i]]
					}
				}else{
					this[i] = []
				}

				if (source[i] instanceof Array) {
					[].push.apply(this[i], source[i])
				}else{
					this[i].push(source[i])
				}
			}
	}
	return this
}

/**
 * @return {String} The string containing all variables, in the MIME content encoding application/x-www-form-urlencoded.
 */
URLVariables.prototype.toString = function () {
	var urlvar_keys = []
	for(var i in this) {
		if (typeof this[i] != "function" && !URLVariables.prototype[i])
			urlvar_keys.push(i)
	}
	urlvar_keys.sort()

	var l = []
	for (i in urlvar_keys) {
		var key = urlvar_keys[i]
		if (!(this[key] instanceof Array)){
			this[key] = [this[key]]
		}

		this[key].sort()
		this[key].forEach(function(val, index, array) {
			l.push(encodeURIComponent(key) + "=" + encodeURIComponent(val))
		})
	}
	return l.join("&")
}<|endoftext|>


<commit_before>const devAPI = 'http://localhost:4000'
const prodAPI = 'http://ec2-52-206-122-212.compute-1.amazonaws.com'

export default () => {
  const env = process.env.NODE_ENV
  if (env === 'development') {
    return prodAPI
  } else if(env === 'production') {
    return prodAPI
  } else {
    return devAPI
  }

}
<commit_msg>Clean up<commit_after>const devAPI = 'http://localhost:4000'
const prodAPI = 'http://ec2-52-206-122-212.compute-1.amazonaws.com'

export default () => {
  const env = process.env.NODE_ENV
  if (env === 'development') {
    return devAPI
  } else if(env === 'production') {
    return prodAPI
  } else {
    return devAPI
  }

}
<|endoftext|>


<commit_before>import parser from '../parser';
import writer from '../cli/lib/writer';

const change = ({ type, msg, cwd, parserInstance = parser(cwd), write = writer({ parserInstance }) }) => {
    return parserInstance
        .change(parserInstance.SEPARATORS[type], msg)
        .then(write);
};

export default change;

export const TYPE = {
    ADDED : 'Added',
    CHANGED : 'Changed',
    FIXED : 'Fixed',
    SECURITY : 'Security',
    DEPRECATED : 'Deprecated',
    REMOVED : 'Removed'
};
<commit_msg>Fixed issue with CHANGE_TYPES not matching parser instance SEPARATORS<commit_after>import parser from '../parser';
import writer from '../cli/lib/writer';

const change = ({ type, msg, cwd, parserInstance = parser(cwd), write = writer({ parserInstance }) }) => {
    return parserInstance
        .change(parserInstance.SEPARATORS[type], msg)
        .then(write);
};

export default change;

export const TYPE = {
    ADDED : 'added',
    CHANGED : 'changed',
    FIXED : 'fixed',
    SECURITY : 'security',
    DEPRECATED : 'deprecated',
    REMOVED : 'removed'
};
<|endoftext|>