<commit_before>const Keymap = require("browserkeymap")

// ;; Input rules are regular expressions describing a piece of text
// that, when typed, causes something to happen. This might be
// changing two dashes into an emdash, wrapping a paragraph starting
// with `"> "` into a blockquote, or something entirely different.
class InputRule {
  // :: (RegExp, union<string, (state: EditorState, match: [string], start: number, end: number) → EditorTransform>)
  // Create an input rule. The rule applies when the user typed
  // something and the text directly in front of the cursor matches
  // `match`, which should probably end with `$`.
  //
  // The `handler` can be a string, in which case the matched text
  // will simply be replaced by that string, or a function, which will
  // be called with the match array produced by
  // [`RegExp.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec),
  // and should produce a new state in which the rule has taken
  // effect, or null to indicate the input was not handled.
  constructor(match, handler) {
    this.match = match
    this.handler = typeof handler == "string" ? stringHandler(handler) : handler
  }
}
exports.InputRule = InputRule

function stringHandler(string) {
  return function(state, match, start, end, realStart) {
    let insert = string
    if (match[1]) {
      start += match[0].length - match[1].length
      if (start > realStart) {
        insert = match[0].slice(start - realStart, match[0].length - match[1].length) + insert
        start = realStart
      }
    }
    let marks = state.doc.marksAt(start)
    return state.tr.replaceWith(start, end, state.schema.text(insert, marks))
  }
}

const MAX_MATCH = 100

exports.inputRules = function({rules}) {
  return {
    stateFields: {
      appliedInputRule: {
        init() { return null },
        applyTransform(_, _tr, options) { return options.fromInputRule },
        applySelection() { return null }
      }
    },

    applyTextInput(state, from, to, text) {
      let $from = state.doc.resolve(from)
      let textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - MAX_MATCH), $from.parentOffset,
                                                null, "\ufffc") + text
      for (let i = 0; i < rules.length; i++) {
        let match = rules[i].match.exec(textBefore)
        let transform = match && rules[i].handler(state, match, from - (match[0].length - text.length), to, from)
        if (transform)
          return transform.apply({fromInputRule: {transform, from, to, text}})
      }
    },

    keymaps: [new Keymap({Backspace: maybeUndoInputRule})]
  }
}

function maybeUndoInputRule(state) {
  let undoable = state.appliedInputRule
  if (!undoable) return null
  let tr = state.tr, toUndo = undoable.transform
  for (let i = toUndo.steps.length - 1; i >= 0; i--)
    tr.step(toUndo.steps[i].invert(toUndo.docs[i]))
  let marks = tr.doc.marksAt(undoable.from)
  tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks))
  return tr.apply()
}
<commit_msg>Remove dependency on browserkeymap, use simple onKeyDown, onKeyPress handlers<commit_after>// ;; Input rules are regular expressions describing a piece of text
// that, when typed, causes something to happen. This might be
// changing two dashes into an emdash, wrapping a paragraph starting
// with `"> "` into a blockquote, or something entirely different.
class InputRule {
  // :: (RegExp, union<string, (state: EditorState, match: [string], start: number, end: number) → EditorTransform>)
  // Create an input rule. The rule applies when the user typed
  // something and the text directly in front of the cursor matches
  // `match`, which should probably end with `$`.
  //
  // The `handler` can be a string, in which case the matched text
  // will simply be replaced by that string, or a function, which will
  // be called with the match array produced by
  // [`RegExp.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec),
  // and should produce a new state in which the rule has taken
  // effect, or null to indicate the input was not handled.
  constructor(match, handler) {
    this.match = match
    this.handler = typeof handler == "string" ? stringHandler(handler) : handler
  }
}
exports.InputRule = InputRule

function stringHandler(string) {
  return function(state, match, start, end, realStart) {
    let insert = string
    if (match[1]) {
      start += match[0].length - match[1].length
      if (start > realStart) {
        insert = match[0].slice(start - realStart, match[0].length - match[1].length) + insert
        start = realStart
      }
    }
    let marks = state.doc.marksAt(start)
    return state.tr.replaceWith(start, end, state.schema.text(insert, marks))
  }
}

const MAX_MATCH = 100

exports.inputRules = function({rules}) {
  return {
    stateFields: {
      appliedInputRule: {
        init() { return null },
        applyTransform(_, _tr, options) { return options.fromInputRule },
        applySelection() { return null }
      }
    },

    applyTextInput(state, from, to, text) {
      let $from = state.doc.resolve(from)
      let textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - MAX_MATCH), $from.parentOffset,
                                                null, "\ufffc") + text
      for (let i = 0; i < rules.length; i++) {
        let match = rules[i].match.exec(textBefore)
        let transform = match && rules[i].handler(state, match, from - (match[0].length - text.length), to, from)
        if (transform)
          return transform.apply({fromInputRule: {transform, from, to, text}})
      }
    },

    onKeyDown(view, event) {
      if (event.keyCode == 8) return maybeUndoInputRule(view.state, view.props.onAction)
      return false
    }
  }
}

function maybeUndoInputRule(state, onAction) {
  let undoable = state.appliedInputRule
  if (!undoable) return false
  let tr = state.tr, toUndo = undoable.transform
  for (let i = toUndo.steps.length - 1; i >= 0; i--)
    tr.step(toUndo.steps[i].invert(toUndo.docs[i]))
  let marks = tr.doc.marksAt(undoable.from)
  tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks))
  onAction(tr.action())
  return true
}
<|endoftext|>


<commit_before>/*

HDXStatiscs class. Used to fetch
statistics from HDX's statistics service,
Funnel.Space.

*/

var HDXStatistics = {
  base: 'http://funnel.space/api/',
  available_metrics: [],
  metrics: function (callback) {
    d3.json(this.base + 'metrics', function (error, data) {
      if (error) {
        return error
      }
      data.resources.forEach(function (x) { this.HDXStatistics.available_metrics.push(x.metricid) })
      console.log('Available metrics from Funnel Space:', this.HDXStatistics.available_metrics)
    })
  },
  fetch: function (metricid) {
    d3.json(this.base + 'funnels?metricid=' + metricid, function (error, data) {
      if (error) {
        return error
      }
      console.log(data)
    })
  },
  latest: function (metricid, container_id, round_value) {
    d3.json(this.base + 'funnels?metricid=' + metricid, function (error, data) {
      if (error) {
        return error
      }
      var output = _.maxBy(data.resources, 'period_end_date')
      document.getElementById(container_id).innerHTML = _.round(output.value, round_value)
    })
  }
}
<commit_msg>Created new logic for pulling latest figures from funnel space.<commit_after>/*

HDXStatiscs class. Used to fetch
statistics from HDX's statistics service,
Funnel.Space.

*/

var HDXStatistics = {
  base: 'http://funnel.space/api/',
  available_metrics: [],
  metrics: function (callback) {
    d3.json(this.base + 'metrics', function (error, data) {
      if (error) {
        return error
      }
      data.resources.forEach(function (x) { this.HDXStatistics.available_metrics.push(x.metricid) })
      console.log('Available metrics from Funnel Space:', this.HDXStatistics.available_metrics)
    })
  },
  fetch: function (metricid) {
    d3.json(this.base + 'funnels?metricid=' + metricid, function (error, data) {
      if (error) {
        return error
      }
      console.log(data)
    })
  },
  mean: function (metricid, container_id, round_value) {
    d3.json(this.base + 'funnels?metricid=' + metricid + '&period_type=d', function (error, data) {
      if (error) {
        return error
      }
      var output = _.sumBy(data.resources, 'value') / data.resources.length
      document.getElementById(container_id).innerHTML = numeral(_.round(output.value, round_value)).format('0,0')
    })
  },
  share: function (metricid, container_id, round_value) {
    d3.json(this.base + 'funnels?metricid=' + metricid, function (error, data) {
      if (error) {
        return error
      }
      var output = _.maxBy(data.resources, 'period_end_date')
      document.getElementById(container_id).innerHTML = numeral(_.round(output.value, round_value)).format('0%')
    })
  },
  latest: function (metricid, container_id, round_value) {
    d3.json(this.base + 'funnels?metricid=' + metricid, function (error, data) {
      if (error) {
        return error
      }
      var output = _.maxBy(data.resources, 'period_end_date')
      document.getElementById(container_id).innerHTML = numeral(_.round(output.value, round_value)).format('0,0')
    })
  },
  cumulative: function (metricid, container_id, round_value) {
    d3.json(this.base + 'funnels?metricid=' + metricid + '&period_type=w', function (error, data) {
      if (error) {
        return error
      }
      var output = _.sumBy(data.resources, 'value')
      console.log(output)
      document.getElementById(container_id).innerHTML = _.round(output, round_value)
    })
  }
}
<|endoftext|>


