<commit_before>'use strict'

class PromiseReadable {
  constructor (stream) {
    this.stream = stream

    this._errorHandler = (err) => {
      this._errored = err
    }

    stream.on('error', this._errorHandler)
  }

  read (size) {
    const stream = this.stream

    return new Promise((resolve, reject) => {
      if (this._errored) {
        const err = this._errored
        delete this._errored
        return reject(err)
      }

      if (!stream.readable || stream.closed || stream.destroyed) {
        return resolve()
      }

      const readableHandler = () => {
        let chunk = stream.read(size)

        if (chunk != null) {
          removeListeners()
          resolve(chunk)
        }
      }

      const closeHandler = () => {
        removeListeners()
        resolve(stream.bytesWritten || 0)
      }

      const endHandler = () => {
        removeListeners()
        resolve()
      }

      const errorHandler = (err) => {
        delete this._errored
        removeListeners()
        reject(err)
      }

      const removeListeners = () => {
        stream.removeListener('close', closeHandler)
        stream.removeListener('error', errorHandler)
        stream.removeListener('end', endHandler)
        stream.removeListener('readable', readableHandler)
      }

      stream.on('close', closeHandler)
      stream.on('end', endHandler)
      stream.on('error', errorHandler)
      stream.on('readable', readableHandler)

      readableHandler()
    })
  }

  readAll () {
    const stream = this.stream
    const bufferArray = []

    return new Promise((resolve, reject) => {
      if (this._errored) {
        const err = this._errored
        delete this._errored
        return reject(err)
      }

      if (!stream.readable || stream.closed || stream.destroyed) {
        return resolve()
      }

      const dataHandler = (chunk) => {
        bufferArray.push(chunk)
      }

      const closeHandler = () => {
        removeListeners()
        resolve(stream.bytesWritten || 0)
      }

      const endHandler = () => {
        removeListeners()
        resolve(Buffer.concat(bufferArray))
      }

      const errorHandler = (err) => {
        delete this._errored
        removeListeners()
        reject(err)
      }

      const removeListeners = () => {
        stream.removeListener('close', closeHandler)
        stream.removeListener('data', dataHandler)
        stream.removeListener('error', errorHandler)
        stream.removeListener('end', endHandler)
      }

      stream.on('close', closeHandler)
      stream.on('data', dataHandler)
      stream.on('end', endHandler)
      stream.on('error', errorHandler)

      stream.resume()
    })
  }

  once (event) {
    const stream = this.stream

    return new Promise((resolve, reject) => {
      if (this._errored) {
        const err = this._errored
        delete this._errored
        return reject(err)
      }

      if (stream.closed) {
        if (event === 'close') {
          return resolve()
        } else {
          return reject(new Error(`once ${event} after close`))
        }
      } else if (stream.destroyed) {
        if (event === 'close' || event === 'end') {
          return resolve()
        } else {
          return reject(new Error(`once ${event} after destroy`))
        }
      }

      const closeHandler = () => {
        removeListeners()
        resolve()
      }

      const eventHandler = event !== 'close' && event !== 'end' && event !== 'error' ? (argument) => {
        removeListeners()
        resolve(argument)
      } : undefined

      const endHandler = event !== 'close' ? () => {
        removeListeners()
        resolve()
      } : undefined

      const errorHandler = (err) => {
        delete this._errored
        removeListeners()
        reject(err)
      }

      const removeListeners = () => {
        if (eventHandler) {
          stream.removeListener(event, eventHandler)
        }
        stream.removeListener('error', errorHandler)
        if (endHandler) {
          stream.removeListener('end', endHandler)
        }
        stream.removeListener('error', errorHandler)
      }

      if (eventHandler) {
        stream.on(event, eventHandler)
      }
      stream.on('close', closeHandler)
      if (endHandler) {
        stream.on('end', endHandler)
      }
      stream.on('error', errorHandler)
    })
  }

  destroy () {
    this.stream.removeListener('error', this._errorHandler)
    if (typeof this.stream.destroy === 'function') {
      this.stream.destroy()
    }
    delete this.stream
  }
}

PromiseReadable.PromiseReadable = PromiseReadable
PromiseReadable.default = PromiseReadable

module.exports = PromiseReadable
<commit_msg>delete this._errorHandler on destroy<commit_after>'use strict'

class PromiseReadable {
  constructor (stream) {
    this.stream = stream

    this._errorHandler = (err) => {
      this._errored = err
    }

    stream.on('error', this._errorHandler)
  }

  read (size) {
    const stream = this.stream

    return new Promise((resolve, reject) => {
      if (this._errored) {
        const err = this._errored
        delete this._errored
        return reject(err)
      }

      if (!stream.readable || stream.closed || stream.destroyed) {
        return resolve()
      }

      const readableHandler = () => {
        let chunk = stream.read(size)

        if (chunk != null) {
          removeListeners()
          resolve(chunk)
        }
      }

      const closeHandler = () => {
        removeListeners()
        resolve(stream.bytesWritten || 0)
      }

      const endHandler = () => {
        removeListeners()
        resolve()
      }

      const errorHandler = (err) => {
        delete this._errored
        removeListeners()
        reject(err)
      }

      const removeListeners = () => {
        stream.removeListener('close', closeHandler)
        stream.removeListener('error', errorHandler)
        stream.removeListener('end', endHandler)
        stream.removeListener('readable', readableHandler)
      }

      stream.on('close', closeHandler)
      stream.on('end', endHandler)
      stream.on('error', errorHandler)
      stream.on('readable', readableHandler)

      readableHandler()
    })
  }

  readAll () {
    const stream = this.stream
    const bufferArray = []

    return new Promise((resolve, reject) => {
      if (this._errored) {
        const err = this._errored
        delete this._errored
        return reject(err)
      }

      if (!stream.readable || stream.closed || stream.destroyed) {
        return resolve()
      }

      const dataHandler = (chunk) => {
        bufferArray.push(chunk)
      }

      const closeHandler = () => {
        removeListeners()
        resolve(stream.bytesWritten || 0)
      }

      const endHandler = () => {
        removeListeners()
        resolve(Buffer.concat(bufferArray))
      }

      const errorHandler = (err) => {
        delete this._errored
        removeListeners()
        reject(err)
      }

      const removeListeners = () => {
        stream.removeListener('close', closeHandler)
        stream.removeListener('data', dataHandler)
        stream.removeListener('error', errorHandler)
        stream.removeListener('end', endHandler)
      }

      stream.on('close', closeHandler)
      stream.on('data', dataHandler)
      stream.on('end', endHandler)
      stream.on('error', errorHandler)

      stream.resume()
    })
  }

  once (event) {
    const stream = this.stream

    return new Promise((resolve, reject) => {
      if (this._errored) {
        const err = this._errored
        delete this._errored
        return reject(err)
      }

      if (stream.closed) {
        if (event === 'close') {
          return resolve()
        } else {
          return reject(new Error(`once ${event} after close`))
        }
      } else if (stream.destroyed) {
        if (event === 'close' || event === 'end') {
          return resolve()
        } else {
          return reject(new Error(`once ${event} after destroy`))
        }
      }

      const closeHandler = () => {
        removeListeners()
        resolve()
      }

      const eventHandler = event !== 'close' && event !== 'end' && event !== 'error' ? (argument) => {
        removeListeners()
        resolve(argument)
      } : undefined

      const endHandler = event !== 'close' ? () => {
        removeListeners()
        resolve()
      } : undefined

      const errorHandler = (err) => {
        delete this._errored
        removeListeners()
        reject(err)
      }

      const removeListeners = () => {
        if (eventHandler) {
          stream.removeListener(event, eventHandler)
        }
        stream.removeListener('error', errorHandler)
        if (endHandler) {
          stream.removeListener('end', endHandler)
        }
        stream.removeListener('error', errorHandler)
      }

      if (eventHandler) {
        stream.on(event, eventHandler)
      }
      stream.on('close', closeHandler)
      if (endHandler) {
        stream.on('end', endHandler)
      }
      stream.on('error', errorHandler)
    })
  }

  destroy () {
    this.stream.removeListener('error', this._errorHandler)
    delete this._errorHandler
    if (typeof this.stream.destroy === 'function') {
      this.stream.destroy()
    }
    delete this.stream
  }
}

PromiseReadable.PromiseReadable = PromiseReadable
PromiseReadable.default = PromiseReadable

module.exports = PromiseReadable
<|endoftext|>


<commit_before>var app = angular.module('nbaRoutes');

app.service('teamService', function($http, $q){

});<commit_msg>finished step 2 on README.txt<commit_after>var app = angular.module('nbaRoutes');

app.service('teamService', function($http, $q){

	this.addNewGame = function(gameObj){
		var url = "https://api.parse.com/1/classes/" + gameObj.homeTeam;
		parseInt(gameObj.homeTeamScore);
		parseInt(gameObj.opponentScore);
		if(gameObj.homeTeamScore > gameObj.opponentScore){
			gameObj.won = true;
		} else {
			gameObj.won = false;
		}
		return $http({
			method: 'POST',
			url: url,
			data: gameObj
		});
	};

	this.getTeamData = function(team){
		var dfd = $q.defer();
		var url = 'https://api.parse.com/1/classes/' + team;
		$http({
			method: 'GET',
			url: url
		}).then(function(data){
			var results = data.data.results;
			var wins = 0;
			var losses = 0;
			for (var i = 0; i < results.length; i++){
				if(results.won[i] === true){
					wins++;
				} else {
					losses++;
				}
			}
			results.push(wins);
			results.push(losses);
			dfd.resolve(results);
		})
		return dfd.promise;
	}

});<|endoftext|>


<commit_before>#!/usr/bin/env node

var fontelloSvg = require('../');
var _ = require('underscore');
var path = require('path');
var app = require('commander');
var colors = require('colors');

function l(msg, indent, nlBefore, nlAfter) {
  if (!indent) indent = 0;
  if (Array.isArray(msg)) msg = msg.join('\n');
  while (indent--) msg = ' ' + msg;
  if (nlBefore) msg = '\n' + msg;
  if (nlAfter) msg = msg + '\n';
  process.stdout.write(msg + '\n');
}

// Get an object from a string like this: "key : value | key: value"
function argsObject(val) {
  return _.object(val.split('|').map(function(pair) {
    return pair.split(':').map(function(v) {
      return v.trim();
    });
  }));
}

colors.setTheme({
  info: 'green',
  data: 'grey',
  error: 'red'
});

app.version('0.0.1');
app.usage('--config <config file> --out <dir> [options]');
app.option('-c, --config <config file>', 'Set the Fontello configuration file (required)');
app.option('-o, --out <dir>', 'Set the export directory (required)');
app.option('-f, --fill-colors <colors>', 'Transform the SVG paths to the specified colors. Syntax: --fill-colors "black:rgb(0,0,0) | red:rgb(255,0,0)"', argsObject);
app.option('-p, --css-path <path>', 'Set a CSS path for SVG backgrounds.');
app.option('--no-skip', 'Do not skip existing files');
app.option('--verbose', 'Verbose output');
app.parse(process.argv);

// Required parameters
if (!app.config || !app.out) {
  l([
    '',
    '  Error: missing required parameters (--config, --out)'.error,
    ''
  ]);
  app.help();
}

// Start
var config = require(path.resolve(app.config));
var out = path.resolve(app.out);
var colors = app.fillColors || {'black': '#000000'};

start(config.glyphs, out, colors, app);

function start(rawGlyphs, out, colors, app) {
  var glyphs = fontelloSvg.allGlyphs(rawGlyphs, colors);

  if (app.skip) {
    fontelloSvg.missingGlyphs(glyphs, out, processGlyphs);
  } else {
    processGlyphs(glyphs);
  }

  function processGlyphs(glyphsToDl) {
    var glyphsSkipped = glyphs.filter(function(glyph) {
      return glyphsToDl.indexOf(glyph) === -1;
    });
    var downloader = fontelloSvg.downloadSvgs(glyphsToDl, out);

    // Output skipped glyphs
    if (app.skip && app.verbose) {
      glyphsSkipped.forEach(function(glyph) {
        l('[skipped]'.data + ' Existing SVG: ' + glyph.name + '-' + glyph.collection, 2);
      });
    }

    downloader.on('fetch-error', function(httpStream, writeStream) {
      l('[error]'.error + ' Download failed: ' + httpStream.href, 2);
    });
    downloader.on('svg-write', function(writeStream) {
      l('[saved]'.info + ' SVG file written: ' + writeStream.path, 2);
    });

    fontelloSvg.writeCss(glyphs, out + '/index.css', function() {
      l('[saved]'.info + (' ' + out + '/index.css').data, 2);
    });
  }
}
<commit_msg>Messages style<commit_after>#!/usr/bin/env node