<commit_before>locale.de = {
    modes: {
        add_area: {
            title: "Fläche",
            description: "Füge Parks, Gebäude, Seen oder andere Flächen zur Karte hinzu.",
            tail: "Klicke in die Karte, um das Zeichnen einer Fläche wie einen Park, einen See oder Gebäude zu starten.",
            key: "A"
        },
        add_line: {
            title: "Linie",
            description: "Linien können Autobahnen, Straßen, Fußwege oder sogar Kanäle sein.",
            tail: "Klicke in die Karte, um das Zeichnen einer Straße eines Pfades oder einer Route zu starten.",
            key: "L"
        },
        add_point: {
            title: "Punkt",
            description: "Restaurants, Denkmäler und Briefkästen sind Punkte",
            tail: "Klicke in die Karte, um einen Punkt hinzuzufügen.",
            key: "P"
        },
        browse: {
            title: "Navigation",
            description: "Verschieben und Vergrößern/Verkleinern des Kartenausschnitts.",
            key: "B"
        },
        draw_area: {
            tail: "Klicke, um Punkte zur Fläche hinzuzufügen. Klicke auf den ersten Punkt, um die Fläche abzuschließen."
        },
        draw_line: {
            tail: "Klicke, um mehr Punkte zur Linie hizuzufügen. Klicke auf eine andere Linie um die Linien zu verbinden und klicke doppelt, um die Linie zu beenden."
        }
    },

    operations: {
        add: {
            annotation: {
                point: "Punkt hinzugefügt.",
                vertex: "Stützpunkt einem Weg hinzugefügt."
            }
        },
        start: {
            annotation: {
                line: "Linie begonnen.",
                area: "Fläche begonnen."
            }
        },
        'continue': {
            annotation: {
                line: "Linie fortgesetzt.",
                area: "Fläche fortgesetzt."
            }
        },
        cancel_draw: {
            annotation: "Zeichnen abgebrochen."
        },
        change_tags: {
            annotation: "Tags verändert."
        },
        circularize: {
            title: "Abrunden",
            description: "Runde dies ab.",
            key: "O",
            annotation: {
                line: "Runde eine Linie ab.",
                area: "Runde eine Fläche ab."
            }
        },
        orthogonalize: {
            title: "Rechtwinkligkeit herstellen",
            description: "Diese Ecken rechtwinklig ausrichten.",
            key: "Q",
            annotation: {
                line: "Die Ecken einer Linie rechtwinklig ausgerichtet.",
                area: "Die Ecken einer Fläche rechtwinklig ausgerichtet."
            }
        },
        'delete': {
            title: "Löschen",
            description: "Lösche dies aus der Karte.",
            key: "⌫",
            annotation: {
                point: "Punkt gelöscht.",
                vertex: "Stützpunkt aus einem Weg gelöscht.",
                line: "Linie gelöscht.",
                area: "Fläche gelöscht.",
                relation: "Verbindung gelöscht.",
                multiple: "{n} Objekte gelöscht."
            }
        },
        connect: {
            annotation: {
                point: "Weg mit einem Punkt verbunden.",
                vertex: "Weg mit einem anderem Weg verbunden.",
                line: "Weg mit einer Linie verbunden.",
                area: "Weg mit einer Fläche verbunden."
            }
        },
        disconnect: {
            title: "Trennen",
            description: "Trenne diese Wege voneinander.",
            key: "D",
            annotation: "Wege getrennt."
        },
        merge: {
            title: "Vereinigen",
            description: "Vereinige diese Linien.",
            key: "C",
            annotation: "{n} Linien vereinigt."
        },
        move: {
            title: "Verschieben",
            description: "Verschiebe dieses Objekt an einen anderen Ort.",
            key: "M",
            annotation: {
                point: "Punkt verschoben.",
                vertex: "Stützpunkt in einen Weg veschoben.",
                line: "Linie verschoben.",
                area: "Fläche verschoben."
            }
        },
        reverse: {
            title: "Umkehren",
            description: "Ändere die Richtung dieser Linie.",
            key: "V",
            annotation: "Linienrichtung umgekehrt."
        },
        split: {
            title: "Teilen",
            description: "Teile dies in zwei Wege an diesem Punkt.",
            key: "X",
            annotation: "Weg geteilt."
        }
    },

    validations: {
        untagged_point: "Punkt ohne Attribute, der kein Teil einer Linie oder Fläche ist",
        untagged_line: "Linie ohne Attribute",
        untagged_area: "Fläche ohne Attribute",
        tag_suggests_area: "Das Attribut {tag} suggeriert eine Fläche, ist aber keine Fläche",
        deprecated_tags: "Veralterte Attribute: {tags}"
    },

    save: "Speichern",
    save_help: "Speichere Änderungen zu OpenStreetMap, so dass sie für andere Nutzer sichtbar werden",
    no_changes: "Sie haben keine Änderungen zum Speichern.",
    save_error: "Es ist ein Fehler aufgetreten beim Versuch des Speicherns",
    uploading_changes: "Lade Änderungen zu OpenStreetMap.",
    just_edited: "Sie haben gerade OpenStreetMap editiert!",
    okay: "Okay",

    "zoom-in": "Hineinzoomen",
    "zoom-out": "Herauszoomen",

    nothing_to_undo: "Nichts zum Rückgängigmachen.",
    nothing_to_redo: "Nichts zum Wiederherstellen.",

    browser_notice: "Dieser Editor wird in Firefox, Chrome, Safari, Opera, und Internet Explorer 9 und höher unterstzützt. Bitte aktualisieren Sie Ihren Browser oder nutzen Sie Potlatch 2, um die Karte zu modifizieren.",

    inspector: {
        no_documentation_combination:  "Für dieses Attribut ist keine Dokumentation verfügbar.",
        no_documentation_key: "Für dises Schlüsselwort ist keine Dokumentation verfügbar",
        new_tag: "Neues Attribut"
    },

    view_on_osm: "Bei OSM anschauen",

    zoom_in_edit: "Hineinzoomen, um die Karte zu editieren",

    edit_tags: "Attribute bearbeiten",

    geocoder: {
        "find_location": "Finde einen Ort",
        "find_a_place": "Finde einen Platz"
    },

    description: "Beschreibung",

    logout: "Abmelden",

    layerswitcher: {
        title: "Hintergrund",
        description: "Hintergrundeinstellungen",
        percent_brightness: "{opacity}% Helligkeit",
        fix_misalignment: "Fehlerhafte Ausrichtung reparieren",
        reset: "Zurücksetzen"
    }
};
<commit_msg>Update locale/de.js<commit_after>locale.de = {
    modes: {
        add_area: {
            title: "Fläche",
            description: "Füge Parks, Gebäude, Seen oder andere Flächen zur Karte hinzu.",
            tail: "Klicke in die Karte, um das Zeichnen einer Fläche wie einen Park, einen See oder Gebäude zu starten.",
            key: "A"
        },
        add_line: {
            title: "Linie",
            description: "Linien können Autobahnen, Straßen, Fußwege oder sogar Kanäle sein.",
            tail: "Klicke in die Karte, um das Zeichnen einer Straße eines Pfades oder einer Route zu starten.",
            key: "L"
        },
        add_point: {
            title: "Punkt",
            description: "Restaurants, Denkmäler und Briefkästen sind Punkte",
            tail: "Klicke in die Karte, um einen Punkt hinzuzufügen.",
            key: "P"
        },
        browse: {
            title: "Navigation",
            description: "Verschieben und Vergrößern/Verkleinern des Kartenausschnitts.",
            key: "B"
        },
        draw_area: {
            tail: "Klicke, um Punkte zur Fläche hinzuzufügen. Klicke auf den ersten Punkt, um die Fläche abzuschließen."
        },
        draw_line: {
            tail: "Klicke, um mehr Punkte zur Linie hizuzufügen. Klicke auf eine andere Linie um die Linien zu verbinden und klicke doppelt, um die Linie zu beenden."
        }
    },

    operations: {
        add: {
            annotation: {
                point: "Punkt hinzugefügt.",
                vertex: "Stützpunkt einem Weg hinzugefügt."
            }
        },
        start: {
            annotation: {
                line: "Linie begonnen.",
                area: "Fläche begonnen."
            }
        },
        'continue': {
            annotation: {
                line: "Linie fortgesetzt.",
                area: "Fläche fortgesetzt."
            }
        },
        cancel_draw: {
            annotation: "Zeichnen abgebrochen."
        },
        change_tags: {
            annotation: "Tags verändert."
        },
        circularize: {
            title: "Abrunden",
            description: "Runde dies ab.",
            key: "O",
            annotation: {
                line: "Runde eine Linie ab.",
                area: "Runde eine Fläche ab."
            }
        },
        orthogonalize: {
            title: "Rechtwinkligkeit herstellen",
            description: "Diese Ecken rechtwinklig ausrichten.",
            key: "Q",
            annotation: {
                line: "Die Ecken einer Linie rechtwinklig ausgerichtet.",
                area: "Die Ecken einer Fläche rechtwinklig ausgerichtet."
            }
        },
        'delete': {
            title: "Löschen",
            description: "Lösche dies aus der Karte.",
            key: "⌫",
            annotation: {
                point: "Punkt gelöscht.",
                vertex: "Stützpunkt aus einem Weg gelöscht.",
                line: "Linie gelöscht.",
                area: "Fläche gelöscht.",
                relation: "Verbindung gelöscht.",
                multiple: "{n} Objekte gelöscht."
            }
        },
        connect: {
            annotation: {
                point: "Weg mit einem Punkt verbunden.",
                vertex: "Weg mit einem anderem Weg verbunden.",
                line: "Weg mit einer Linie verbunden.",
                area: "Weg mit einer Fläche verbunden."
            }
        },
        disconnect: {
            title: "Trennen",
            description: "Trenne diese Wege voneinander.",
            key: "D",
            annotation: "Wege getrennt."
        },
        merge: {
            title: "Vereinigen",
            description: "Vereinige diese Linien.",
            key: "C",
            annotation: "{n} Linien vereinigt."
        },
        move: {
            title: "Verschieben",
            description: "Verschiebe dieses Objekt an einen anderen Ort.",
            key: "M",
            annotation: {
                point: "Punkt verschoben.",
                vertex: "Stützpunkt in einen Weg veschoben.",
                line: "Linie verschoben.",
                area: "Fläche verschoben."
            }
        },
        reverse: {
            title: "Umkehren",
            description: "Ändere die Richtung dieser Linie.",
            key: "V",
            annotation: "Linienrichtung umgekehrt."
        },
        split: {
            title: "Teilen",
            description: "Teile dies in zwei Wege an diesem Punkt.",
            key: "X",
            annotation: "Weg geteilt."
        }
    },

    validations: {
        untagged_point: "Punkt ohne Attribute, der kein Teil einer Linie oder Fläche ist",
        untagged_line: "Linie ohne Attribute",
        untagged_area: "Fläche ohne Attribute",
        tag_suggests_area: "Das Attribut {tag} suggeriert eine Fläche, ist aber keine Fläche",
        deprecated_tags: "Veralterte Attribute: {tags}"
    },

    save: "Speichern",
    save_help: "Speichere Änderungen zu OpenStreetMap, so dass sie für andere Nutzer sichtbar werden",
    no_changes: "Sie haben keine Änderungen zum Speichern.",
    save_error: "Es ist ein Fehler aufgetreten beim Versuch des Speicherns",
    uploading_changes: "Lade Änderungen zu OpenStreetMap.",
    just_edited: "Sie haben gerade OpenStreetMap editiert!",
    okay: "Okay",

    "zoom-in": "Hineinzoomen",
    "zoom-out": "Herauszoomen",

    nothing_to_undo: "Nichts zum Rückgängigmachen.",
    nothing_to_redo: "Nichts zum Wiederherstellen.",

    browser_notice: "Dieser Editor wird in Firefox, Chrome, Safari, Opera, und Internet Explorer 9 und höher unterstzützt. Bitte aktualisieren Sie Ihren Browser oder nutzen Sie Potlatch 2, um die Karte zu modifizieren.",

    inspector: {
        no_documentation_combination:  "Für dieses Attribut ist keine Dokumentation verfügbar.",
        no_documentation_key: "Für dises Schlüsselwort ist keine Dokumentation verfügbar",
        new_tag: "Neues Attribut"
    },

    view_on_osm: "Bei OSM anschauen",

    zoom_in_edit: "Hineinzoomen, um die Karte zu editieren",

    edit_tags: "Attribute bearbeiten",

    geocoder: {
        title: "Suche einen Ort",
        placeholder: "suche einen Ort",
        no_results: "Der Ort '{name}' konnte nicht gefunden werden"
    },

    description: "Beschreibung",

    logout: "Abmelden",

    layerswitcher: {
        title: "Hintergrund",
        description: "Hintergrundeinstellungen",
        percent_brightness: "{opacity}% Helligkeit",
        fix_misalignment: "Fehlerhafte Ausrichtung reparieren",
        reset: "Zurücksetzen"
    }
};
<|endoftext|>


<commit_before>/**
 * The main CLI logic. This orchestrates all argument parsing, command loading,
 * validation, and execution.
 *
 * @module cli
 *
 * @copyright
 * Copyright (c) 2013 by Appcelerator, Inc. All Rights Reserved.
 *
 * @license
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var fs = require('fs'),
	path = require('path'),

	// flag used to make sure we don't require the native module twice
	initialized = false,

	// the native module
	iosDeviceModule,

	// reference counter to track how many trackDevice() calls are active
	pumping = 0,

	// the setInterval() reference
	interval;

/**
 * Detects which version of node-ios-device should be require()'d.
 */
function loadIosDeviceModule() {
	if (initialized) return;

	var lib = './out/node-ios-device';
	if (process.versions.modules > 0x000B) {
		lib += '-isolate';
	}

	var file = path.resolve(lib + '.node');
	if (!fs.existsSync(file)) {
		throw new Error('Missing compatible node-ios-device library');
	}

	iosDeviceModule = require(lib);
	initialized = true;
}

/**
 * Retrieves an array of all connected iOS devices.
 *
 * @param {Function} callback(err, devices) - A function to call with the connected devices
 */
exports.devices = function devices(callback) {
	if (process.platform != 'darwin') {
		return callback(new Error('OS "' + process.platform + '" not supported'));
	}

	loadIosDeviceModule();
	iosDeviceModule.pumpRunLoop();

	callback(null, iosDeviceModule.devices());
};

/**
 * Continuously retrieves an array of all connected iOS devices. Whenever a
 * device is connected or disconnected, the specified callback is fired.
 *
 * @param {Function} callback(err, devices) - A function to call with the connected devices
 * @returns {Function} off() - A function that discontinues tracking
 */
exports.trackDevices = function trackDevices(callback) {
	if (process.platform != 'darwin') {
		return callback(new Error('OS "' + process.platform + '" not supported'));
	}

	loadIosDeviceModule();

	// if we're not already pumping, start up the pumper
	if (!pumping) {
		interval = setInterval(iosDeviceModule.pumpRunLoop, exports.pumpInterval);
	}
	pumping++;

	// immediately return the array of devices
	exports.devices(callback);

	var off = false;

	// listen for any device connects or disconnects
	iosDeviceModule.on("devicesChanged", function (devices) {
		off || callback(null, iosDeviceModule.devices());
	});

	// return the off() function
	return function () {
		if (!off) {
			off = true;
			pumping = Math.max(pumping - 1, 0);
			pumping || clearInterval(interval);
		}
	};
};

/**
 * Installs an iOS app on the specified device.
 *
 * @param {Function} callback(err) - A function to call when the install finishes
 */
exports.installApp = function installApp(udid, appPath, callback) {
	if (process.platform != 'darwin') {
		return callback(new Error('OS "' + process.platform + '" not supported'));
	}

	appPath = path.resolve(appPath);
	if (!fs.existsSync(appPath)) {
		return callback(new Error('Specified .app path does not exist'));
	}
	if (!fs.statSync(appPath).isDirectory() || !fs.existsSync(path.join(appPath, 'PkgInfo'))) {
		return callback(new Error('Specified .app path is not a valid app'));
	}

	loadIosDeviceModule();
	iosDeviceModule.pumpRunLoop();

	try {
		iosDeviceModule.installApp(udid, appPath);
		callback(null);
	} catch (ex) {
		callback(ex);
	}
};<commit_msg>Fixed bug with wrong module path.<commit_after>/**
 * The main CLI logic. This orchestrates all argument parsing, command loading,
 * validation, and execution.
 *
 * @module cli
 *
 * @copyright
 * Copyright (c) 2013 by Appcelerator, Inc. All Rights Reserved.
 *
 * @license
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

var fs = require('fs'),
	path = require('path'),

	// flag used to make sure we don't require the native module twice
	initialized = false,

	// the native module
	iosDeviceModule,

	// reference counter to track how many trackDevice() calls are active
	pumping = 0,

	// the setInterval() reference
	interval;

/**
 * Detects which version of node-ios-device should be require()'d.
 */
function loadIosDeviceModule() {
	if (initialized) return;

	var lib = __dirname + '/out/node-ios-device';
	if (process.versions.modules > 0x000B) {
		lib += '-isolate';
	}

	var file = path.resolve(lib + '.node');
	if (!fs.existsSync(file)) {
		throw new Error('Missing compatible node-ios-device library');
	}

	iosDeviceModule = require(lib);
	initialized = true;
}

/**
 * Retrieves an array of all connected iOS devices.
 *
 * @param {Function} callback(err, devices) - A function to call with the connected devices
 */
exports.devices = function devices(callback) {
	if (process.platform != 'darwin') {
		return callback(new Error('OS "' + process.platform + '" not supported'));
	}

	loadIosDeviceModule();
	iosDeviceModule.pumpRunLoop();

	callback(null, iosDeviceModule.devices());
};