var fontelloSvg = require('../');
var _ = require('underscore');
var path = require('path');
var app = require('commander');
var colors = require('colors');

function l(msg, indent, nlBefore, nlAfter) {
  if (!indent) indent = 0;
  if (Array.isArray(msg)) msg = msg.join('\n');
  while (indent--) msg = ' ' + msg;
  if (nlBefore) msg = '\n' + msg;
  if (nlAfter) msg = msg + '\n';
  process.stdout.write(msg + '\n');
}

// Get an object from a string like this: "key : value | key: value"
function argsObject(val) {
  return _.object(val.split('|').map(function(pair) {
    return pair.split(':').map(function(v) {
      return v.trim();
    });
  }));
}

colors.setTheme({
  info: 'green',
  data: 'grey',
  error: 'red'
});

app.version('0.0.1');
app.usage('--config <config file> --out <dir> [options]');
app.option('-c, --config <config file>', 'Set the Fontello configuration file (required)');
app.option('-o, --out <dir>', 'Set the export directory (required)');
app.option('-f, --fill-colors <colors>', 'Transform the SVG paths to the specified colors. Syntax: --fill-colors "black:rgb(0,0,0) | red:rgb(255,0,0)"', argsObject);
app.option('-p, --css-path <path>', 'Set a CSS path for SVG backgrounds.');
app.option('--no-skip', 'Do not skip existing files');
app.option('--verbose', 'Verbose output');
app.parse(process.argv);

// Required parameters
if (!app.config || !app.out) {
  l([
    '',
    '  Error: missing required parameters (--config, --out)'.error,
    ''
  ]);
  app.help();
}

// Start
var config = require(path.resolve(app.config));
var out = path.resolve(app.out);
var colors = app.fillColors || {'black': '#000000'};

start(config.glyphs, out, colors, app);

function start(rawGlyphs, out, colors, app) {
  var glyphs = fontelloSvg.allGlyphs(rawGlyphs, colors);

  if (app.skip) {
    fontelloSvg.missingGlyphs(glyphs, out, processGlyphs);
  } else {
    processGlyphs(glyphs);
  }

  function processGlyphs(glyphsToDl) {
    var glyphsSkipped = glyphs.filter(function(glyph) {
      return glyphsToDl.indexOf(glyph) === -1;
    });
    var downloader = fontelloSvg.downloadSvgs(glyphsToDl, out);

    // Output skipped glyphs
    if (app.skip && app.verbose) {
      glyphsSkipped.forEach(function(glyph) {
        l('[skipped]'.data + ' existing SVG: ' + glyph.name + '-' + glyph.collection, 2);
      });
    }

    downloader.on('fetch-error', function(httpStream, writeStream) {
      l('[error]'.error + ' download failed: ' + httpStream.href, 2);
    });
    downloader.on('svg-write', function(writeStream) {
      l('[saved]'.info + ' SVG file written: ' + writeStream.path, 2);
    });

    fontelloSvg.writeCss(glyphs, out + '/index.css', function() {
      l('[saved]'.info + (' ' + out + '/index.css').data, 2);
    });
  }
}
<|endoftext|>