/**
 * Continuously retrieves an array of all connected iOS devices. Whenever a
 * device is connected or disconnected, the specified callback is fired.
 *
 * @param {Function} callback(err, devices) - A function to call with the connected devices
 * @returns {Function} off() - A function that discontinues tracking
 */
exports.trackDevices = function trackDevices(callback) {
	if (process.platform != 'darwin') {
		return callback(new Error('OS "' + process.platform + '" not supported'));
	}

	loadIosDeviceModule();

	// if we're not already pumping, start up the pumper
	if (!pumping) {
		interval = setInterval(iosDeviceModule.pumpRunLoop, exports.pumpInterval);
	}
	pumping++;

	// immediately return the array of devices
	exports.devices(callback);

	var off = false;

	// listen for any device connects or disconnects
	iosDeviceModule.on("devicesChanged", function (devices) {
		off || callback(null, iosDeviceModule.devices());
	});

	// return the off() function
	return function () {
		if (!off) {
			off = true;
			pumping = Math.max(pumping - 1, 0);
			pumping || clearInterval(interval);
		}
	};
};

/**
 * Installs an iOS app on the specified device.
 *
 * @param {Function} callback(err) - A function to call when the install finishes
 */
exports.installApp = function installApp(udid, appPath, callback) {
	if (process.platform != 'darwin') {
		return callback(new Error('OS "' + process.platform + '" not supported'));
	}

	appPath = path.resolve(appPath);
	if (!fs.existsSync(appPath)) {
		return callback(new Error('Specified .app path does not exist'));
	}
	if (!fs.statSync(appPath).isDirectory() || !fs.existsSync(path.join(appPath, 'PkgInfo'))) {
		return callback(new Error('Specified .app path is not a valid app'));
	}

	loadIosDeviceModule();
	iosDeviceModule.pumpRunLoop();

	try {
		iosDeviceModule.installApp(udid, appPath);
		callback(null);
	} catch (ex) {
		callback(ex);
	}
};<|endoftext|>


<commit_before>'use strict';

module.exports = function () {
	var sinh = Math.sinh;
	if (typeof sinh !== 'function') return false;
	return sinh(1) === 1.1752011936438014;
};
<commit_msg>Fix detection of native sinh<commit_after>'use strict';

module.exports = function () {
	var sinh = Math.sinh;
	if (typeof sinh !== 'function') return false;
	return ((sinh(1) === 1.1752011936438014) && (sinh(Number.MIN_VALUE) === 5e-324));
};
<|endoftext|>


<commit_before>import { formatFileSize, isDefinedGlobally } from './utils';

const messages = {
  after: (field, [target]) => `Pole ${field} musi być po polu ${target}.`,
  alpha_dash: (field) => `Pole ${field} może zawierać litery, cyfry oraz myślnik lub podkreślnik.`,
  alpha_num: (field) => `Pole ${field} może zawierać tylko litery i cyfry.`,
  alpha_spaces: (field) => `Pole ${field} może zawierać tylko litery oraz spacje.`,
  alpha: (field) => `Pole ${field} może zawierać tylko litery.`,
  before: (field, [target]) => `Pole ${field} musi być przed ${target}.`,
  between: (field, [min, max]) => `Pole ${field} must be between ${min} and ${max}.`,
  confirmed: (field, [confirmedField]) => `Pole ${field} nie zgadza się z polem potwierdzającym ${confirmedField}.`,
  date_between: (field, [min, max]) => `Pole ${field} musi zawierać się między ${min} a ${max}.`,
  date_format: (field, [format]) => `Pole ${field} musi pasować do formatu ${format}.`,
  decimal: (field, [decimals = '*'] = []) => `Pole ${field} musi być liczbą i może zawierać ${decimals === '*' ? '' : decimals} miejsca po przecinku.`,
  digits: (field, [length]) => `Pole ${field} musi być liczbą i dokładnie ${length} cyfr.`,
  dimensions: (field, [width, height]) => `Obraz ${field} musi być szeroki na ${width} pikseli i wysoki na ${height} pikseli.`,
  email: (field) => `Pole ${field} musi być poprawnym adresem email.`,
  ext: (field) => `Plik ${field} musi być poprawnym plikiem.`,
  image: (field) => `Pole ${field} musi być obrazem.`,
  in: (field) => `Pole ${field} musi być poprawną wartością.`,
  ip: (field) => `Pole ${field} musi być poprawnym adresem IP.`,
  max: (field, [length]) => `Pole ${field} nie może być dłuższe niż ${length} znaków.`,
  mimes: (field) => `Plik ${field} musi posiadać poprawne rozszerzenie.`,
  min: (field, [length]) => `Pole ${field} musi być długie na co najmniej ${length} znaków.`,
  not_in: (field) => `Pole ${field} musi być poprawną wartością.`,
  numeric: (field) => `Pole ${field} może zawierać tylko cyfry.`,
  regex: (field) => `Format pola ${field} jest nieodpowiedni.`,
  required: (field) => `Pole ${field} jest wymagane.`,
  size: (field, [size]) => `Plik ${field} musi być mniejszy niż ${formatFileSize(size)}.`,
  url: (field) => `Pole ${field} nie jest poprawnym URL.`
};

const locale = {
  name: 'pl',
  messages,
  attributes: {}
};

if (isDefinedGlobally()) {
  VeeValidate.Validator.localize({ [locale.name]: locale });
}

export default locale;
<commit_msg>Update pl.js<commit_after>import { formatFileSize, isDefinedGlobally } from './utils';

const messages = {
  after: (field, [target]) => `Pole ${field} musi być po polu ${target}.`,
  alpha_dash: (field) => `Pole ${field} może zawierać litery, cyfry oraz myślnik lub podkreślnik.`,
  alpha_num: (field) => `Pole ${field} może zawierać tylko litery i cyfry.`,
  alpha_spaces: (field) => `Pole ${field} może zawierać tylko litery oraz spacje.`,
  alpha: (field) => `Pole ${field} może zawierać tylko litery.`,
  before: (field, [target]) => `Pole ${field} musi być przed ${target}.`,
  between: (field, [min, max]) => `Pole ${field} musi być pomiędzy ${min} oraz ${max}.`,
  confirmed: (field, [confirmedField]) => `Pole ${field} nie zgadza się z polem potwierdzającym ${confirmedField}.`,
  date_between: (field, [min, max]) => `Pole ${field} musi zawierać się między ${min} a ${max}.`,
  date_format: (field, [format]) => `Pole ${field} musi pasować do formatu ${format}.`,
  decimal: (field, [decimals = '*'] = []) => `Pole ${field} musi być liczbą i może zawierać ${decimals === '*' ? '' : decimals} miejsca po przecinku.`,
  digits: (field, [length]) => `Pole ${field} musi być liczbą i dokładnie ${length} cyfr.`,
  dimensions: (field, [width, height]) => `Obraz ${field} musi być szeroki na ${width} pikseli i wysoki na ${height} pikseli.`,
  email: (field) => `Pole ${field} musi być poprawnym adresem email.`,
  ext: (field) => `Plik ${field} musi być poprawnym plikiem.`,
  image: (field) => `Pole ${field} musi być obrazem.`,
  in: (field) => `Pole ${field} musi być poprawną wartością.`,
  ip: (field) => `Pole ${field} musi być poprawnym adresem IP.`,
  max: (field, [length]) => `Pole ${field} nie może być dłuższe niż ${length} znaków.`,
  mimes: (field) => `Plik ${field} musi posiadać poprawne rozszerzenie.`,
  min: (field, [length]) => `Pole ${field} musi być długie na co najmniej ${length} znaków.`,
  not_in: (field) => `Pole ${field} musi być poprawną wartością.`,
  numeric: (field) => `Pole ${field} może zawierać tylko cyfry.`,
  regex: (field) => `Format pola ${field} jest nieodpowiedni.`,
  required: (field) => `Pole ${field} jest wymagane.`,
  size: (field, [size]) => `Plik ${field} musi być mniejszy niż ${formatFileSize(size)}.`,
  url: (field) => `Pole ${field} nie jest poprawnym URL.`
};

const locale = {
  name: 'pl',
  messages,
  attributes: {}
};

if (isDefinedGlobally()) {
  VeeValidate.Validator.localize({ [locale.name]: locale });
}

export default locale;
<|endoftext|>


<commit_before>// ==UserScript==
// @name         pr0 filter
// @description  filters by tags
// @namespace    filter
// @version      1.1.0.3
// @author       cRYPTOR
// @match        *://pr0gramm.com/*
// @grant		 none
// ==/UserScript==

$(document).ready(function(){

	var filterSettings = {
		tags: ['wichtel', 'repost'],
		marks: {
			'0':0, // Schwuchtel
			'1':0, // Neuschwuchtel
			'2':0, // Altschwuchtel
			'3':0, // Admin
			'4':0, // Gesperrt
			'5':0, // Moderator
			'6':1, // Fliesentischbesitzer
			'7':0, // Lebende Legende
			'8':0, // pr0wichtler
			'9':0, // Edler Spender
		},
		debug: false,
	};

	var call = function(callback, callbackData){
		if( callback != null){
			return callback(callbackData);
		}
	};

	var debugLog = function(str){
		if( filterSettings.debug){
			console.log(str);
		}
	};

	var promoted = false;
	var getId = function(e){
		return promoted ? e.promoted : e.id;
	}

	var searchObjects = [];
	var searchObjectFactory = {
		createSearchObject : function(content, callback){
			searchObjects.push({
				searchContainers: [],
				searchOptions:{
					'tags':content
				},
				ids: {},
				is: function(id){
					return this.ids[id] != undefined;
				},
				needsUpdate: function(id){
					return !this.containerContains(id);
				},
				containerContains: function(id){
					var toReturn = true;
					$(this.searchContainers).each(function(i,e){
						if( id >= e.min && id <= e.max ){
							return toReturn = false;
						}
					});
					return !toReturn;
				},
				update: function(id, callback, callbackData){

					var o = this;
					o.searchOptions.flags = p.user.flags;
					o.searchOptions.older = id;
					o.searchOptions.promoted = promoted;

					p.api.get('items.get', o.searchOptions, function(data){
						var c = o.searchContainers[o.searchContainers.push({max:id,min:Number.MAX_VALUE})-1];
						if(data.items.length == 0) {
							c.min = -1;
							return call(callback, callbackData);
						}
						$(data.items).each(function(i, e){
							var id = getId(e);
							if( id < c.min){
								c.min = id;
							}
							o.ids[id] = 1;
						});
						return call(callback, callbackData);
					});
				}
			});
			call(callback);
		}
	};

	var updateAll = function(d){
		if( searchObjects.length == 0){
			return call(d.callback);
		}
		var isUp2Date = true;
		$(d.data.items).each(function(iIndex, i){
			if(!isUp2Date){
				return false;
			}
			$(searchObjects).each(function(sOIndex, sO){
				var id = getId(i);
				if( sO.needsUpdate(id)){
					sO.update(id, updateAll, d);
					return isUp2Date = false;
				}
			});
		});

		if( isUp2Date ){
			call(d.callback);
		}
	};

	p.Stream.prototype._load = function(options, callback){

		var stream = this;
		options.flags = p.user.flags;

		p.api.get('items.get', p.merge(options, this.options), function (data){

			promoted = stream.options.promoted;
			if( stream.options.tags != undefined ){
				var position = stream._processResponse(data);
				callback(data.items, position, data.error);
				return;
			}

			updateAll({
				'data' : data,
				'callback' : function(){

					var oldLength = data.items.length;
					data.items = $.grep(data.items, function(el, i){
						return filterSettings.marks[el.mark] == 0;
					});

					if(searchObjects.length > 0){
						data.items = $.grep(data.items, function(el, i){
							var keep = true;
							$(searchObjects).each(function(sOIndex, sO){
								if( sO.is(el.id) ){
									return keep = false;
								}
							});
							return keep;
						});
					}

					var dif = oldLength - data.items.length;
					if( dif > 0 ){
						debugLog('filtered ' + dif + ' items!');
					}

					var position = stream._processResponse(data);
					callback(data.items, position, data.error);
				}
			});
		});
	};

	var softReload = function(){

		var pathName = document.location.pathname;
		if( !(pathName.indexOf('top') > -1
		   || pathName.indexOf('new') > -1
		   || pathName == '/') ){
			return;
		}

		if( p.currentView.loadInProgress ){
			setTimeout(softReload,10);
			return;
		}

		var $currentItem = p.currentView.$currentItem;
		if($currentItem != undefined){
			p.currentView.hideItem();
		}

		var isTop = pathName.indexOf('top') > -1;
		p.currentView.show({tab:isTop ? 'top' : 'new'});

		if($currentItem != undefined){
			$currentItem = $('#' + $currentItem[0].id);
			if($currentItem[0] != undefined){
				p.currentView.showItem($currentItem, 1);
			}
		}
	}

	if(filterSettings.tags.length > 0){
		var count = 0;
		$(filterSettings.tags).each(function(i,t){
			searchObjectFactory.createSearchObject(t, function(){
				++count;
				if( count == searchObjects.length){
					softReload();
				}
			});
		});
	}else{
		softReload();
	}
});<commit_msg>PR0-0006<commit_after>// ==UserScript==
// @name         pr0 filter
// @description  filters by tags
// @namespace    filter
// @version      1.1.0.4
// @author       cRYPTOR
// @match        *://pr0gramm.com/*
// @grant		 none
// ==/UserScript==

$(document).ready(function(){

	var filterSettings = {
		tags: ['wichtel', 'repost'],
		marks: {
			'0':0, // Schwuchtel
			'1':0, // Neuschwuchtel
			'2':0, // Altschwuchtel
			'3':0, // Admin
			'4':0, // Gesperrt
			'5':0, // Moderator
			'6':1, // Fliesentischbesitzer
			'7':0, // Lebende Legende
			'8':0, // pr0wichtler
			'9':0, // Edler Spender
		},
		debug: false,
	};

	var call = function(callback, callbackData){
		if( callback != null){
			return callback(callbackData);
		}
	};

	var debugLog = function(str){
		if( filterSettings.debug){
			console.log(str);
		}
	};

	var promoted = false;
	var getId = function(e){
		return promoted ? e.promoted : e.id;
	}

	var searchObjects = [];
	var searchObjectFactory = {
		createSearchObject : function(content, callback){
			searchObjects.push({
				searchContainers: [],
				searchOptions:{
					'tags':content
				},
				ids: {},
				is: function(id){
					return this.ids[id] != undefined;
				},
				needsUpdate: function(id){
					return !this.containerContains(id);
				},
				containerContains: function(id){
					var toReturn = true;
					$(this.searchContainers).each(function(i,e){
						if( id >= e.min && id <= e.max ){
							return toReturn = false;
						}
					});
					return !toReturn;
				},
				update: function(id, callback, callbackData){

					var o = this;
					o.searchOptions.flags = p.user.flags;
					o.searchOptions.older = id;
					o.searchOptions.promoted = promoted;

					p.api.get('items.get', o.searchOptions, function(data){
						var c = o.searchContainers[o.searchContainers.push({max:id,min:Number.MAX_VALUE})-1];
						if(data.items.length == 0) {
							c.min = -1;
							return call(callback, callbackData);
						}
						$(data.items).each(function(i, e){
							var id = getId(e);
							if( id < c.min){
								c.min = id;
							}
							o.ids[id] = 1;
						});
						return call(callback, callbackData);
					});
				}
			});
			call(callback);
		}
	};

	var updateAll = function(d){
		if( searchObjects.length == 0){
			return call(d.callback);
		}
		var isUp2Date = true;
		$(d.data.items).each(function(iIndex, i){
			if(!isUp2Date){
				return false;
			}
			$(searchObjects).each(function(sOIndex, sO){
				var id = getId(i);
				if( sO.needsUpdate(id)){
					sO.update(id, updateAll, d);
					return isUp2Date = false;
				}
			});
		});

		if( isUp2Date ){
			call(d.callback);
		}
	};

	p.Stream.prototype._load = function(options, callback){

		var stream = this;
		options.flags = p.user.flags;

		p.api.get('items.get', p.merge(options, this.options), function (data){

			promoted = stream.options.promoted;
			if( stream.options.tags != undefined || stream.options.user != undefined ){
				var position = stream._processResponse(data);
				callback(data.items, position, data.error);
				return;
			}

			updateAll({
				'data' : data,
				'callback' : function(){

					var oldLength = data.items.length;
					data.items = $.grep(data.items, function(el, i){
						return filterSettings.marks[el.mark] == 0;
					});

					if(searchObjects.length > 0){
						data.items = $.grep(data.items, function(el, i){
							var keep = true;
							$(searchObjects).each(function(sOIndex, sO){
								if( sO.is(el.id) ){
									return keep = false;
								}
							});
							return keep;
						});
					}

					var dif = oldLength - data.items.length;
					if( dif > 0 ){
						debugLog('filtered ' + dif + ' items!');
					}

					var position = stream._processResponse(data);
					callback(data.items, position, data.error);
				}
			});
		});
	};

	var softReload = function(){

		var pathName = document.location.pathname;
		if( !(pathName.indexOf('top') > -1
		   || pathName.indexOf('new') > -1
		   || pathName == '/') ){
			return;
		}

		if( p.currentView.loadInProgress ){
			setTimeout(softReload,10);
			return;
		}

		var $currentItem = p.currentView.$currentItem;
		if($currentItem != undefined){
			p.currentView.hideItem();
		}

		var isTop = pathName.indexOf('top') > -1;
		p.currentView.show({tab:isTop ? 'top' : 'new'});

		if($currentItem != undefined){
			$currentItem = $('#' + $currentItem[0].id);
			if($currentItem[0] != undefined){
				p.currentView.showItem($currentItem, 1);
			}
		}
	}

	if(filterSettings.tags.length > 0){
		var count = 0;
		$(filterSettings.tags).each(function(i,t){
			searchObjectFactory.createSearchObject(t, function(){
				++count;
				if( count == searchObjects.length){
					softReload();
				}
			});
		});
	}else{
		softReload();
	}
});<|endoftext|>