<commit_before>tinyMCE.addI18n({sl:{common:{more_colors:"Ve\u010d barv",invalid_data:"Napaka: vne\u0161ene so bile nepravilne vrednosti, ozna\u010dene so z rde\u010do.",popup_blocked:"\u017dal va\u0161e orodje za prepre\u010devanje odpiranja neza\u017eelenih oken (popup-blocker) ne omogo\u010da prikaza pomo\u017enega okna izbranega orodja. Prepre\u010devanje odpiranja oken morate onemogo\u010diti.",clipboard_no_support:"Trenutno ni podporto v va\u0161em brskalniku. Uporabite bli\u017enjice tipkovnice.",clipboard_msg:"Delo z odlo\u017ei\u0161\u010dem ni mogo\u010de v tem brskalniku. Lahko uporabljate kombinacije tipk Ctrl+X, Ctrl+C, Ctrl+V.\n\u017delite ve\u010d informacij o tem?",not_set:"-- ni nastavljeno --",class_name:"Razred",browse:"Prebrskaj",close:"Zapri",cancel:"Prekli\u010di",update:"Posodobi",insert:"Vstavi",apply:"Uporabi",edit_confirm:"\u017delite uporabiti na\u010din \\'videz ne vara\\' (WYSIWYG) za to vnosno polje?",invalid_data_number:"{#field} mora biti veljavno \u0161tevilo",invalid_data_min:"{#field} mora biti ve\u010dje od {#min}",invalid_data_size:"{#field} mora biti \u0161tevilo ali odstotek",value:"(vrednost)"},contextmenu:{full:"Polno",right:"Desno",center:"Sredina",left:"Levo",align:"Poravnava"},insertdatetime:{day_short:"ned,pon,tor,sre,\u010det,pet,sob,ned",day_long:"nedelja,ponedeljek,torek,sreda,\u010detrtek,petek,sobota,nedelja",months_short:"jan,feb,mar,apr,maj,jun,jul,avg,sep,okt,nov,dec",months_long:"januar,februar,marec,april,maj,junij,julij,avgust,september,oktober,november,december",inserttime_desc:"Vstavi \u010das",insertdate_desc:"Vstavi datum",time_fmt:"%H:%M:%S",date_fmt:"%d.%m.%Y"},print:{print_desc:"Natisni"},preview:{preview_desc:"Predogled"},directionality:{rtl_desc:"Smer od desne proti levi",ltr_desc:"Smer od leve proti desni"},layer:{content:"Nov sloj...",absolute_desc:"Preklop absolutnega polo\u017eaja",backward_desc:"Premakni v ozadje",forward_desc:"Premakni v ospredje",insertlayer_desc:"Vstavi nov sloj"},save:{save_desc:"Shrani",cancel_desc:"Prekli\u010di vse spremembe"},nonbreaking:{nonbreaking_desc:"Vstavi nedeljivi presledek"},iespell:{download:"ieSpell ni zaznan. \u017delite, da ga namestim?",iespell_desc:"Za\u017eeni preverjanje \u010drkovanja"},advhr:{delta_height:"spremeba_vi\u0161ine",delta_width:"sprememba_\u0161irine",advhr_desc:"Vodoravna \u010drta"},emotions:{delta_height:"delta_vi\u0161ina",delta_width:"delta_\u0161irina",emotions_desc:"Sme\u0161ki"},searchreplace:{replace_desc:"Najdi/zamenjaj",search_desc:"Najdi",delta_width:"",delta_height:""},advimage:{image_desc:"Vstavi/uredi sliko",delta_width:"",delta_height:""},advlink:{link_desc:"Vstavi/uredi povezavo",delta_height:"",delta_width:""},xhtmlxtras:{attribs_desc:"Vstavi/uredi atribute",ins_desc:"Vstavljeno",del_desc:"Izbrisano",acronym_desc:"Kratica",abbr_desc:"Okraj\u0161ava",cite_desc:"Citat",attribs_delta_height:"",attribs_delta_width:"",ins_delta_height:"",ins_delta_width:"",del_delta_height:"",del_delta_width:"",acronym_delta_height:"",acronym_delta_width:"",abbr_delta_height:"",abbr_delta_width:"",cite_delta_height:"",cite_delta_width:""},style:{desc:"Uredi sloge CSS",delta_height:"",delta_width:""},paste:{plaintext_mode:'Operacija prilepi je sedaj v na\u010dinu "golo besedilo". \u010ce jo \u017eelite vrniti v obi\u010dajen na\u010din, kliknite \u0161e enkrat.',plaintext_mode_sticky:'Operacija prilepi je sedaj v na\u010dinu "golo besedilo". \u010ce jo \u017eelite vrniti v obi\u010dajen na\u010din, kliknite \u0161e enkrat. Po izvedbi lepljenja se bo nastavitev povrnila v obi\u010dajen na\u010din.',selectall_desc:"Izberi vse",paste_word_desc:"Prilepi iz Word-a",paste_text_desc:"Prilepi kot golo besedilo"},paste_dlg:{word_title:"Uporabite kombinacijo tipk CTRL+V, da prilepite vsebino v okno.",text_linebreaks:"Obdr\u017ei prelome vrstic",text_title:"Uporabite kombinacijo tipk CTRL+V, da prilepite vsebino v okno."},table:{cellprops_delta_width:"100",cell:"Celica",col:"Stolpec",row:"Vrstica",del:"Odstrani tabelo",copy_row_desc:"Kopiraj vrstico",cut_row_desc:"Izre\u017ei vrstico",paste_row_after_desc:"Prilepi vrstico po",paste_row_before_desc:"Prilepi vrstico pred",props_desc:"Lastnosti tabele",cell_desc:"Lastnosti celice",row_desc:"Lastnosti vrstice",merge_cells_desc:"Spoji celice",split_cells_desc:"Razcepi celico",delete_col_desc:"Odstrani stolpec",col_after_desc:"Vstavi stolpec po",col_before_desc:"Vstavi stolpec pred",delete_row_desc:"Odstrani vrstico",row_after_desc:"Vstavi vrstico pod",row_before_desc:"Vstavi vrstico nad",desc:"Vstavi/posodobi tabelo",merge_cells_delta_height:"",merge_cells_delta_width:"",table_delta_height:"",table_delta_width:"",cellprops_delta_height:"",rowprops_delta_height:"",rowprops_delta_width:""},autosave:{warning_message:"\u010ce povrnete shranjeno vsebino, boste prepisali trenutno vsebino urejevalnika.nnSte prepri\u010dani, da \u017eelite nadaljevati?",restore_content:"Povrni na zadnje shranjeno vsebino.",unload_msg:"\u010ce nadaljujete, bodo spremembe izgubljene."},fullscreen:{desc:"Preklopi celozaslonski na\u010din"},media:{delta_height:"",delta_width:"",edit:"Uredi multimedijsko vsebino",desc:"Vstavi / uredi multimedijsko vsebino"},fullpage:{desc:"Lastnosti dokumenta",delta_width:"sprememba_\u0161irine",delta_height:"sprememba_vi\u0161ine"},template:{desc:"Vstavi pripravljeno vsebino predloge"},visualchars:{desc:"Preklopi prikaz nadzornih znakov."},spellchecker:{desc:"Preklopi \u010drkovalnik",menu:"Nastavitve \u010drkovalnika",ignore_word:"Prezri besedo",ignore_words:"Prezri vse",langs:"Jeziki",wait:"Prosim po\u010dakaj...",sug:"Predlogi",no_sug:"Ni predlogov",no_mpell:"Napa\u010dnega \u010drkovanja nisem na\u0161el.",learn_word:"Zapomni si besedo"},pagebreak:{desc:"Vstavi lom strani."},advlist:{types:"Tipi",def:"Privzeto",lower_alpha:"Mali znaki",lower_greek:"Male gr\u0161ke \u010drke",lower_roman:"Male latinske \u010drke",upper_alpha:"Veliki znaki",upper_roman:"Velike latinske \u010drke",circle:"Krog",disc:"Disk",square:"Kvadrat"},colors:{"333300":"Temno olivna","993300":"Za\u017egano oran\u017ena","000000":"\u010crna","003300":"Temno zelena","003366":"Sinje temna","000080":"Mornarsko modra","333399":"Indigo","333333":"Zelo temno siva","800000":"Kostanjevo rde\u010da",FF6600:"Oran\u017ena","808000":"Olivna","008000":"Zelena","008080":"Temno sinje modra","0000FF":"Modra","666699":"Sivo modra","808080":"Siva",FF0000:"Rde\u010da",FF9900:"Jantarna","99CC00":"Rumeno zelena","339966":"Morsko zelena","33CCCC":"Turkizna","3366FF":"Kraljevsko modra","800080":"Vijoli\u010dna","999999":"Srednje siva",FF00FF:"Svetlo vijoli\u010dna",FFCC00:"Zlata",FFFF00:"Rumena","00FF00":"Citronsko zelena","00FFFF":"Akvarijsko modra","00CCFF":"Nebe\u0161ko modra","993366":"Rjava",C0C0C0:"Srebrna",FF99CC:"Roza",FFCC99:"Mareli\u010dna",FFFF99:"Svetlo rumena",CCFFCC:"Bledo zelena",CCFFFF:"Bledo turkizna","99CCFF":"Svetlo nebe\u0161ko modra",CC99FF:"Slivova",FFFFFF:"Bela"},aria:{rich_text_area:"Polje z obogatenim besedilom"},wordcount:{words:"Besed:"},visualblocks:{desc:"Prika\u017ei/skrij elemente blokov"}}});<commit_msg>Update TinyMCE global translation<commit_after>tinyMCE.addI18n({sl:{common:{more_colors:"Ve\u010d barv",invalid_data:"Napaka: vne\u0161ene so bile nepravilne vrednosti, ozna\u010dene so z rde\u010do.",popup_blocked:"\u017dal va\u0161e orodje za prepre\u010devanje odpiranja neza\u017eelenih oken (popup-blocker) ne omogo\u010da prikaza pomo\u017enega okna izbranega orodja. Prepre\u010devanje odpiranja oken morate onemogo\u010diti.",clipboard_no_support:"Trenutno ni podporto v va\u0161em brskalniku. Uporabite bli\u017enjice tipkovnice.",clipboard_msg:"Delo z odlo\u017ei\u0161\u010dem ni mogo\u010de v tem brskalniku. Lahko uporabljate kombinacije tipk Ctrl+X, Ctrl+C, Ctrl+V.\n\u017delite ve\u010d informacij o tem?",not_set:"-- ni nastavljeno --",class_name:"Razred",browse:"Prebrskaj",close:"Zapri",cancel:"Prekli\u010di",update:"Posodobi",insert:"Vstavi",apply:"Uporabi",edit_confirm:"\u017delite uporabiti na\u010din \\'videz ne vara\\' (WYSIWYG) za to vnosno polje?",invalid_data_number:"{#field} mora biti veljavno \u0161tevilo",invalid_data_min:"{#field} mora biti ve\u010dje od {#min}",invalid_data_size:"{#field} mora biti \u0161tevilo ali odstotek",value:"(vrednost)"},contextmenu:{full:"Polno",right:"Desno",center:"Sredina",left:"Levo",align:"Poravnava"},insertdatetime:{day_short:"ned,pon,tor,sre,\u010det,pet,sob,ned",day_long:"nedelja,ponedeljek,torek,sreda,\u010detrtek,petek,sobota,nedelja",months_short:"jan,feb,mar,apr,maj,jun,jul,avg,sep,okt,nov,dec",months_long:"januar,februar,marec,april,maj,junij,julij,avgust,september,oktober,november,december",inserttime_desc:"Vstavi \u010das",insertdate_desc:"Vstavi datum",time_fmt:"%H:%M:%S",date_fmt:"%d.%m.%Y"},print:{print_desc:"Natisni"},preview:{preview_desc:"Predogled"},directionality:{rtl_desc:"Smer od desne proti levi",ltr_desc:"Smer od leve proti desni"},layer:{content:"Nov sloj...",absolute_desc:"Preklop absolutnega polo\u017eaja",backward_desc:"Premakni v ozadje",forward_desc:"Premakni v ospredje",insertlayer_desc:"Vstavi nov sloj"},save:{save_desc:"Shrani",cancel_desc:"Prekli\u010di vse spremembe"},nonbreaking:{nonbreaking_desc:"Vstavi nedeljivi presledek"},iespell:{download:"ieSpell ni zaznan. \u017delite, da ga namestim?",iespell_desc:"Za\u017eeni preverjanje \u010drkovanja"},advhr:{delta_height:"spremeba_vi\u0161ine",delta_width:"sprememba_\u0161irine",advhr_desc:"Vodoravna \u010drta"},emotions:{delta_height:"delta_vi\u0161ina",delta_width:"delta_\u0161irina",emotions_desc:"Sme\u0161ki"},searchreplace:{replace_desc:"Najdi/zamenjaj",search_desc:"Najdi",delta_width:"",delta_height:""},advimage:{image_desc:"Vstavi/uredi sliko",delta_width:"",delta_height:""},advlink:{link_desc:"Vstavi/uredi povezavo",delta_height:"",delta_width:""},xhtmlxtras:{attribs_desc:"Vstavi/uredi atribute",ins_desc:"Vstavljeno",del_desc:"Izbrisano",acronym_desc:"Kratica",abbr_desc:"Okraj\u0161ava",cite_desc:"Citat",attribs_delta_height:"",attribs_delta_width:"",ins_delta_height:"",ins_delta_width:"",del_delta_height:"",del_delta_width:"",acronym_delta_height:"",acronym_delta_width:"",abbr_delta_height:"",abbr_delta_width:"",cite_delta_height:"",cite_delta_width:""},style:{desc:"Uredi sloge CSS",delta_height:"",delta_width:""},paste:{plaintext_mode:'Operacija prilepi je sedaj v na\u010dinu "golo besedilo". \u010ce jo \u017eelite vrniti v obi\u010dajen na\u010din, kliknite \u0161e enkrat.',plaintext_mode_sticky:'Operacija prilepi je sedaj v na\u010dinu "golo besedilo". \u010ce jo \u017eelite vrniti v obi\u010dajen na\u010din, kliknite \u0161e enkrat. Po izvedbi lepljenja se bo nastavitev povrnila v obi\u010dajen na\u010din.',selectall_desc:"Izberi vse",paste_word_desc:"Prilepi iz Word-a",paste_text_desc:"Prilepi kot golo besedilo"},paste_dlg:{word_title:"Uporabite kombinacijo tipk CTRL+V, da prilepite vsebino v okno.",text_linebreaks:"Obdr\u017ei prelome vrstic",text_title:"Uporabite kombinacijo tipk CTRL+V, da prilepite vsebino v okno."},table:{cellprops_delta_width:"100",cell:"Celica",col:"Stolpec",row:"Vrstica",del:"Odstrani tabelo",copy_row_desc:"Kopiraj vrstico",cut_row_desc:"Izre\u017ei vrstico",paste_row_after_desc:"Prilepi vrstico po",paste_row_before_desc:"Prilepi vrstico pred",props_desc:"Lastnosti tabele",cell_desc:"Lastnosti celice",row_desc:"Lastnosti vrstice",merge_cells_desc:"Spoji celice",split_cells_desc:"Razcepi celico",delete_col_desc:"Odstrani stolpec",col_after_desc:"Vstavi stolpec po",col_before_desc:"Vstavi stolpec pred",delete_row_desc:"Odstrani vrstico",row_after_desc:"Vstavi vrstico pod",row_before_desc:"Vstavi vrstico nad",desc:"Vstavi/posodobi tabelo",merge_cells_delta_height:"",merge_cells_delta_width:"",table_delta_height:"",table_delta_width:"",cellprops_delta_height:"",rowprops_delta_height:"",rowprops_delta_width:""},autosave:{warning_message:"\u010ce povrnete shranjeno vsebino, boste prepisali trenutno vsebino urejevalnika.nnSte prepri\u010dani, da \u017eelite nadaljevati?",restore_content:"Povrni na zadnje shranjeno vsebino.",unload_msg:"\u010ce nadaljujete, bodo spremembe izgubljene."},fullscreen:{desc:"Preklopi celozaslonski na\u010din"},media:{delta_height:"",delta_width:"",edit:"Uredi multimedijsko vsebino",desc:"Vstavi / uredi multimedijsko vsebino"},fullpage:{desc:"Lastnosti dokumenta",delta_width:"sprememba_\u0161irine",delta_height:"sprememba_vi\u0161ine"},template:{desc:"Vstavi pripravljeno vsebino predloge"},visualchars:{desc:"Preklopi prikaz nadzornih znakov."},spellchecker:{desc:"Preklopi \u010drkovalnik",menu:"Nastavitve \u010drkovalnika",ignore_word:"Prezri besedo",ignore_words:"Prezri vse",langs:"Jeziki",wait:"Prosim po\u010dakaj...",sug:"Predlogi",no_sug:"Ni predlogov",no_mpell:"Napa\u010dnega \u010drkovanja nisem na\u0161el.",learn_word:"Zapomni si besedo"},pagebreak:{desc:"Vstavi lom strani."},advlist:{types:"Tipi",def:"Privzeto",lower_alpha:"Mali znaki",lower_greek:"Male gr\u0161ke \u010drke",lower_roman:"Male latinske \u010drke",upper_alpha:"Veliki znaki",upper_roman:"Velike latinske \u010drke",circle:"Krog",disc:"Disk",square:"Kvadrat"},colors:{"333300":"Temno olivna","993300":"Za\u017egano oran\u017ena","000000":"\u010crna","003300":"Temno zelena","003366":"Sinje temna","000080":"Mornarsko modra","333399":"Indigo","333333":"Zelo temno siva","800000":"Kostanjevo rde\u010da",FF6600:"Oran\u017ena","808000":"Olivna","008000":"Zelena","008080":"Temno sinje modra","0000FF":"Modra","666699":"Sivo modra","808080":"Siva",FF0000:"Rde\u010da",FF9900:"Jantarna","99CC00":"Rumeno zelena","339966":"Morsko zelena","33CCCC":"Turkizna","3366FF":"Kraljevsko modra","800080":"Vijoli\u010dna","999999":"Srednje siva",FF00FF:"Svetlo vijoli\u010dna",FFCC00:"Zlata",FFFF00:"Rumena","00FF00":"Citronsko zelena","00FFFF":"Akvarijsko modra","00CCFF":"Nebe\u0161ko modra","993366":"Rjava",C0C0C0:"Srebrna",FF99CC:"Roza",FFCC99:"Mareli\u010dna",FFFF99:"Svetlo rumena",CCFFCC:"Bledo zelena",CCFFFF:"Bledo turkizna","99CCFF":"Svetlo nebe\u0161ko modra",CC99FF:"Slivova",FFFFFF:"Bela"},aria:{rich_text_area:"Polje z obogatenim besedilom"},wordcount:{words:"Besed:"},visualblocks:{desc:"Prika\u017ei/skrij elemente blokov"},magentowidget:{insert_widget:"Vstavi gradnik"},magentovariable:{insert_variable:"Vstavi spremenljivko"}}});<|endoftext|>


<commit_before>#! /usr/bin/env node
const shell = require('shelljs');
const chalk = require('chalk');
// SET SILENT TRUE SO THAT DEFAULT OUTPUT IS NOT PRINTED ON CONSOLE
shell.config.silent = true;
// get command line argument for commit message
module.exports = (branchName, args, callback) => {
  // remove \n from the end
  let command = 'git push';
  switch (args.length) {
    case 0:
      command += ` origin ${branchName}`;
      break;
    case 1:
      command += ` origin ${args[0]}`;
      break;
    case 2:
      command += ` ${args[0]} ${args[1]}`;
      break;
    default:
      callback(chalk.redBright('Invalid arguments'));
      return;
  }
  shell.exec(command, (code, stdout, stderr) => {
    // console.log(121, { code, stdout, stderr });
    if (stderr) {
      console.log(2);
      const commitLine = stderr.substr(stderr.indexOf('..') + 2);
      console.log({ commitLine });
      console.log(branchName);
      console.log(stderr.indexOf(branchName) - 2);
      const commitLine1 = commitLine.substr(0, stderr.indexOf(branchName) - 2);
      console.log({ commitLine1 });
      callback(chalk.redBright(stderr));
      return;
    }
    callback(chalk.greenBright(stdout));
  });
};
<commit_msg>invalid arg removed from data<commit_after>#! /usr/bin/env node
const shell = require('shelljs');
const chalk = require('chalk');
// SET SILENT TRUE SO THAT DEFAULT OUTPUT IS NOT PRINTED ON CONSOLE
shell.config.silent = true;
// get command line argument for commit message
module.exports = (branchName, args, callback) => {
  // remove \n from the end
  let command = 'git push';
  switch (args.length) {
    case 0:
      command += ` origin ${branchName}`;
      break;
    case 1:
      command += ` origin ${args[0]}`;
      break;
    case 2:
      command += ` ${args[0]} ${args[1]}`;
      break;
    default:
      callback(chalk.redBright('Invalid arguments'));
      return;
  }
  shell.exec(command, (code, stdout, stderr) => {
    // console.log(121, { code, stdout, stderr });
    if (stderr) {
      console.log(2);
      const commitLine = stderr.substr(stderr.indexOf('..') + 2).substr(0, stderr.indexOf('  '));
      console.log({ commitLine });
      callback(chalk.redBright(stderr));
      return;
    }
    callback(chalk.greenBright(stdout));
  });
};
<|endoftext|>