<commit_before>function initialize_webiopi(){
    // apply style.css after initialize webiopi
    applyCustomCss('styles.css');

    // set touch area
    var touchArea = $("#touchArea")[0];

    // add touch event listener
    touchArea.addEventListener("touchstart", touchEvent, false);
    touchArea.addEventListener("touchmove", touchEvent, false);
    touchArea.addEventListener("touchend", touchEndEvent, false);

    // add click event listener
    touchArea.addEventListener("click", clickEvent, false);

    webiopi().refreshGPIO(false);

    imageSetup();
}

var commandID = 0;

var mCount = 0;
var mCanvas;
var mCtx;
var mImg1;
var mImg2;
var mImgArrow;
var mWidth = 640;
var mHeight = 480;

var viewScale = 0.90;

var URL1, URL2;

var cameraMode = 0; //0:auto 1:preview 2:manual
var photoNumb = 0;

function imageSetup(){
		getData('./photo/camera.set').then(function(data) {
				photoNumb = data;
		});

		var host = location.host;
		var hostname = host.split(":")[0];

		var port_mjpeg = 9000;
		var port_webiopi = 8000;
		URL_MJPEG = 'http://' + hostname + ':' + port_mjpeg + '/?action=snapshot';
		//  URL2 = 'http://' + hostname + ':8000/m2/img/CrawlerControllerTrans.png';
		URL_PREVIEW = 'http://' + hostname + ':' + port_webiopi + '/rpicam/photo/';

		mCanvas = document.getElementById("canvas");
		mCtx = mCanvas.getContext('2d');

		mWidth = viewScale*document.getElementById("touchArea").offsetWidth;
		mHeight= mWidth*3/4;

		mCanvas.width = mWidth;
		mCanvas.height = mHeight;

		mImg1 = new Image();
		mImg2 = new Image();
		mImgPreview = new Image();

		mImg1.src = URL_MJPEG +'&'+(mCount++);

		//  mImgArrow.src = URL2;

		mImg1.onload = function() {
				if(cameraMode == 0 || cameraMode == 2){
						mImg2.src = URL_MJPEG + '&' + (mCount++);
						mCtx.drawImage(mImg1, 0, 0, mWidth, mHeight);
						//					mCtx.drawImage(mImgArrow, 0, 0, mWidth, mHeight);
				}
				if(cameraMode == 1){
						mImg2.src = URL_PREVIEW + getZeroDigit(photoNumb, 6) + ".jpg";
						mCtx.drawImage(mImg1, 0, 0, mWidth, mHeight);
				}
		};

		mImg2.onload = function() {
				if(cameraMode == 0 || cameraMode == 2){
						mImg1.src =URL_MJPEG + '&' + (mCount++);
						mCtx.drawImage(mImg2, 0, 0, mWidth, mHeight);
						//					mCtx.drawImage(mImgArrow, 0, 0, mWidth, mHeight);
				}

				if(cameraMode == 1){
						mImg1.src = URL_PREVIEW + getZeroDigit(photoNumb, 6) + ".jpg";
						mCtx.drawImage(mImg2, 0, 0, mWidth, mHeight);
				}
		};
}

function getData(url) {
  return $.ajax({
    type: 'get',
    url: url
  });
}

// touch event for smartphone
function touchEvent(e){
    e.preventDefault();

    var touch = e.touches[0];
    var width = viewScale*document.getElementById("touchArea").offsetWidth;
    var height = width*3/4;

		if(touch.pageX<width/3){ // left
				if(cameraMode == 1){
						photoNumb--;
				}
		}else if(touch.pageX<2*width/3){ // middle
				if(touch.pageY<height/2){ // upper

				}else{ // lower
						if(cameraMode == 0 || cameraMode == 2){
								ActionShutter();
						}
				}
		}else if(touch.pageX<width){ // right
				if(cameraMode == 1){
						photoNumb++;
				}
		}
}

// touch end event
function touchEndEvent(e){
    e.preventDefault();

}

// click event for PC
function clickEvent(e){
    var width = viewScale*document.getElementById("touchArea").offsetWidth;
    var height = width*3/4;

		if(e.pageX<width/3){ // left
				if(cameraMode == 1){
						photoNumb--;
				}
		}else if(e.pageX<2*width/3){ // middle
				if(e.pageY>=2*height/5 && e.pageY<3*height/5){
				}else if(e.pageY<height/2){
						if(cameraMode == 0 || cameraMode == 2){
								ActionShutter();
						}
				}else{
				}
		}else if(e.pageX<width){ // right
				if(cameraMode == 1){
						photoNumb++;
				}
		}
}

function applyCustomCss(custom_css){
    var head = document.getElementsByTagName('head')[0];
    var style = document.createElement('link');
    style.rel = "stylesheet";
    style.type = 'text/css';
    style.href = custom_css;
    head.appendChild(style);
}

function getZeroDigit(num,digit) {
	var n,m,s;
	if (isNaN(num)) {
		s = num;
	} else {
		s = num.toString();
	}
	m = digit - s.length;
	for (n=0;n<m;n++) {
		s = "0" + s;
	}
	return s;
}

function ChangeMode(){
		cameraMode++;
		if(cameraMode > 2){
				cameraMode = 0;
		}
}

function ActionShutter(){
    webiopi().callMacro("shutterCamera", [0]);

		getData('./photo/camera.set').then(function(data) {
				photoNumb = data;
		});

		setTimeout("imageSetup()", 5000);
}

function ActionShutdown(){
    webiopi().callMacro("shutdownCamera", [0]);
}
<commit_msg>add auto reload<commit_after>function initialize_webiopi(){
    // apply style.css after initialize webiopi
    applyCustomCss('styles.css');

    // set touch area
    var touchArea = $("#touchArea")[0];

    // add touch event listener
    touchArea.addEventListener("touchstart", touchEvent, false);
    touchArea.addEventListener("touchmove", touchEvent, false);
    touchArea.addEventListener("touchend", touchEndEvent, false);

    // add click event listener
    touchArea.addEventListener("click", clickEvent, false);

    webiopi().refreshGPIO(false);

    imageSetup();
}

var commandID = 0;

var mCount = 0;
var mCanvas;
var mCtx;
var mImg1;
var mImg2;
var mImgShutter;
var mImgArrow;

var mWidth = 640;
var mHeight = 480;

var viewScale = 0.90;

var URL1, URL2;

var cameraMode = 0; //0:auto 1:preview 2:manual
var photoNumb = 0;

function imageSetup(){
		getData('./photo/camera.set').then(function(data) {
				photoNumb = data;
		});

		var host = location.host;
		var hostname = host.split(":")[0];

		var port_mjpeg = 9000;
		var port_webiopi = 8000;
		URL_MJPEG = 'http://' + hostname + ':' + port_mjpeg + '/?action=snapshot';
		URL_SHUTTER = 'http://' + hostname + ':' + port_webiopi + '/rpicam/img/shutter.png';
		URL_PREVIEW = 'http://' + hostname + ':' + port_webiopi + '/rpicam/photo/';
		URL_ARROW = 'http://' + hostname + ':' + port_webiopi + '/rpicam/img/arrow.png';

		mCanvas = document.getElementById("canvas");
		mCtx = mCanvas.getContext('2d');

		mWidth = viewScale*document.getElementById("touchArea").offsetWidth;
		mHeight= mWidth*3/4;

		mCanvas.width = mWidth;
		mCanvas.height = mHeight;

		mImg1 = new Image();
		mImg2 = new Image();
		mImgShutter = new Image();
		mImgArrow = new Image();

		mImg1.src = URL_MJPEG +'&'+(mCount++);

		mImgShutter.src = URL_SHUTTER;
		mImgArrow.src = URL_ARROW;

		mImg1.onload = function() {
				if(cameraMode == 0 || cameraMode == 2){
						mImg2.src = URL_MJPEG + '&' + (mCount++);
						mCtx.drawImage(mImg1, 0, 0, mWidth, mHeight);
						mCtx.drawImage(mImgShutter, 0, 0, mWidth, mHeight);
				}
				if(cameraMode == 1){
						mImg2.src = URL_PREVIEW + getZeroDigit(photoNumb, 6) + ".jpg";
						mCtx.drawImage(mImg1, 0, 0, mWidth, mHeight);
						mCtx.drawImage(mImgArrow, 0, 0, mWidth, mHeight);
				}
		};

		mImg2.onload = function() {
				if(cameraMode == 0 || cameraMode == 2){
						mImg1.src =URL_MJPEG + '&' + (mCount++);
						mCtx.drawImage(mImg2, 0, 0, mWidth, mHeight);
						mCtx.drawImage(mImgShutter, 0, 0, mWidth, mHeight);
				}

				if(cameraMode == 1){
						mImg1.src = URL_PREVIEW + getZeroDigit(photoNumb, 6) + ".jpg";
						mCtx.drawImage(mImg2, 0, 0, mWidth, mHeight);
						mCtx.drawImage(mImgArrow, 0, 0, mWidth, mHeight);
				}
		};
}

function getData(url) {
  return $.ajax({
    type: 'get',
    url: url
  });
}

// touch event for smartphone
function touchEvent(e){
    e.preventDefault();

    var touch = e.touches[0];
    var width = viewScale*document.getElementById("touchArea").offsetWidth;
    var height = width*3/4;

		if(touch.pageX<width/3){ // left
				if(cameraMode == 1){
						photoNumb--;
				}
		}else if(touch.pageX<2*width/3){ // middle
				if(touch.pageY<height/2){ // upper

				}else{ // lower
						if(cameraMode == 0 || cameraMode == 2){
								ActionShutter();
						}
				}
		}else if(touch.pageX<width){ // right
				if(cameraMode == 1){
						photoNumb++;
				}
		}
}

// touch end event
function touchEndEvent(e){
    e.preventDefault();

}

// click event for PC
function clickEvent(e){
    var width = viewScale*document.getElementById("touchArea").offsetWidth;
    var height = width*3/4;

		if(e.pageX<width/3){ // left
				if(cameraMode == 1){
						photoNumb--;
				}
		}else if(e.pageX<2*width/3){ // middle
				if(e.pageY>=2*height/5 && e.pageY<3*height/5){
				}else if(e.pageY<height/2){
						if(cameraMode == 0 || cameraMode == 2){
								ActionShutter();
						}
				}else{
				}
		}else if(e.pageX<width){ // right
				if(cameraMode == 1){
						photoNumb++;
				}
		}
}

function applyCustomCss(custom_css){
    var head = document.getElementsByTagName('head')[0];
    var style = document.createElement('link');
    style.rel = "stylesheet";
    style.type = 'text/css';
    style.href = custom_css;
    head.appendChild(style);
}

function getZeroDigit(num,digit) {
	var n,m,s;
	if (isNaN(num)) {
		s = num;
	} else {
		s = num.toString();
	}
	m = digit - s.length;
	for (n=0;n<m;n++) {
		s = "0" + s;
	}
	return s;
}

function ChangeMode(){
		cameraMode++;
		if(cameraMode > 2){
				cameraMode = 0;
		}
}

function ActionShutter(){
    webiopi().callMacro("shutterCamera", [0]);

		getData('./photo/camera.set').then(function(data) {
				photoNumb = data;
		});

		setTimeout("imageSetup()", 5000);
}

function ActionShutdown(){
    webiopi().callMacro("shutdownCamera", [0]);
}
<|endoftext|>


<commit_before>$('.navbar a').on('click', function(event) {
     event.preventDefault();
     var location_anchor = $(this).attr('href');
     if(location_anchor == '#'){
        location_anchor = 'html';
     }
     $('html, body').animate({
      scrollTop: $(location_anchor).offset().top
      }, 1000);
});

$('#footer-menu li a').on('click', function(event) {
     event.preventDefault();
     var location_anchor = $(this).attr('href');
     if(location_anchor == '#'){
        location_anchor = 'html';
     }
     $('html, body').animate({
      scrollTop: $(location_anchor).offset().top
      }, 1000);
});

$('#buscar_caminho').on('click', function(e) {
    e.preventdefault()
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {

        var point = new google.maps.LatLng(position.coords.latitude,
                                    position.coords.longitude);
        calcRoute(point);
        });
    }
});

//map
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var ftec = new google.maps.LatLng(-29.173913, -51.218490);
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
  zoom:15,
  center: ftec,
  streetViewControl: false,
  panControl: true,
  overviewMapControl: true,
  zoomControl: true,
  scaleControl: true
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
var marker = new google.maps.Marker({
              position: ftec,
              map: map,
              title:"FTEC Caxias do Sul"
});

function calcRoute(starte) {
  var start = document.getElementById("search-route").value;
  if(starte != undefined) {
    start = starte;
  }
  var end = ftec;
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
  }
  });
}

autocomplete = new google.maps.places.Autocomplete(
    (document.getElementById('search-route')),
    { types: ['geocode'] });
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
  calcRoute();
});

document.getElementById("search-route").addEventListener("keypress", function(e){
    if (e.keyCode == 13) {
        calcRoute();
        return false;
    }
});

$('body').scrollspy({ target: '#main-navbar' });

$(document).on('click','a.navbar-brand',function(e) {
    if( $(e.target).is('a') ) {
        $('.navbar-collapse.in').collapse('hide');
    }
});
<commit_msg>Add js para fechar collapsed menu apos click no titulo.<commit_after>$('.navbar a').on('click', function(event) {
     event.preventDefault();
     var location_anchor = $(this).attr('href');
     if(location_anchor == '#'){
        location_anchor = 'html';
     }
     $('html, body').animate({
      scrollTop: $(location_anchor).offset().top
      }, 1000);
});

$('#footer-menu li a').on('click', function(event) {
     event.preventDefault();
     var location_anchor = $(this).attr('href');
     if(location_anchor == '#'){
        location_anchor = 'html';
     }
     $('html, body').animate({
      scrollTop: $(location_anchor).offset().top
      }, 1000);
});

$('#buscar_caminho').on('click', function(e) {
    e.preventdefault()
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {

        var point = new google.maps.LatLng(position.coords.latitude,
                                    position.coords.longitude);
        calcRoute(point);
        });
    }
});

//map
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var ftec = new google.maps.LatLng(-29.173913, -51.218490);
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
  zoom:15,
  center: ftec,
  streetViewControl: false,
  panControl: true,
  overviewMapControl: true,
  zoomControl: true,
  scaleControl: true
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
var marker = new google.maps.Marker({
              position: ftec,
              map: map,
              title:"FTEC Caxias do Sul"
});

function calcRoute(starte) {
  var start = document.getElementById("search-route").value;
  if(starte != undefined) {
    start = starte;
  }
  var end = ftec;
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
  }
  });
}

autocomplete = new google.maps.places.Autocomplete(
    (document.getElementById('search-route')),
    { types: ['geocode'] });
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
  calcRoute();
});

document.getElementById("search-route").addEventListener("keypress", function(e){
    if (e.keyCode == 13) {
        calcRoute();
        return false;
    }
});

$('body').scrollspy({ target: '#main-navbar' });

$(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a') ) {
        $(this).collapse('hide');
    }
});

$(document).on('click','a.navbar-brand',function(e) {
    if( $(e.target).is('a') ) {
        $('.navbar-collapse.in').collapse('hide');
    }
});
<|endoftext|>


<commit_before>'use strict'

// This Library Helps consolidate the System Information collection into a simple collection

//Key Library Imports
var os = require('os')
var v8 = require('v8')

//Pull all System info into single JSON
//May look at splitting these later to improve performance
var nodeInfoInventory = {
    "os": {
        "EOL": os.EOL,
        "arch": os.arch(),
        "numCPUs": os.cpus().length,
        "cpus": os.cpus(),
        "endianness": os.endianness(),
        "freemem": os.freemem(),
        "homedir": os.homedir(),
        "hostname": os.hostname(),
        "load avg": os.loadavg(),
        "network interfaces": os.networkInterfaces(),
        "platform": os.platform(),
        "release": os.release(),
        "tmp dir": os.tmpdir(),
        "total memory": os.totalmem(),
        "type": os.type(),
        "uptime": (os.uptime() / 60 / 60) + " Hours "
    },

    "v8": {
        "Heap Statistics": v8.getHeapStatistics()
    },

    "globals": {
        "__dirname": __dirname,
        "__filename": __filename,
    },

    "module": {
        "filename": module.filename,
        "id": module.id,
        "loaded": module.loaded,
        "parent": module.parent
    },

    "process": {
        "arch": process.arch,
        "cwd": process.cwd(),
        "argv": process.argv.toString(),
        "execArgv": process.execArgv.toString(),
        "config": process.config,
        "env": process.env,
        "memory Usage": process.memoryUsage(),
        "pid": process.pid,
        "platform": process.platform,
        "release": process.release,
        "title": process.title,
        "uptime": process.uptime(),
        "versions": process.versions
    }
}

/*This Function will send the Full consolidated Information in JSON Format*/
function getNodeInfo() {
	return JSON.stringify(nodeInfoInventory)
}
module.exports.getNodeInfo = exports.getNodeInfo = getNodeInfo;
<commit_msg>filtered module.parent<commit_after>'use strict'