<commit_before>// Copyright 2002-2012, University of Colorado

/**
 * Points to a specific node (with a trail), and whether it is conceptually before or after the node.
 *
 * There are two orderings:
 * - rendering order: the order that node selves would be rendered, matching the Trail implicit order
 * - nesting order:   the order in depth first with entering a node being "before" and exiting a node being "after"
 *
 * TODO: more seamless handling of the orders. or just exclusively use the nesting order
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  "use strict";

  var assert = require( 'ASSERT/assert' )( 'scenery' );

  var scenery = require( 'SCENERY/scenery' );

  require( 'SCENERY/util/Trail' );

  /*
   * isBefore: whether this points to before the node (and its children) have been rendered, or after
   */
  scenery.TrailPointer = function( trail, isBefore ) {
    assert && assert( trail instanceof scenery.Trail, 'trail is not a trail' );
    this.trail = trail;

    this.setBefore( isBefore );
  };
  var TrailPointer = scenery.TrailPointer;

  TrailPointer.prototype = {
    constructor: TrailPointer,

    copy: function() {
      return new TrailPointer( this.trail.copy(), this.isBefore );
    },

    setBefore: function( isBefore ) {
      this.isBefore = isBefore;
      this.isAfter = !isBefore;
    },

    // return the equivalent pointer that swaps before and after (may return null if it doesn't exist)
    getRenderSwappedPointer: function() {
      var newTrail = this.isBefore ? this.trail.previous() : this.trail.next();

      if ( newTrail === null ) {
        return null;
      } else {
        return new TrailPointer( newTrail, !this.isBefore );
      }
    },

    getRenderBeforePointer: function() {
      return this.isBefore ? this : this.getRenderSwappedPointer();
    },

    getRenderAfterPointer: function() {
      return this.isAfter ? this : this.getRenderSwappedPointer();
    },

    /*
     * In the render order, will return 0 if the pointers are equivalent, -1 if this pointer is before the
     * other pointer, and 1 if this pointer is after the other pointer.
     */
    compareRender: function( other ) {
      assert && assert( other !== null );

      var a = this.getRenderBeforePointer();
      var b = other.getRenderBeforePointer();

      if ( a !== null && b !== null ) {
        // normal (non-degenerate) case
        return a.trail.compare( b.trail );
      } else {
        // null "before" point is equivalent to the "after" pointer on the last rendered node.
        if ( a === b ) {
          return 0; // uniqueness guarantees they were the same
        } else {
          return a === null ? 1 : -1;
        }
      }
    },

    /*
     * Like compareRender, but for the nested (depth-first) order
     *
     * TODO: optimization?
     */
    compareNested: function( other ) {
      assert && assert( other );

      var comparison = this.trail.compare( other.trail );

      if ( comparison === 0 ) {
        // if trails are equal, just compare before/after
        if ( this.isBefore === other.isBefore ) {
          return 0;
        } else {
          return this.isBefore ? -1 : 1;
        }
      } else {
        // if one is an extension of the other, the shorter isBefore flag determines the order completely
        if ( this.trail.isExtensionOf( other.trail ) ) {
          return other.isBefore ? 1 : -1;
        } else if ( other.trail.isExtensionOf( this.trail ) ) {
          return this.isBefore ? -1 : 1;
        } else {
          // neither is a subtrail of the other, so a straight trail comparison should give the answer
          return comparison;
        }
      }
    },

    equalsRender: function( other ) {
      return this.compareRender( other ) === 0;
    },

    equalsNested: function( other ) {
      return this.compareNested( other ) === 0;
    },

    // TODO: refactor with "Side"-like handling
    // moves this pointer forwards one step in the nested order
    nestedForwards: function() {
      if ( this.isBefore ) {
        if ( this.trail.lastNode()._children.length > 0 ) {
          // stay as before, just walk to the first child
          this.trail.addDescendant( this.trail.lastNode()._children[0], 0 );
        } else {
          // stay on the same node, but switch to after
          this.setBefore( false );
        }
      } else {
        if ( this.trail.indices.length === 0 ) {
          // nothing else to jump to below, so indicate the lack of existence
          return null;
        } else {
          var index = this.trail.indices[this.trail.indices.length - 1];
          this.trail.removeDescendant();

          if ( this.trail.lastNode()._children.length > index + 1 ) {
            // more siblings, switch to the beginning of the next one
            this.trail.addDescendant( this.trail.lastNode()._children[index+1], index + 1 );
            this.setBefore( true );
          } else {
            // no more siblings. exit on parent. nothing else needed since we're already isAfter
          }
        }
      }
    },

    // moves this pointer backwards one step in the nested order
    nestedBackwards: function() {
      if ( this.isBefore ) {
        if ( this.trail.indices.length === 0 ) {
          // jumping off the front
          return null;
        } else {
          var index = this.trail.indices[this.trail.indices.length - 1];
          this.trail.removeDescendant();

          if ( index - 1 >= 0 ) {
            // more siblings, switch to the beginning of the previous one and switch to isAfter
            this.trail.addDescendant( this.trail.lastNode()._children[index-1], index - 1 );
            this.setBefore( false );
          } else {
            // no more siblings. enter on parent. nothing else needed since we're already isBefore
          }
        }
      } else {
        if ( this.trail.lastNode()._children.length > 0 ) {
          // stay isAfter, but walk to the last child
          var children = this.trail.lastNode()._children;
          this.trail.addDescendant( children[children.length-1], children.length - 1 );
        } else {
          // switch to isBefore, since this is a leaf node
          this.setBefore( true );
        }
      }
    },

    // treats the pointer as render-ordered (includes the start pointer 'before' if applicable, excludes the end pointer 'before' if applicable
    eachNodeBetween: function( other, callback ) {
      this.eachTrailBetween( other, function( trail ) {
        callback( trail.lastNode() );
      } );
    },

    // treats the pointer as render-ordered (includes the start pointer 'before' if applicable, excludes the end pointer 'before' if applicable
    eachTrailBetween: function( other, callback ) {
      // this should trigger on all pointers that have the 'before' flag, except a pointer equal to 'other'.

      // since we exclude endpoints in the depthFirstUntil call, we need to fire this off first
      if ( this.isBefore ) {
        callback( this.trail );
      }

      this.depthFirstUntil( other, function( pointer ) {
        if ( pointer.isBefore ) {
          callback( pointer.trail );
        }
      }, true ); // exclude the endpoints so we can ignore the ending 'before' case
    },

    /*
     * Recursively (depth-first) iterates over all pointers between this pointer and 'other', calling
     * callback( pointer ) for each pointer. If excludeEndpoints is truthy, the callback will not be
     * called if pointer is equivalent to this pointer or 'other'.
     *
     * If the callback returns a truthy value, the subtree for the current pointer will be skipped
     * (applies only to before-pointers)
     */
    depthFirstUntil: function( other, callback, excludeEndpoints ) {
      // make sure this pointer is before the other, but allow start === end if we are not excluding endpoints
      assert && assert( this.compareNested( other ) <= ( excludeEndpoints ? -1 : 0 ), 'TrailPointer.depthFirstUntil pointers out of order, possibly in both meanings of the phrase!' );
      assert && assert( this.trail.rootNode() === other.trail.rootNode(), 'TrailPointer.depthFirstUntil takes pointers with the same root' );

      // sanity check TODO: remove later
      this.trail.reindex();
      other.trail.reindex();

      var pointer = this.copy();

      var first = true;

      while ( !pointer.equalsNested( other ) ) {
        var skipSubtree = false;

        if ( first ) {
          // start point
          if ( !excludeEndpoints ) {
            skipSubtree = callback( pointer );
          }
          first = false;
        } else {
          // between point
          skipSubtree = callback( pointer );
        }

        if ( skipSubtree && pointer.isBefore ) {
          // to skip the subtree, we just change to isAfter
          pointer.setBefore( false );

          // if we skip a subtree, make sure we don't run past the ending pointer
          if ( pointer.compareNested( other ) === 1 ) {
            break;
          }
        } else {
          pointer.nestedForwards();
        }
      }

      // end point
      if ( !excludeEndpoints ) {
        callback( pointer );
      }
    },

    toString: function() {
      return '[' + ( this.isBefore ? 'before' : 'after' ) + ' ' + this.trail.toString().slice( 1 );
    }
  };

  return TrailPointer;
} );

<commit_msg>Adding assertion to ensure we don't blow past our end point in trail iteration<commit_after>// Copyright 2002-2012, University of Colorado