// This Library Helps consolidate the System Information collection into a simple collection

//Key Library Imports
var os = require('os')
var v8 = require('v8')

//Pull all System info into single JSON
//May look at splitting these later to improve performance
var nodeInfoInventory = {
    "os": {
        "EOL": os.EOL,
        "arch": os.arch(),
        "numCPUs": os.cpus().length,
        "cpus": os.cpus(),
        "endianness": os.endianness(),
        "freemem": os.freemem(),
        "homedir": os.homedir(),
        "hostname": os.hostname(),
        "load avg": os.loadavg(),
        "network interfaces": os.networkInterfaces(),
        "platform": os.platform(),
        "release": os.release(),
        "tmp dir": os.tmpdir(),
        "total memory": os.totalmem(),
        "type": os.type(),
        "uptime": (os.uptime() / 60 / 60) + " Hours "
    },

    "v8": {
        "Heap Statistics": v8.getHeapStatistics()
    },

    "globals": {
        "__dirname": __dirname,
        "__filename": __filename,
    },

    "module": {
        "filename": module.filename,
        "id": module.id,
        "loaded": module.loaded//,
        //"parent": module.parent
    },

    "process": {
        "arch": process.arch,
        "cwd": process.cwd(),
        "argv": process.argv.toString(),
        "execArgv": process.execArgv.toString(),
        "config": process.config,
        "env": process.env,
        "memory Usage": process.memoryUsage(),
        "pid": process.pid,
        "platform": process.platform,
        "release": process.release,
        "title": process.title,
        "uptime": process.uptime(),
        "versions": process.versions
    }
}

/*This Function will send the Full consolidated Information in JSON Format*/
function getNodeInfo() {
	return JSON.stringify(nodeInfoInventory)
}
module.exports.getNodeInfo = exports.getNodeInfo = getNodeInfo;
<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    for(var vertex in vertices){
        canvas_draw_path({
          'style': 'stroke',
          'vertices': [
            {
              'type': 'moveTo',
              'x': vertices[vertex]['dx'],
              'y': vertices[vertex]['dy'],
            },
            {
              'x': vertices[vertex]['dx'],
              'y': vertices[vertices[vertex]['parent']]['dy'],
            },
          ],
        });
        canvas_draw_path({
          'style': 'stroke',
          'vertices': [
            {
              'type': 'moveTo',
              'x': vertices[vertex]['dx'],
              'y': vertices[vertices[vertex]['parent']]['dy'],
            },
            {
              'x': vertices[vertices[vertex]['parent']]['dx'],
              'y': vertices[vertices[vertex]['parent']]['dy'],
            },
          ],
        });
    }

    // Draw vertices_amount and lineWidth.
    canvas_buffer.fillText(
      vertices_amount,
      0,
      25
    );
    canvas_buffer.fillText(
      canvas_buffer.lineWidth,
      0,
      50
    );
}

function logic(){
    for(var vertex in vertices){
        vertices[vertex]['loop'] = math_clamp({
          'max': 360,
          'min': 0,
          'value': vertices[vertex]['loop'] + vertices[vertex]['speed'],
          'wrap': true,
        });

        var rotation = vertices[vertex]['loop'] * math_degree;

        vertices[vertex]['dx'] =
          canvas_x
          + vertices[vertex]['x']
          + vertices[vertex]['radius']
          * Math.cos(rotation);
        vertices[vertex]['dy'] =
          canvas_y
          + vertices[vertex]['y']
          + vertices[vertex]['radius']
          * Math.sin(rotation);
    }
}

function randomize(){
    vertices.length = 0;

    var loop_counter = vertices_amount - 1;
    do{
        vertices.push({
          'dx': 0,
          'dy': 0,
          'loop': core_random_integer({
            'max': 360,
          }),
          'parent': vertices_amount - loop_counter,
          'radius': Math.random() * properties['radius'] + 5,
          'speed': core_random_integer({
            'max': properties['speed'],
          }) - properties['speed'] / 2,
          'x': core_random_integer({
            'max': properties['x'],
          }) - properties['x'] / 2,
          'y': core_random_integer({
            'max': properties['y'],
          }) - properties['y'] / 2,
        });
    }while(loop_counter--);

    vertices[vertices_amount - 1]['parent'] = 0;
}

function repo_init(){
    core_events_bind({
      'keybinds': {
        65: {
          'solo': true,
          'todo': function(){
              canvas_buffer.lineWidth = Math.max(
                canvas_buffer.lineWidth - 1,
                1
              );
          },
        },
        68: {
          'solo': true,
          'todo': function(){
              canvas_buffer.lineWidth += 1;
          },
        },
        83: {
          'todo': function(){
              vertices_amount = Math.max(
                vertices_amount - 1,
                2
              );
              randomize();
          },
        },
        87: {
          'todo': function(){
              vertices_amount += 1;
              randomize();
          },
        },
        'all': {
          'todo': randomize,
        },
      },
      'mousebinds': {
        'mousedown': {
          'todo': randomize,
        },
      },
    });
    canvas_init();
}

function resize_logic(){
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.lineJoin = 'round';
    canvas_buffer.strokeStyle = '#fff';

    randomize();
}

var properties = {
  'radius': 20,
  'speed': 15,
  'x': 500,
  'y': 500,
};
var vertices = [];
var vertices_amount = 23;
<commit_msg>added core_repo_init() usage<commit_after>'use strict';

function draw_logic(){
    for(var vertex in vertices){
        canvas_draw_path({
          'style': 'stroke',
          'vertices': [
            {
              'type': 'moveTo',
              'x': vertices[vertex]['dx'],
              'y': vertices[vertex]['dy'],
            },
            {
              'x': vertices[vertex]['dx'],
              'y': vertices[vertices[vertex]['parent']]['dy'],
            },
          ],
        });
        canvas_draw_path({
          'style': 'stroke',
          'vertices': [
            {
              'type': 'moveTo',
              'x': vertices[vertex]['dx'],
              'y': vertices[vertices[vertex]['parent']]['dy'],
            },
            {
              'x': vertices[vertices[vertex]['parent']]['dx'],
              'y': vertices[vertices[vertex]['parent']]['dy'],
            },
          ],
        });
    }

    // Draw vertices_amount and lineWidth.
    canvas_buffer.fillText(
      vertices_amount,
      0,
      25
    );
    canvas_buffer.fillText(
      canvas_buffer.lineWidth,
      0,
      50
    );
}

function logic(){
    for(var vertex in vertices){
        vertices[vertex]['loop'] = math_clamp({
          'max': 360,
          'min': 0,
          'value': vertices[vertex]['loop'] + vertices[vertex]['speed'],
          'wrap': true,
        });

        var rotation = vertices[vertex]['loop'] * math_degree;

        vertices[vertex]['dx'] =
          canvas_x
          + vertices[vertex]['x']
          + vertices[vertex]['radius']
          * Math.cos(rotation);
        vertices[vertex]['dy'] =
          canvas_y
          + vertices[vertex]['y']
          + vertices[vertex]['radius']
          * Math.sin(rotation);
    }
}

function randomize(){
    vertices.length = 0;

    var loop_counter = vertices_amount - 1;
    do{
        vertices.push({
          'dx': 0,
          'dy': 0,
          'loop': core_random_integer({
            'max': 360,
          }),
          'parent': vertices_amount - loop_counter,
          'radius': Math.random() * properties['radius'] + 5,
          'speed': core_random_integer({
            'max': properties['speed'],
          }) - properties['speed'] / 2,
          'x': core_random_integer({
            'max': properties['x'],
          }) - properties['x'] / 2,
          'y': core_random_integer({
            'max': properties['y'],
          }) - properties['y'] / 2,
        });
    }while(loop_counter--);

    vertices[vertices_amount - 1]['parent'] = 0;
}

function repo_init(){
    core_repo_init({
      'title': '9YG0E6r.htm',
    });
    core_events_bind({
      'keybinds': {
        65: {
          'solo': true,
          'todo': function(){
              canvas_buffer.lineWidth = Math.max(
                canvas_buffer.lineWidth - 1,
                1
              );
          },
        },
        68: {
          'solo': true,
          'todo': function(){
              canvas_buffer.lineWidth += 1;
          },
        },
        83: {
          'todo': function(){
              vertices_amount = Math.max(
                vertices_amount - 1,
                2
              );
              randomize();
          },
        },
        87: {
          'todo': function(){
              vertices_amount += 1;
              randomize();
          },
        },
        'all': {
          'todo': randomize,
        },
      },
      'mousebinds': {
        'mousedown': {
          'todo': randomize,
        },
      },
    });
    canvas_init();
}

function resize_logic(){
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.lineJoin = 'round';
    canvas_buffer.strokeStyle = '#fff';

    randomize();
}

var properties = {
  'radius': 20,
  'speed': 15,
  'x': 500,
  'y': 500,
};
var vertices = [];
var vertices_amount = 23;
<|endoftext|>