/**
 * Points to a specific node (with a trail), and whether it is conceptually before or after the node.
 *
 * There are two orderings:
 * - rendering order: the order that node selves would be rendered, matching the Trail implicit order
 * - nesting order:   the order in depth first with entering a node being "before" and exiting a node being "after"
 *
 * TODO: more seamless handling of the orders. or just exclusively use the nesting order
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  "use strict";

  var assert = require( 'ASSERT/assert' )( 'scenery' );

  var scenery = require( 'SCENERY/scenery' );

  require( 'SCENERY/util/Trail' );

  /*
   * isBefore: whether this points to before the node (and its children) have been rendered, or after
   */
  scenery.TrailPointer = function( trail, isBefore ) {
    assert && assert( trail instanceof scenery.Trail, 'trail is not a trail' );
    this.trail = trail;

    this.setBefore( isBefore );
  };
  var TrailPointer = scenery.TrailPointer;

  TrailPointer.prototype = {
    constructor: TrailPointer,

    copy: function() {
      return new TrailPointer( this.trail.copy(), this.isBefore );
    },

    setBefore: function( isBefore ) {
      this.isBefore = isBefore;
      this.isAfter = !isBefore;
    },

    // return the equivalent pointer that swaps before and after (may return null if it doesn't exist)
    getRenderSwappedPointer: function() {
      var newTrail = this.isBefore ? this.trail.previous() : this.trail.next();

      if ( newTrail === null ) {
        return null;
      } else {
        return new TrailPointer( newTrail, !this.isBefore );
      }
    },

    getRenderBeforePointer: function() {
      return this.isBefore ? this : this.getRenderSwappedPointer();
    },

    getRenderAfterPointer: function() {
      return this.isAfter ? this : this.getRenderSwappedPointer();
    },

    /*
     * In the render order, will return 0 if the pointers are equivalent, -1 if this pointer is before the
     * other pointer, and 1 if this pointer is after the other pointer.
     */
    compareRender: function( other ) {
      assert && assert( other !== null );

      var a = this.getRenderBeforePointer();
      var b = other.getRenderBeforePointer();

      if ( a !== null && b !== null ) {
        // normal (non-degenerate) case
        return a.trail.compare( b.trail );
      } else {
        // null "before" point is equivalent to the "after" pointer on the last rendered node.
        if ( a === b ) {
          return 0; // uniqueness guarantees they were the same
        } else {
          return a === null ? 1 : -1;
        }
      }
    },

    /*
     * Like compareRender, but for the nested (depth-first) order
     *
     * TODO: optimization?
     */
    compareNested: function( other ) {
      assert && assert( other );

      var comparison = this.trail.compare( other.trail );

      if ( comparison === 0 ) {
        // if trails are equal, just compare before/after
        if ( this.isBefore === other.isBefore ) {
          return 0;
        } else {
          return this.isBefore ? -1 : 1;
        }
      } else {
        // if one is an extension of the other, the shorter isBefore flag determines the order completely
        if ( this.trail.isExtensionOf( other.trail ) ) {
          return other.isBefore ? 1 : -1;
        } else if ( other.trail.isExtensionOf( this.trail ) ) {
          return this.isBefore ? -1 : 1;
        } else {
          // neither is a subtrail of the other, so a straight trail comparison should give the answer
          return comparison;
        }
      }
    },

    equalsRender: function( other ) {
      return this.compareRender( other ) === 0;
    },

    equalsNested: function( other ) {
      return this.compareNested( other ) === 0;
    },

    // TODO: refactor with "Side"-like handling
    // moves this pointer forwards one step in the nested order
    nestedForwards: function() {
      if ( this.isBefore ) {
        if ( this.trail.lastNode()._children.length > 0 ) {
          // stay as before, just walk to the first child
          this.trail.addDescendant( this.trail.lastNode()._children[0], 0 );
        } else {
          // stay on the same node, but switch to after
          this.setBefore( false );
        }
      } else {
        if ( this.trail.indices.length === 0 ) {
          // nothing else to jump to below, so indicate the lack of existence
          return null;
        } else {
          var index = this.trail.indices[this.trail.indices.length - 1];
          this.trail.removeDescendant();

          if ( this.trail.lastNode()._children.length > index + 1 ) {
            // more siblings, switch to the beginning of the next one
            this.trail.addDescendant( this.trail.lastNode()._children[index+1], index + 1 );
            this.setBefore( true );
          } else {
            // no more siblings. exit on parent. nothing else needed since we're already isAfter
          }
        }
      }
    },

    // moves this pointer backwards one step in the nested order
    nestedBackwards: function() {
      if ( this.isBefore ) {
        if ( this.trail.indices.length === 0 ) {
          // jumping off the front
          return null;
        } else {
          var index = this.trail.indices[this.trail.indices.length - 1];
          this.trail.removeDescendant();

          if ( index - 1 >= 0 ) {
            // more siblings, switch to the beginning of the previous one and switch to isAfter
            this.trail.addDescendant( this.trail.lastNode()._children[index-1], index - 1 );
            this.setBefore( false );
          } else {
            // no more siblings. enter on parent. nothing else needed since we're already isBefore
          }
        }
      } else {
        if ( this.trail.lastNode()._children.length > 0 ) {
          // stay isAfter, but walk to the last child
          var children = this.trail.lastNode()._children;
          this.trail.addDescendant( children[children.length-1], children.length - 1 );
        } else {
          // switch to isBefore, since this is a leaf node
          this.setBefore( true );
        }
      }
    },

    // treats the pointer as render-ordered (includes the start pointer 'before' if applicable, excludes the end pointer 'before' if applicable
    eachNodeBetween: function( other, callback ) {
      this.eachTrailBetween( other, function( trail ) {
        callback( trail.lastNode() );
      } );
    },

    // treats the pointer as render-ordered (includes the start pointer 'before' if applicable, excludes the end pointer 'before' if applicable
    eachTrailBetween: function( other, callback ) {
      // this should trigger on all pointers that have the 'before' flag, except a pointer equal to 'other'.

      // since we exclude endpoints in the depthFirstUntil call, we need to fire this off first
      if ( this.isBefore ) {
        callback( this.trail );
      }

      this.depthFirstUntil( other, function( pointer ) {
        if ( pointer.isBefore ) {
          callback( pointer.trail );
        }
      }, true ); // exclude the endpoints so we can ignore the ending 'before' case
    },

    /*
     * Recursively (depth-first) iterates over all pointers between this pointer and 'other', calling
     * callback( pointer ) for each pointer. If excludeEndpoints is truthy, the callback will not be
     * called if pointer is equivalent to this pointer or 'other'.
     *
     * If the callback returns a truthy value, the subtree for the current pointer will be skipped
     * (applies only to before-pointers)
     */
    depthFirstUntil: function( other, callback, excludeEndpoints ) {
      // make sure this pointer is before the other, but allow start === end if we are not excluding endpoints
      assert && assert( this.compareNested( other ) <= ( excludeEndpoints ? -1 : 0 ), 'TrailPointer.depthFirstUntil pointers out of order, possibly in both meanings of the phrase!' );
      assert && assert( this.trail.rootNode() === other.trail.rootNode(), 'TrailPointer.depthFirstUntil takes pointers with the same root' );

      // sanity check TODO: remove later
      this.trail.reindex();
      other.trail.reindex();

      var pointer = this.copy();

      var first = true;

      while ( !pointer.equalsNested( other ) ) {
        assert && assert( pointer.compareNested( other ) !== 1, 'skipped in depthFirstUntil' );
        var skipSubtree = false;

        if ( first ) {
          // start point
          if ( !excludeEndpoints ) {
            skipSubtree = callback( pointer );
          }
          first = false;
        } else {
          // between point
          skipSubtree = callback( pointer );
        }

        if ( skipSubtree && pointer.isBefore ) {
          // to skip the subtree, we just change to isAfter
          pointer.setBefore( false );

          // if we skip a subtree, make sure we don't run past the ending pointer
          if ( pointer.compareNested( other ) === 1 ) {
            break;
          }
        } else {
          pointer.nestedForwards();
        }
      }

      // end point
      if ( !excludeEndpoints ) {
        callback( pointer );
      }
    },

    toString: function() {
      return '[' + ( this.isBefore ? 'before' : 'after' ) + ' ' + this.trail.toString().slice( 1 );
    }
  };

  return TrailPointer;
} );

<|endoftext|>


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

/**
 * @fileoverview DHTML prompt to replace javascript's prompt().
 *
 * @see ../demos/prompt.html
 */

goog.provide('goog.ui.Prompt');

goog.require('goog.Timer');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.ui.Component.Error');
goog.require('goog.ui.Dialog');
goog.require('goog.ui.Dialog.ButtonSet');
goog.require('goog.ui.Dialog.DefaultButtonKeys');
goog.require('goog.ui.Dialog.EventType');
goog.require('goog.userAgent');

/**
 * Creates an object that represents a prompt (used in place of javascript's
 * prompt). The html structure of the prompt is the same as the layout for
 * dialog.js except for the addition of a text box which is placed inside the
 * "Content area" and has the default class-name 'modal-dialog-userInput'
 *
 * @param {string} promptTitle The title of the prompt.
 * @param {string} promptText The text of the prompt.
 * @param {Function} callback The function to call when the user selects Ok or
 *     Cancel. The function should expect a single argument which represents
 *     what the user entered into the prompt. If the user presses cancel, the
 *     value of the argument will be null.
 * @param {string=} opt_defaultValue Optional default value that should be in
 *     the text box when the prompt appears.
 * @param {string=} opt_class Optional prefix for the classes.
 * @param {boolean=} opt_useIframeForIE For IE, workaround windowed controls
 *     z-index issue by using a an iframe instead of a div for bg element.
 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper; see {@link
 *    goog.ui.Component} for semantics.
 * @constructor
 * @extends {goog.ui.Dialog}
 */
goog.ui.Prompt = function(promptTitle, promptText, callback, opt_defaultValue,
    opt_class, opt_useIframeForIE, opt_domHelper) {
  goog.ui.Dialog.call(this, opt_class, opt_useIframeForIE, opt_domHelper);

  this.setTitle(promptTitle);
  this.setContent(promptText + '

');
  this.callback_ = callback;
  this.defaultValue_ = goog.isDef(opt_defaultValue) ? opt_defaultValue : '';

  goog.events.listen(
      this, goog.ui.Dialog.EventType.SELECT, this.onPromptExit_);

  /** @desc label for a dialog button. */
  var MSG_PROMPT_OK = goog.getMsg('OK');
  /** @desc label for a dialog button. */
  var MSG_PROMPT_CANCEL = goog.getMsg('Cancel');
  var buttonSet = new goog.ui.Dialog.ButtonSet(opt_domHelper);
  buttonSet.set(goog.ui.Dialog.DefaultButtonKeys.OK, MSG_PROMPT_OK, true);
  buttonSet.set(goog.ui.Dialog.DefaultButtonKeys.CANCEL,
      MSG_PROMPT_CANCEL, false, true);
  this.setButtonSet(buttonSet);
};
goog.inherits(goog.ui.Prompt, goog.ui.Dialog);

/**
 * Callback function which is invoked with the response to the prompt
 * @type {Function}
 * @private
 */
goog.ui.Prompt.prototype.callback_ = goog.nullFunction;

/**
 * Default value to display in prompt window
 * @type {string}
 * @private
 */
goog.ui.Prompt.prototype.defaultValue_ = '';

/**
 * Element in which user enters response (HTML <input> text box)
 * @type {HTMLInputElement}
 * @private
 */
goog.ui.Prompt.prototype.userInputEl_ = null;

/**
 * Tracks whether the prompt is in the process of closing to prevent multiple
 * calls to the callback when the user presses enter.
 * @type {boolean}
 * @private
 */
goog.ui.Prompt.prototype.isClosing_ = false;

/**
 * Number of rows in the user input element.
 * The default is 1 which means use an <input> element.
 * @type {number}
 * @private
 */
goog.ui.Prompt.prototype.rows_ = 1;

/**
 * Number of cols in the user input element.
 * The default is 0 which means use browser default.
 * @type {number}
 * @private
 */
goog.ui.Prompt.prototype.cols_ = 0;

/**
 * Set the number of rows in the user input element.
 * A values of 1 means use an <input> element.  If the prompt is already
 * rendered then you cannot change from <input> to <textarea> or vice versa.
 * @param {number} rows Number of rows for user input element.
 * @throws {goog.ui.Component.Error.ALREADY_RENDERED} If the component is
 *    already rendered and an attempt to change between <input> and <textarea>
 *    is made.
 */
goog.ui.Prompt.prototype.setRows = function(rows) {
  if (this.isInDocument()) {
    if (this.userInputEl_.tagName.toLowerCase() == 'input') {
      if (rows > 1) {
        throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
      }
    } else {
      if (rows <= 1) {
        throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
      }
      this.userInputEl_.rows = rows;
    }
  }
  this.rows_ = rows;
};

/**
 * @return {number} The number of rows in the user input element.
 */
goog.ui.Prompt.prototype.getRows = function() {
  return this.rows_;
};

/**
 * Set the number of cols in the user input element.
 * @param {number} cols Number of cols for user input element.
 */
goog.ui.Prompt.prototype.setCols = function(cols) {
  this.cols_ = cols;
  if (this.userInputEl_) {
    if (this.userInputEl_.tagName.toLowerCase() == 'input') {
      this.userInputEl_.size = cols;
    } else {
      this.userInputEl_.cols = cols;
    }
  }
};

/**
 * @return {number} The number of cols in the user input element.
 */
goog.ui.Prompt.prototype.getCols = function() {
  return this.cols_;
};

/**
 * Create the initial DOM representation for the prompt.
 */
goog.ui.Prompt.prototype.createDom = function() {
  goog.ui.Prompt.superClass_.createDom.call(this);

  var cls = this.getClass();

  // add input box to the content
  var attrs = {
    'className': goog.getCssName(cls, 'userInput'),
    'value': this.defaultValue_};
  if (this.rows_ == 1) {
    // If rows == 1 then use an input element.
    this.userInputEl_ = /** @type {HTMLInputElement} */
        (this.getDomHelper().createDom('input', attrs));
    this.userInputEl_.type = 'text';
    if (this.cols_) {
      this.userInputEl_.size = this.cols_;
    }
  } else {
    // If rows > 1 then use a textarea.
    this.userInputEl_ = /** @type {HTMLInputElement} */
        (this.getDomHelper().createDom('textarea', attrs));
    this.userInputEl_.rows = this.rows_;
    if (this.cols_) {
      this.userInputEl_.cols = this.cols_;
    }
  }

  var contentEl = this.getContentElement();
  contentEl.appendChild(this.getDomHelper().createDom(
      'div', {'style': 'overflow: auto'}, this.userInputEl_));

  if (this.rows_ > 1) {
    // Set default button to null so <enter> will work properly in the textarea
    this.getButtonSet().setDefault(null);
  }
};

/**
 * Causes the prompt to appear, centered on the screen, gives focus
 * to the text box, and selects the text
 * @param {boolean} visible Whether the dialog should be visible.
 */
goog.ui.Prompt.prototype.setVisible = function(visible) {
  goog.ui.Dialog.prototype.setVisible.call(this, visible);
  if (visible) {
    this.isClosing_ = false;
    this.userInputEl_.value = this.defaultValue_;
    this.focus();
  }
};

/**
 * Overrides setFocus to put focus on the input element.
 * @override
 */
goog.ui.Prompt.prototype.focus = function() {
  if (goog.userAgent.OPERA) {
    // select() doesn't focus <input> elements in Opera.
    this.userInputEl_.focus();
  }
  this.userInputEl_.select();
};

/**
 * Sets the default value of the prompt when it is displayed.
 * @param {string} defaultValue The default value to display.
 */
goog.ui.Prompt.prototype.setDefaultValue = function(defaultValue) {
  this.defaultValue_ = defaultValue;
};

/**
 * Handles the closing of the prompt, invoking the callback function that was
 * registered to handle the value returned by the prompt.
 * @param {goog.ui.Dialog.Event} e The dialog's selection event.
 * @private
 */
goog.ui.Prompt.prototype.onPromptExit_ = function(e) {
  /*
   * The timeouts below are required for one edge case. If after the dialog
   * hides, suppose validation of the input fails which displays an alert. If
   * the user pressed the Enter key to dismiss the alert that was displayed it
   * can trigger the event handler a second time. This timeout ensures that the
   * alert is displayed only after the prompt is able to clean itself up.
   */
  if (!this.isClosing_) {
    this.isClosing_ = true;
    if (e.key == 'ok') {
      goog.Timer.callOnce(
          goog.bind(this.callback_, this, this.userInputEl_.value), 1);
    } else {
      goog.Timer.callOnce(goog.bind(this.callback_, this, null), 1);
    }
  }
};

/** @inheritDoc */
goog.ui.Prompt.prototype.disposeInternal = function() {
  goog.dom.removeNode(this.userInputEl_);

  goog.events.unlisten(this, goog.ui.Dialog.EventType.SELECT,
      this.onPromptExit_, true, this);

  goog.ui.Prompt.superClass_.disposeInternal.call(this);

  this.defaulValue_ = null;
  this.userInputEl_ = null;
};
<commit_msg><commit_after>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview DHTML prompt to replace javascript's prompt().
 *
 * @see ../demos/prompt.html
 */

goog.provide('goog.ui.Prompt');

goog.require('goog.Timer');
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.ui.Component.Error');
goog.require('goog.ui.Dialog');
goog.require('goog.ui.Dialog.ButtonSet');
goog.require('goog.ui.Dialog.DefaultButtonKeys');
goog.require('goog.ui.Dialog.EventType');
goog.require('goog.userAgent');

/**
 * Creates an object that represents a prompt (used in place of javascript's
 * prompt). The html structure of the prompt is the same as the layout for
 * dialog.js except for the addition of a text box which is placed inside the
 * "Content area" and has the default class-name 'modal-dialog-userInput'
 *
 * @param {string} promptTitle The title of the prompt.
 * @param {string} promptText The text of the prompt.
 * @param {Function} callback The function to call when the user selects Ok or
 *     Cancel. The function should expect a single argument which represents
 *     what the user entered into the prompt. If the user presses cancel, the
 *     value of the argument will be null.
 * @param {string=} opt_defaultValue Optional default value that should be in
 *     the text box when the prompt appears.
 * @param {string=} opt_class Optional prefix for the classes.
 * @param {boolean=} opt_useIframeForIE For IE, workaround windowed controls
 *     z-index issue by using a an iframe instead of a div for bg element.
 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper; see {@link
 *    goog.ui.Component} for semantics.
 * @constructor
 * @extends {goog.ui.Dialog}
 */
goog.ui.Prompt = function(promptTitle, promptText, callback, opt_defaultValue,
    opt_class, opt_useIframeForIE, opt_domHelper) {
  goog.ui.Dialog.call(this, opt_class, opt_useIframeForIE, opt_domHelper);

  /**
   * The id of the input element.
   * @type {string}
   * @private
   */
  this.inputElementId_ = this.makeId('ie');

  this.setTitle(promptTitle);
  this.setContent('' + promptText +
      '

');
  this.callback_ = callback;
  this.defaultValue_ = goog.isDef(opt_defaultValue) ? opt_defaultValue : '';

  goog.events.listen(
      this, goog.ui.Dialog.EventType.SELECT, this.onPromptExit_);

  /** @desc label for a dialog button. */
  var MSG_PROMPT_OK = goog.getMsg('OK');
  /** @desc label for a dialog button. */
  var MSG_PROMPT_CANCEL = goog.getMsg('Cancel');
  var buttonSet = new goog.ui.Dialog.ButtonSet(opt_domHelper);
  buttonSet.set(goog.ui.Dialog.DefaultButtonKeys.OK, MSG_PROMPT_OK, true);
  buttonSet.set(goog.ui.Dialog.DefaultButtonKeys.CANCEL,
      MSG_PROMPT_CANCEL, false, true);
  this.setButtonSet(buttonSet);
};
goog.inherits(goog.ui.Prompt, goog.ui.Dialog);

/**
 * Callback function which is invoked with the response to the prompt
 * @type {Function}
 * @private
 */
goog.ui.Prompt.prototype.callback_ = goog.nullFunction;

/**
 * Default value to display in prompt window
 * @type {string}
 * @private
 */
goog.ui.Prompt.prototype.defaultValue_ = '';

/**
 * Element in which user enters response (HTML <input> text box)
 * @type {HTMLInputElement}
 * @private
 */
goog.ui.Prompt.prototype.userInputEl_ = null;

/**
 * Tracks whether the prompt is in the process of closing to prevent multiple
 * calls to the callback when the user presses enter.
 * @type {boolean}
 * @private
 */
goog.ui.Prompt.prototype.isClosing_ = false;

/**
 * Number of rows in the user input element.
 * The default is 1 which means use an <input> element.
 * @type {number}
 * @private
 */
goog.ui.Prompt.prototype.rows_ = 1;

/**
 * Number of cols in the user input element.
 * The default is 0 which means use browser default.
 * @type {number}
 * @private
 */
goog.ui.Prompt.prototype.cols_ = 0;

/**
 * Set the number of rows in the user input element.
 * A values of 1 means use an <input> element.  If the prompt is already
 * rendered then you cannot change from <input> to <textarea> or vice versa.
 * @param {number} rows Number of rows for user input element.
 * @throws {goog.ui.Component.Error.ALREADY_RENDERED} If the component is
 *    already rendered and an attempt to change between <input> and <textarea>
 *    is made.
 */
goog.ui.Prompt.prototype.setRows = function(rows) {
  if (this.isInDocument()) {
    if (this.userInputEl_.tagName.toLowerCase() == 'input') {
      if (rows > 1) {
        throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
      }
    } else {
      if (rows <= 1) {
        throw Error(goog.ui.Component.Error.ALREADY_RENDERED);
      }
      this.userInputEl_.rows = rows;
    }
  }
  this.rows_ = rows;
};

/**
 * @return {number} The number of rows in the user input element.
 */
goog.ui.Prompt.prototype.getRows = function() {
  return this.rows_;
};

/**
 * Set the number of cols in the user input element.
 * @param {number} cols Number of cols for user input element.
 */
goog.ui.Prompt.prototype.setCols = function(cols) {
  this.cols_ = cols;
  if (this.userInputEl_) {
    if (this.userInputEl_.tagName.toLowerCase() == 'input') {
      this.userInputEl_.size = cols;
    } else {
      this.userInputEl_.cols = cols;
    }
  }
};

/**
 * @return {number} The number of cols in the user input element.
 */
goog.ui.Prompt.prototype.getCols = function() {
  return this.cols_;
};

/**
 * Create the initial DOM representation for the prompt.
 */
goog.ui.Prompt.prototype.createDom = function() {
  goog.ui.Prompt.superClass_.createDom.call(this);

  var cls = this.getClass();

  // add input box to the content
  var attrs = {
    'className': goog.getCssName(cls, 'userInput'),
    'value': this.defaultValue_};
  if (this.rows_ == 1) {
    // If rows == 1 then use an input element.
    this.userInputEl_ = /** @type {HTMLInputElement} */
        (this.getDomHelper().createDom('input', attrs));
    this.userInputEl_.type = 'text';
    if (this.cols_) {
      this.userInputEl_.size = this.cols_;
    }
  } else {
    // If rows > 1 then use a textarea.
    this.userInputEl_ = /** @type {HTMLInputElement} */
        (this.getDomHelper().createDom('textarea', attrs));
    this.userInputEl_.rows = this.rows_;
    if (this.cols_) {
      this.userInputEl_.cols = this.cols_;
    }
  }

  this.userInputEl_.id = this.inputElementId_;
  var contentEl = this.getContentElement();
  contentEl.appendChild(this.getDomHelper().createDom(
      'div', {'style': 'overflow: auto'}, this.userInputEl_));

  if (this.rows_ > 1) {
    // Set default button to null so <enter> will work properly in the textarea
    this.getButtonSet().setDefault(null);
  }
};

/**
 * Causes the prompt to appear, centered on the screen, gives focus
 * to the text box, and selects the text
 * @param {boolean} visible Whether the dialog should be visible.
 */
goog.ui.Prompt.prototype.setVisible = function(visible) {
  goog.ui.Dialog.prototype.setVisible.call(this, visible);
  if (visible) {
    this.isClosing_ = false;
    this.userInputEl_.value = this.defaultValue_;
    this.focus();
  }
};

/**
 * Overrides setFocus to put focus on the input element.
 * @override
 */
goog.ui.Prompt.prototype.focus = function() {
  if (goog.userAgent.OPERA) {
    // select() doesn't focus <input> elements in Opera.
    this.userInputEl_.focus();
  }
  this.userInputEl_.select();
};

/**
 * Sets the default value of the prompt when it is displayed.
 * @param {string} defaultValue The default value to display.
 */
goog.ui.Prompt.prototype.setDefaultValue = function(defaultValue) {
  this.defaultValue_ = defaultValue;
};

/**
 * Handles the closing of the prompt, invoking the callback function that was
 * registered to handle the value returned by the prompt.
 * @param {goog.ui.Dialog.Event} e The dialog's selection event.
 * @private
 */
goog.ui.Prompt.prototype.onPromptExit_ = function(e) {
  /*
   * The timeouts below are required for one edge case. If after the dialog
   * hides, suppose validation of the input fails which displays an alert. If
   * the user pressed the Enter key to dismiss the alert that was displayed it
   * can trigger the event handler a second time. This timeout ensures that the
   * alert is displayed only after the prompt is able to clean itself up.
   */
  if (!this.isClosing_) {
    this.isClosing_ = true;
    if (e.key == 'ok') {
      goog.Timer.callOnce(
          goog.bind(this.callback_, this, this.userInputEl_.value), 1);
    } else {
      goog.Timer.callOnce(goog.bind(this.callback_, this, null), 1);
    }
  }
};

/** @inheritDoc */
goog.ui.Prompt.prototype.disposeInternal = function() {
  goog.dom.removeNode(this.userInputEl_);

  goog.events.unlisten(this, goog.ui.Dialog.EventType.SELECT,
      this.onPromptExit_, true, this);

  goog.ui.Prompt.superClass_.disposeInternal.call(this);

  this.defaulValue_ = null;
  this.userInputEl_ = null;
};
<|endoftext|>


<commit_before>// Worker class
//
'use strict';

const _           = require('lodash');
const co          = require('bluebird-co');
const randomBytes = require('crypto').randomBytes;
const toPromiseFn = require('./utils').toPromiseFn;

// Redis time to milliseconds
//
// - time (Array) - time from redis
//
function redisToMs(time) {
  // Redis reply containing two elements: unix time in seconds, microseconds
  return time[0] * 1000 + Math.round(time[1] / 1000);
}

function Worker(queue, options) {
  this.queue = queue;

  this.name = options.name;

  // Override taskID if passed
  if (options.taskID) {
    if (typeof options.taskID === 'string') {
      this.taskID = function () { return options.taskID; };
    } else {
      this.taskID = options.taskID;
    }
  }

  this.chunksPerInstance = options.chunksPerInstance || Infinity;

  this.retry = options.retry || 2;
  this.retryDelay = options.retryDelay || 60 * 1000;

  this.timeout = options.timeout || 30 * 1000;

  this.cron = options.cron;

  let track = 3600 * 1000;

  if (options.track === false) track = 0;
  if (_.isNumber(options.track)) track = options.track;

  this.track = track;

  this.postponeDelay = options.postponeDelay;

  this.map = toPromiseFn(options.map || function () { return [ this.data ]; }, 0);

  this.process = toPromiseFn(options.process || function () {}, 0);

  this.reduce = toPromiseFn(options.reduce || function (/* chunksResult */) {}, 1);

  this.chunksTracker = {};
}

Worker.prototype.taskID = function () {
  return randomBytes(20).toString('hex');
};

// Run the task immediately
//
// - taskData (Object) - optional, the task params
//
Worker.prototype.push = function (taskData) {
  return this.queue.__addTask__(this, taskData);
};

// Postpone the task executions
//
// - taskData (Object) - optional, the task params, default: `null`
// - delay (Number) - optional, delay execution for the given amount of time,
//   default: `worker.postponeDelay`
//
Worker.prototype.postpone = co.wrap(function* (taskData, delay) {
  if (arguments.length === 1) {
    // postpone(delay) if the argument is a number
    // postpone(taskData) otherwise
    if (Number.isFinite(taskData)) {
      delay = taskData;
      taskData = null;
    } else {
      delay = null;
    }
  }

  if (!Number.isFinite(delay)) {
    delay = this.postponeDelay;
  }

  let task_id_local = this.taskID(taskData);
  // Add global prefix and worker name to every task ID
  let task_id_global = this.queue.__prefix__ + this.name + ':' + task_id_local;

  let redisTime = yield this.queue.__redis__.timeAsync();

  let time = redisToMs(redisTime) + delay;

  // Create a new task in the postponed set
  //
  // - prefix
  // - task ID
  // - worker name
  // - task data
  // - delay
  //
  yield this.queue.__redis__.evalAsync(
    this.queue.__scripts__.task_add_postponed,
    2,
    this.queue.__prefix__,
    task_id_global,
    this.name,
    JSON.stringify(taskData || null),
    time
  );

  return task_id_local;
});

// Get information about task status.
//
// - taskID (String) - optional, task ID returned from `push` or `postpone`
//   functions, result of `.taskID()` by default
//
// The value of the resolved promise is (Object | Null) - task info if task exists, null otherwise
//   - worker (String) - worker name
//   - state  (String) - one of "mapping", "aggregating", "reducing" or "postponed"
//   - chunks (Object) - full chunk IDs by state (optional, only present if task is in "aggregating" state)
//     - pending (Array) - array of pending chunk IDs
//     - active  (Array) - array of active chunk IDs
//     - done    (Array) - array of completed chunk IDs
//     - errored (Array) - array of failed chunk IDs
//
Worker.prototype.status = co.wrap(function* (taskID) {
  let result = {};

  // Add global prefix and worker name to every task ID
  let task_id_global = this.queue.__prefix__ + this.name + ':' + taskID;

  let data = yield this.queue.__redis__.hmgetAsync(task_id_global, 'type', 'state');

  if (!data[0]) {
    // no such task
    return null;
  }

  result.worker = data[0];
  result.state  = data[1];

  if (result.state !== 'aggregating') {
    return result;
  }

  let stats = yield this.queue.__redis__.multi()
                              .llen(task_id_global + ':chunks:pending')
                              .zcard(task_id_global + ':chunks:active')
                              .zcard(task_id_global + ':chunks:errored')
                              .scard(task_id_global + ':chunks:done')
                              .execAsync();

  result.chunks = {
    pending: stats[0],
    active:  stats[1],
    errored: stats[2],
    done:    stats[3]
  };

  return result;
});

// Cancel the task and remove it from queue. Chunks that started execution
// will continue, but their results will be discarded and no new chunks
// will be processed.
//
// - taskID (String) - optional, task ID returned from `push` or `postpone`
//   functions, result of `.taskID()` by default
//
Worker.prototype.cancel = function (taskID) {
  // Add global prefix and worker name to every task ID
  let task_id_global = this.queue.__prefix__ + this.name + ':' + taskID;

  return this.queue.__deleteTask__(task_id_global);
};

module.exports = Worker;
<commit_msg>Fix worker.cancel() function in queue<commit_after>// Worker class
//
'use strict';

const _           = require('lodash');
const co          = require('bluebird-co');
const randomBytes = require('crypto').randomBytes;
const toPromiseFn = require('./utils').toPromiseFn;

// Redis time to milliseconds
//
// - time (Array) - time from redis
//
function redisToMs(time) {
  // Redis reply containing two elements: unix time in seconds, microseconds
  return time[0] * 1000 + Math.round(time[1] / 1000);
}

function Worker(queue, options) {
  this.queue = queue;

  this.name = options.name;

  // Override taskID if passed
  if (options.taskID) {
    if (typeof options.taskID === 'string') {
      this.taskID = function () { return options.taskID; };
    } else {
      this.taskID = options.taskID;
    }
  }

  this.chunksPerInstance = options.chunksPerInstance || Infinity;

  this.retry = options.retry || 2;
  this.retryDelay = options.retryDelay || 60 * 1000;

  this.timeout = options.timeout || 30 * 1000;

  this.cron = options.cron;

  let track = 3600 * 1000;

  if (options.track === false) track = 0;
  if (_.isNumber(options.track)) track = options.track;

  this.track = track;

  this.postponeDelay = options.postponeDelay;

  this.map = toPromiseFn(options.map || function () { return [ this.data ]; }, 0);

  this.process = toPromiseFn(options.process || function () {}, 0);

  this.reduce = toPromiseFn(options.reduce || function (/* chunksResult */) {}, 1);

  this.chunksTracker = {};
}

Worker.prototype.taskID = function () {
  return randomBytes(20).toString('hex');
};

// Run the task immediately
//
// - taskData (Object) - optional, the task params
//
Worker.prototype.push = function (taskData) {
  return this.queue.__addTask__(this, taskData);
};

// Postpone the task executions
//
// - taskData (Object) - optional, the task params, default: `null`
// - delay (Number) - optional, delay execution for the given amount of time,
//   default: `worker.postponeDelay`
//
Worker.prototype.postpone = co.wrap(function* (taskData, delay) {
  if (arguments.length === 1) {
    // postpone(delay) if the argument is a number
    // postpone(taskData) otherwise
    if (Number.isFinite(taskData)) {
      delay = taskData;
      taskData = null;
    } else {
      delay = null;
    }
  }

  if (!Number.isFinite(delay)) {
    delay = this.postponeDelay;
  }

  let task_id_local = this.taskID(taskData);
  // Add global prefix and worker name to every task ID
  let task_id_global = this.queue.__prefix__ + this.name + ':' + task_id_local;

  let redisTime = yield this.queue.__redis__.timeAsync();

  let time = redisToMs(redisTime) + delay;

  // Create a new task in the postponed set
  //
  // - prefix
  // - task ID
  // - worker name
  // - task data
  // - delay
  //
  yield this.queue.__redis__.evalAsync(
    this.queue.__scripts__.task_add_postponed,
    2,
    this.queue.__prefix__,
    task_id_global,
    this.name,
    JSON.stringify(taskData || null),
    time
  );

  return task_id_local;
});

// Get information about task status.
//
// - taskID (String) - optional, task ID returned from `push` or `postpone`
//   functions, result of `.taskID()` by default
//
// The value of the resolved promise is (Object | Null) - task info if task exists, null otherwise
//   - worker (String) - worker name
//   - state  (String) - one of "mapping", "aggregating", "reducing" or "postponed"
//   - chunks (Object) - full chunk IDs by state (optional, only present if task is in "aggregating" state)
//     - pending (Array) - array of pending chunk IDs
//     - active  (Array) - array of active chunk IDs
//     - done    (Array) - array of completed chunk IDs
//     - errored (Array) - array of failed chunk IDs
//
Worker.prototype.status = co.wrap(function* (taskID) {
  let result = {};

  // Add global prefix and worker name to every task ID
  let task_id_global = this.queue.__prefix__ + this.name + ':' + taskID;

  let data = yield this.queue.__redis__.hmgetAsync(task_id_global, 'type', 'state');

  if (!data[0]) {
    // no such task
    return null;
  }

  result.worker = data[0];
  result.state  = data[1];

  if (result.state !== 'aggregating') {
    return result;
  }

  let stats = yield this.queue.__redis__.multi()
                              .llen(task_id_global + ':chunks:pending')
                              .zcard(task_id_global + ':chunks:active')
                              .zcard(task_id_global + ':chunks:errored')
                              .scard(task_id_global + ':chunks:done')
                              .execAsync();

  result.chunks = {
    pending: stats[0],
    active:  stats[1],
    errored: stats[2],
    done:    stats[3]
  };

  return result;
});

// Cancel the task and remove it from queue. Chunks that started execution
// will continue, but their results will be discarded and no new chunks
// will be processed.
//
// - taskID (String) - optional, task ID returned from `push` or `postpone`
//   functions, result of `.taskID()` by default
//
Worker.prototype.cancel = function (taskID) {
  // Default to taskID() for singleton workers
  if (!taskID) taskID = this.taskID();

  // Add global prefix and worker name to every task ID
  let task_id_global = this.queue.__prefix__ + this.name + ':' + taskID;

  return this.queue.__deleteTask__(task_id_global);
};

module.exports = Worker;
<|endoftext|>


<commit_before>function addOne(nameModel3D, path, objPath, mtlPath, type_behavior, x, y, z, r1=0, r2=0, r3=0, s=1){

    // Add javascript variables for viewing the object correctly
    selected_object_trs={"translation":[x, y, z],"rotation":[r1,r2,r3],"scale":s};
    resources3D[nameModel3D]= { "path": path,
                                "obj":objPath,
                                "mtl":mtlPath,
                                "type_behavior":type_behavior,
                                "trs":selected_object_trs};

    // Load the extra item in 3D environment or get it from recycle bin ============================

    // envir.cameraOrbit.children[0] is the recycle bin
    var objInRecycleBin = envir.cameraOrbit.children[0].getObjectByName(nameModel3D);

    // Restore from recycle bin
    if(typeof objInRecycleBin != "undefined"){

        resources3D[nameModel3D] = delArchive[nameModel3D];

        //----------- Add meshes -----------
        //objInRecycleBin.traverse(function (node) {
        //    //if (node.material)
        //    //    node.material.side = THREE.DoubleSide;
        //});
        ////---------------------------------

        // envir.cameraOrbit.children[0] is the recycle Bin
        envir.cameraOrbit.children[0].remove(objInRecycleBin);

        objInRecycleBin.scale.set(s,s,s);
        objInRecycleBin.position.set(x,y,z);
        objInRecycleBin.rotation.set(r1,r2,r3);
        envir.scene.add(objInRecycleBin);

        transform_controls.attach(objInRecycleBin);

    // Load it if it is not in recycle bin
    } else {

        // Make progress bar visible
        $("#progress").get(0).style.display = "block";

        var manager = new THREE.LoadingManager();

        manager.onProgress = function (item, loaded, total) {
            //console.log( item, loaded, total );
        };

        // When all are finished loading
        manager.onLoad = function () {

            //var i_last = obj_ARR.length - 1;
            //console.log(nameModel3D);

            var insertedObject = envir.scene.getObjectByName(nameModel3D); //.substring(0,nameModel3D.lastIndexOf(("_"))));
            if(!insertedObject) {
                $( "#dialog-message" ).dialog( "open" );
            }
            trs_tmp = resources3D[nameModel3D]['trs'];

            insertedObject.position.set(trs_tmp['translation'][0], trs_tmp['translation'][1], trs_tmp['translation'][2]);
            insertedObject.rotation.set(trs_tmp['rotation'][0], trs_tmp['rotation'][1], trs_tmp['rotation'][2]);
            insertedObject.scale.set(trs_tmp['scale'], trs_tmp['scale'], trs_tmp['scale']);
            insertedObject.parent = envir.scene;

            // place controls to last inserted obj
            transform_controls.attach(insertedObject);
            envir.scene.add(transform_controls);

            transform_controls.object.position.set(trs_tmp['translation'][0], trs_tmp['translation'][1], trs_tmp['translation'][2]);
            transform_controls.object.rotation.set(trs_tmp['rotation'][0], trs_tmp['rotation'][1], trs_tmp['rotation'][2]);
            transform_controls.object.scale.set(trs_tmp['scale'], trs_tmp['scale'], trs_tmp['scale']);

            selected_object_name = nameModel3D;
        }

        var extraResource = {};
        extraResource[nameModel3D] = resources3D[nameModel3D];

        var loaderMulti = new LoaderMulti();
        loaderMulti.load(manager, extraResource);
    }

}

/**
 *    ----------- Check for Recycle Bin Drag ----------------------------
 */
function checkForRecycle(){

    var raycasterRecycleBin = new THREE.Raycaster();
    var mouseDrag = new THREE.Vector2();

    // handle scrolling of window
    var offtop = envir.container_3D_all.getBoundingClientRect().top;
    var offleft =envir.container_3D_all.getBoundingClientRect().left;

    // translate into -1 to 1 values
    mouseDrag.x =   ( (event.clientX - offleft)  / envir.container_3D_all.clientWidth ) * 2 - 1;
    mouseDrag.y = - ( (event.clientY - offtop) / envir.container_3D_all.clientHeight ) * 2 + 1;

    // calculate objects intersecting the picking ray
    raycasterRecycleBin.setFromCamera( mouseDrag, envir.cameraOrbit );

    var intersects = raycasterRecycleBin.intersectObjects( [envir.cameraOrbit.children[0]], false );

    if(intersects.length>0)
        putInRecyleBin(transform_controls.object.name);
}

/**
 *
 * -- Put in recycle bin --
 *
 * @param nameToRemove
 */
function putInRecyleBin(nameToRemove){

    var container = document.paramsform;

    // Delete Variables
    delArchive[nameToRemove] = resources3D[nameToRemove];
    delete resources3D[nameToRemove];

    // Remove from scene and add to recycle bin
    var objectSelected = envir.scene.getObjectByName(nameToRemove);

    transform_controls.detach(objectSelected);

    // prevent orbiting
    document.dispatchEvent(new CustomEvent("mouseup", { "detail": "Example of an event" }));

    envir.scene.remove(objectSelected);
    objectSelected.position.set(0,0,0);

    var bbox = new THREE.Box3().setFromObject(objectSelected);

    scale_factor_x = 2/(bbox.max.x - bbox.min.x);
    scale_factor_y = 2/(bbox.max.y - bbox.min.y);
    scale_factor_z = 2/(bbox.max.z - bbox.min.z);

    if (scale_factor_x > 1000)
        scale_factor_x = 1;

    if (scale_factor_y > 1000)
        scale_factor_y = 1;

    if (scale_factor_z > 1000)
        scale_factor_z = 1;

    console.log(scale_factor_x, scale_factor_y, scale_factor_z);

    objectSelected.scale.set(scale_factor_x, scale_factor_y, scale_factor_z);
    objectSelected.isInRecycleBin = true;

    // Removed items are added to the cameraOrbit ??? Find something better
    envir.cameraOrbit.children[0].add(objectSelected);

    // Make trs box visible - invisible
    //if (obj_ARR.length > 0) {
    //    transform_controls.attach(obj_ARR[0]);
    //    transform_controls.traverse(function(node){if(node.name=='trs_modeChanger') node.visible=true});
    //}else
    //    transform_controls.traverse(function(node){if(node.name=='trs_modeChanger') node.visible=false});

}

/**
 * Expand items from recycle bin
 *
 */
function enlistDeletedObjects(){

    for(var i=0; i < envir.cameraOrbit.children[0].children.length; i++){
        if (envir.cameraOrbit.children[0].children[i] instanceof THREE.Group){
            var recycledItem = envir.cameraOrbit.children[0].children[i];
            recycledItem.position.set(0, (i+1)*4, 0);
            recycledItem.isInRecycleBin = true;
        }
    }

    isRecycleBinDeployed = true;
}

/**
 *   Collapse items in recycle bin
 *
 */
function delistDeletedObjects(){

    for(var i=0; i < envir.cameraOrbit.children[0].children.length; i++){
        if (envir.cameraOrbit.children[0].children[i] instanceof THREE.Group){
            var recycledItem = envir.cameraOrbit.children[0].children[i];
            recycledItem.position.set(0,0,0);
            recycledItem.isInRecycleBin = true;
        }
    }

    isRecycleBinDeployed = false;
}
<commit_msg>Fake commit<commit_after>function addOne(nameModel3D, path, objPath, mtlPath, type_behavior, x, y, z, r1=0, r2=0, r3=0, s=1){

    // Add javascript variables for viewing the object correctly
    selected_object_trs={"translation":[x, y, z],"rotation":[r1,r2,r3],"scale":s};
    resources3D[nameModel3D]= { "path": path,
                                "obj":objPath,
                                "mtl":mtlPath,
                                "type_behavior":type_behavior,
                                "trs":selected_object_trs};

    //   Load the extra item in 3D environment or get it from recycle bin ============================

    // envir.cameraOrbit.children[0] is the recycle bin
    var objInRecycleBin = envir.cameraOrbit.children[0].getObjectByName(nameModel3D);

    // Restore from recycle bin
    if(typeof objInRecycleBin != "undefined"){

        resources3D[nameModel3D] = delArchive[nameModel3D];

        //----------- Add meshes -----------
        //objInRecycleBin.traverse(function (node) {
        //    //if (node.material)
        //    //    node.material.side = THREE.DoubleSide;
        //});
        ////---------------------------------

        // envir.cameraOrbit.children[0] is the recycle Bin
        envir.cameraOrbit.children[0].remove(objInRecycleBin);

        objInRecycleBin.scale.set(s,s,s);
        objInRecycleBin.position.set(x,y,z);
        objInRecycleBin.rotation.set(r1,r2,r3);
        envir.scene.add(objInRecycleBin);

        transform_controls.attach(objInRecycleBin);

    // Load it if it is not in recycle bin
    } else {

        // Make progress bar visible
        $("#progress").get(0).style.display = "block";

        var manager = new THREE.LoadingManager();

        manager.onProgress = function (item, loaded, total) {
            //console.log( item, loaded, total );
        };

        // When all are finished loading
        manager.onLoad = function () {

            //var i_last = obj_ARR.length - 1;
            //console.log(nameModel3D);

            var insertedObject = envir.scene.getObjectByName(nameModel3D); //.substring(0,nameModel3D.lastIndexOf(("_"))));
            if(!insertedObject) {
                $( "#dialog-message" ).dialog( "open" );
            }
            trs_tmp = resources3D[nameModel3D]['trs'];

            insertedObject.position.set(trs_tmp['translation'][0], trs_tmp['translation'][1], trs_tmp['translation'][2]);
            insertedObject.rotation.set(trs_tmp['rotation'][0], trs_tmp['rotation'][1], trs_tmp['rotation'][2]);
            insertedObject.scale.set(trs_tmp['scale'], trs_tmp['scale'], trs_tmp['scale']);
            insertedObject.parent = envir.scene;

            // place controls to last inserted obj
            transform_controls.attach(insertedObject);
            envir.scene.add(transform_controls);

            transform_controls.object.position.set(trs_tmp['translation'][0], trs_tmp['translation'][1], trs_tmp['translation'][2]);
            transform_controls.object.rotation.set(trs_tmp['rotation'][0], trs_tmp['rotation'][1], trs_tmp['rotation'][2]);
            transform_controls.object.scale.set(trs_tmp['scale'], trs_tmp['scale'], trs_tmp['scale']);

            selected_object_name = nameModel3D;
        }

        var extraResource = {};
        extraResource[nameModel3D] = resources3D[nameModel3D];

        var loaderMulti = new LoaderMulti();
        loaderMulti.load(manager, extraResource);
    }

}

/**
 *    ----------- Check for Recycle Bin Drag ----------------------------
 */
function checkForRecycle(){

    var raycasterRecycleBin = new THREE.Raycaster();
    var mouseDrag = new THREE.Vector2();

    // handle scrolling of window
    var offtop = envir.container_3D_all.getBoundingClientRect().top;
    var offleft =envir.container_3D_all.getBoundingClientRect().left;

    // translate into -1 to 1 values
    mouseDrag.x =   ( (event.clientX - offleft)  / envir.container_3D_all.clientWidth ) * 2 - 1;
    mouseDrag.y = - ( (event.clientY - offtop) / envir.container_3D_all.clientHeight ) * 2 + 1;

    // calculate objects intersecting the picking ray
    raycasterRecycleBin.setFromCamera( mouseDrag, envir.cameraOrbit );

    var intersects = raycasterRecycleBin.intersectObjects( [envir.cameraOrbit.children[0]], false );

    if(intersects.length>0)
        putInRecyleBin(transform_controls.object.name);
}

/**
 *
 * -- Put in recycle bin --
 *
 * @param nameToRemove
 */
function putInRecyleBin(nameToRemove){

    var container = document.paramsform;

    // Delete Variables
    delArchive[nameToRemove] = resources3D[nameToRemove];
    delete resources3D[nameToRemove];

    // Remove from scene and add to recycle bin
    var objectSelected = envir.scene.getObjectByName(nameToRemove);

    transform_controls.detach(objectSelected);

    // prevent orbiting
    document.dispatchEvent(new CustomEvent("mouseup", { "detail": "Example of an event" }));

    envir.scene.remove(objectSelected);
    objectSelected.position.set(0,0,0);

    var bbox = new THREE.Box3().setFromObject(objectSelected);

    scale_factor_x = 2/(bbox.max.x - bbox.min.x);
    scale_factor_y = 2/(bbox.max.y - bbox.min.y);
    scale_factor_z = 2/(bbox.max.z - bbox.min.z);

    if (scale_factor_x > 1000)
        scale_factor_x = 1;

    if (scale_factor_y > 1000)
        scale_factor_y = 1;

    if (scale_factor_z > 1000)
        scale_factor_z = 1;

    console.log(scale_factor_x, scale_factor_y, scale_factor_z);

    objectSelected.scale.set(scale_factor_x, scale_factor_y, scale_factor_z);
    objectSelected.isInRecycleBin = true;

    // Removed items are added to the cameraOrbit ??? Find something better
    envir.cameraOrbit.children[0].add(objectSelected);

    // Make trs box visible - invisible
    //if (obj_ARR.length > 0) {
    //    transform_controls.attach(obj_ARR[0]);
    //    transform_controls.traverse(function(node){if(node.name=='trs_modeChanger') node.visible=true});
    //}else
    //    transform_controls.traverse(function(node){if(node.name=='trs_modeChanger') node.visible=false});

}

/**
 * Expand items from recycle bin
 *
 */
function enlistDeletedObjects(){

    for(var i=0; i < envir.cameraOrbit.children[0].children.length; i++){
        if (envir.cameraOrbit.children[0].children[i] instanceof THREE.Group){
            var recycledItem = envir.cameraOrbit.children[0].children[i];
            recycledItem.position.set(0, (i+1)*4, 0);
            recycledItem.isInRecycleBin = true;
        }
    }

    isRecycleBinDeployed = true;
}

/**
 *   Collapse items in recycle bin
 *
 */
function delistDeletedObjects(){

    for(var i=0; i < envir.cameraOrbit.children[0].children.length; i++){
        if (envir.cameraOrbit.children[0].children[i] instanceof THREE.Group){
            var recycledItem = envir.cameraOrbit.children[0].children[i];
            recycledItem.position.set(0,0,0);
            recycledItem.isInRecycleBin = true;
        }
    }

    isRecycleBinDeployed = false;
}
<|endoftext|>