text:
MainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI){
  ui->setupUi(this);
  loadIcons();
  scaleFactor = 1/15.0; //simple default value
  ui->combo_rotation->clear();
    ui->combo_rotation->addItem(tr("None"), 0);
    ui->combo_rotation->addItem(tr("Left"), -90);
    ui->combo_rotation->addItem(tr("Right"), 90);
    ui->combo_rotation->addItem(tr("Inverted"), 180);

  singleTileMenu = new QMenu(this);
    singleTileMenu->addAction(tr("Align Horizontally"))->setWhatsThis("X");
    singleTileMenu->addAction(tr("Align Vertically"))->setWhatsThis("Y");
    singleTileMenu->addAction(tr("Align Horizontal then Vertical"))->setWhatsThis("XY");
    singleTileMenu->addAction(tr("Align Vertical then Horizontal"))->setWhatsThis("YX");
  ui->mdiArea->setContextMenuPolicy(Qt::CustomContextMenu);

  profilesMenu = new QMenu(this);
    ui->tool_save->setMenu(profilesMenu);

  connect(ui->mdiArea, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showMenu()) );

  connect(singleTileMenu, SIGNAL(triggered(QAction*)), this, SLOT(tileSingleScreen(QAction*)) );
  connect(ui->push_close, SIGNAL(clicked()), this, SLOT(close()) );
  connect(ui->push_rescan, SIGNAL(clicked()), this, SLOT(UpdateScreens()) );
  connect(ui->push_activate, SIGNAL(clicked()), this, SLOT(ActivateScreen()) );
  connect(ui->tool_deactivate, SIGNAL(clicked()), this, SLOT(DeactivateScreen()) );

  connect(ui->tool_save, SIGNAL(clicked()), this, SLOT(SaveSettings()) );
  connect(ui->tool_applyconfig, SIGNAL(clicked()), this, SLOT(ApplyChanges()) );
  connect(ui->mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),this, SLOT(ScreenSelected()) );
  connect(ui->tool_tileX, SIGNAL(clicked()), this, SLOT(tileScreensX()) );
  connect(ui->tool_tileY, SIGNAL(clicked()), this, SLOT(tileScreensY()) );
  connect(ui->tool_tile, SIGNAL(clicked()), this, SLOT(tileScreens()) );
  connect(ui->combo_availscreens, SIGNAL(currentIndexChanged(int)), this, SLOT(updateNewScreenResolutions()) );

  connect(ui->tool_profile_load, SIGNAL(clicked()), this, SLOT(loadProfile()) );
  connect(ui->tool_profile_remove, SIGNAL(clicked()), this, SLOT(removeProfile()) );
  connect(profilesMenu, SIGNAL(triggered(QAction*)), this, SLOT(saveAsProfile(QAction*)) );

  updateProfiles();
  QTimer::singleShot(0, this, SLOT(UpdateScreens()) );
}

MainUI::~MainUI(){

}

void MainUI::loadIcons(){
  this->setWindowIcon( LXDG::findIcon("preferences-system-windows-actions","") );
  ui->tool_deactivate->setIcon( LXDG::findIcon("list-remove","") );

  ui->push_activate->setIcon( LXDG::findIcon("list-add","") );
  ui->push_rescan->setIcon( LXDG::findIcon("view-refresh","") );
  ui->push_close->setIcon( LXDG::findIcon("window-close","") );
  ui->tabWidget->setTabIcon(0, LXDG::findIcon("preferences-desktop-display","") );
  ui->tabWidget->setTabIcon(1, LXDG::findIcon("list-add","") );
  ui->tool_applyconfig->setIcon( LXDG::findIcon("dialog-ok-apply","") );
}

QString MainUI::currentSelection(){
  QMdiSubWindow *tmp = ui->mdiArea->activeSubWindow();
  if(tmp!=0){ return tmp->whatsThis(); }
  else{ return ""; }
}

ScreenInfo MainUI::currentScreenInfo(){
  QString item = currentSelection();
  if(item!=0){
    for(int i=0; i<SCREENS.length(); i++){
      if(SCREENS[i].ID==item){ return SCREENS[i]; }
    }
  }
  //Fallback when nothing found/selected
  return ScreenInfo();
}

void MainUI::AddScreenToWidget(ScreenInfo screen){
  //qDebug() << "Add Screen To Widget:" << screen.ID << screen.geom;
  QLabel *lab = new QLabel(this);
  lab->setAlignment(Qt::AlignCenter);
  QMdiSubWindow *it = ui->mdiArea->addSubWindow(lab, Qt::Tool | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
  it->setSystemMenu(0);
  it->setWindowTitle(screen.ID);
  lab->setText(QString::number(screen.geom.width())+"x"+QString::number(screen.geom.height()));

  it->setWhatsThis(screen.ID);
  QRect scaled( screen.geom.topLeft()*scaleFactor, screen.geom.size()*scaleFactor);
  //qDebug() << " - Scaled:" << scaled;
  it->show();
  it->setGeometry(scaled); //scale it down for the display
  it->setFixedSize(scaled.size());

}

void MainUI::SyncBackend(){
  QString item = currentSelection();
  if(item.isEmpty()){ return; } //nothing to do
  QString newres = ui->combo_resolution->currentData().toString().section("(",0,0).simplified();
  if(newres.isEmpty()){ return; } //nothing to do
  //qDebug() << "Apply Screen Changes" << item << "->" << newres;
  //Adjust the order of the two screens
  bool setprimary = ui->check_primary->isChecked();
  QList<QMdiSubWindow*> windows = ui->mdiArea->subWindowList();
  for(int i=0; i<SCREENS.length(); i++){
    if(SCREENS[i].ID == item){
      SCREENS[i].geom.setWidth(newres.section("x",0,0).toInt());
      SCREENS[i].geom.setHeight(newres.section("x",1,1).toInt());
      //qDebug() << " - New Geom:" << SCREENS[i].geom;
      SCREENS[i].rotation = ui->combo_rotation->currentData().toInt();
    }
    if(setprimary){ SCREENS[i].isprimary = (SCREENS[i].ID==item); }
    //Find the window associated with this screen
    for(int s=0; s<windows.length(); s++){
      if(windows[s]->whatsThis()==SCREENS[i].ID){
        //qDebug() << "Adjust geom of window:" << SCREENS[i].geom;
        SCREENS[i].geom.moveTopLeft( windows[s]->geometry().topLeft()/scaleFactor );
        //qDebug() << " - New Geom:" << SCREENS[i].geom;
        if(SCREENS[i].applyChange<1){ SCREENS[i].applyChange = (windows[s]->widget()->isEnabled() ? 0 : 1); } //disabled window is one that will be removed
      }
    }
  }
}

void MainUI::UpdateScreens(QString profile){
  //First probe the server for current screens
  if(profile.isEmpty()){ SCREENS = RRSettings::CurrentScreens(); }
  else{ SCREENS = RRSettings::PreviousSettings(profile); }

  //Determine the scale factor for putting these into the UI
  QRegion tot;
  for(int i=0; i<SCREENS.length(); i++){
    if(SCREENS[i].isactive){ tot = tot.united( SCREENS[i].geom ); }
  }
  int wid = tot.boundingRect().width();
  scaleFactor = (0.9*ui->mdiArea->width())/wid;
  //Now go through the screens and arrange them in order from left->right in the UI
  //bool found = true;
  //int xoffset = 0; //start at 0
  //int cnum = 0;
  QString csel = currentSelection();
  //Clear all the current widgets
  while(ui->mdiArea->currentSubWindow()!=0 ){
    QMdiSubWindow *tmp = ui->mdiArea->currentSubWindow();
    tmp->widget()->deleteLater();
    ui->mdiArea->removeSubWindow(tmp);
    tmp->deleteLater();
  }
  //Now add all the active screens to the display
  for(int i=0; i<SCREENS.length(); i++){
    if(SCREENS[i].isactive){ AddScreenToWidget(SCREENS[i]); }
  }

  //Now update the available/current screens in the UI
  ui->combo_availscreens->clear();
  for(int i=0; i<SCREENS.length(); i++){
    if(!SCREENS[i].isactive && SCREENS[i].isavailable){
      ui->combo_availscreens->addItem(SCREENS[i].ID);
    }
  }
  if(ui->combo_availscreens->count()<1){
    ui->group_avail->setVisible(false);
    ui->tabWidget->setCurrentIndex(0);
    ui->tabWidget->setTabEnabled(1,false);
  }else{
    ui->group_avail->setVisible(true);
    ui->tabWidget->setTabEnabled(1,true);
  }
  ScreenSelected(); //update buttons
  updateNewScreenResolutions();
}

void MainUI::ScreenSelected(){
  QString item = currentSelection();
  //QListWidgetItem *item = ui->list_screens->currentItem();
  if(item.isEmpty()){
    //nothing selected
    ui->tool_deactivate->setEnabled(false);
    ui->tab_config->setEnabled(false);
  }else{
    //Item selected
    ui->tool_deactivate->setEnabled(true);
    ui->tab_config->setEnabled(true);
    //Update the info available on the config tab
    ScreenInfo cur = currentScreenInfo();
    ui->combo_resolution->clear();
    QString cres = QString::number(cur.geom.width())+"x"+QString::number(cur.geom.height());
    for(int i=0; i<cur.resList.length(); i++){
      QString res = cur.resList[i].section(" ",0,0, QString::SectionSkipEmpty);
      if(cur.resList[i].contains("+")){ ui->combo_resolution->addItem( QString(tr("%1 (Recommended)")).arg(res), res); }
      else{ui->combo_resolution->addItem(res, res); }
      if(cur.resList[i].contains(cres)){ ui->combo_resolution->setCurrentIndex(i); }
    }
    ui->check_primary->setChecked( cur.isprimary );
    int index = ui->combo_rotation->findData( cur.rotation );
    if(index<0){ index = 0; }
    ui->combo_rotation->setCurrentIndex(index);
  }
}

void MainUI::updateNewScreenResolutions(){
  QString id = ui->combo_availscreens->currentText();
  for(int i=0; i<SCREENS.length(); i++){
    if(SCREENS[i].ID==id){
      ui->combo_resolutions->clear();
      for(int r=0; r<SCREENS[i].resList.length(); r++){
        ui->combo_resolutions->addItem(SCREENS[i].resList[r].section(" ",0,0, QString::SectionSkipEmpty));
        if(SCREENS[i].resList[r].contains("+")){ ui->combo_resolutions->setCurrentIndex(r); } //preferred resolution
      }
      break;
    }
  }
}

void MainUI::tileScreensY(bool activeonly){
  //qDebug() << "Tile Windows in Y Dimension";
  QList<QMdiSubWindow*> wins = ui->mdiArea->subWindowList();
  QMdiSubWindow *active = ui->mdiArea->currentSubWindow();
  QRegion total;
  int ypos = 0;
  QMdiSubWindow *cur = 0;
  while(!wins.isEmpty()){
    cur=0;
    for(int i=0; i<wins.length(); i++){
      if(wins[i]==active && wins.length()>1){ continue; } //ensure active window is last
      if(cur==0){ cur = wins[i]; } //first one
      else if(wins[i]->pos().y() < cur->pos().y()){ cur = wins[i]; }
    }
    if(cur==0){
      //Note: This should **never** happen
      qDebug() << "No windows found below y=:" << ypos;
      //need to move the reference point
      QRect bounding = total.boundingRect();
      ypos+= (bounding.height()/2);
    }else{
      if(total.isNull()){
        //First window handled
        if(!activeonly || cur==active){ cur->move(cur->pos().x(), ypos); }
      }else{
        int newy = ypos;
        bool overlap = true;
        while(overlap){
          QRegion tmp(cur->pos().x(), newy, cur->width(), cur->height());
          QRegion diff = tmp.subtracted(total);
          overlap = (diff.boundingRect()!=tmp.boundingRect() || diff.rects().length()>1);
          //qDebug() << "Check Y Overlap:" << newy << overlap << tmp.boundingRect() << diff.boundingRect();
          if(overlap){
	   QVector<QRect> rects = diff.rects();
            QRect bound = diff.boundingRect();
            //qDebug() << " - got Y overlap:" << bound << rects;
            if( bound.isNull() || rects.isEmpty() ){ newy+=cur->height(); }
            else{
             int orig = newy;
              newy = bound.top();
              for(int i=0; i<rects.length(); i++){
                //qDebug() << " - Check Rect:" << newy << rects[i] << cur->height();
                if(rects[i].height()==cur->height()){ continue; } //skip this one - just the same height
                if(rects[i].top()>newy || newy==bound.bottom()){ newy=rects[i].top(); }
              }
              if(orig==newy){ newy = bound.bottom()+1; } //make sure it always changes - no infinite loops!!
            }
          }
        }
        if(!activeonly || cur==active){ cur->move(cur->pos().x(), newy); }
      }
      total = total.united(cur->geometry());
      wins.removeAll(cur);
    }
  }
}

void MainUI::tileScreensX(bool activeonly){
  //qDebug() << "Tile Windows in X Dimension";
  QList<QMdiSubWindow*> wins = ui->mdiArea->subWindowList();
  QMdiSubWindow *active = ui->mdiArea->currentSubWindow();
  QRegion total;
  int xpos = 0;
  QMdiSubWindow *cur = 0;
  while(!wins.isEmpty()){
    cur=0;
    for(int i=0; i<wins.length(); i++){
      if(wins[i]==active && wins.length()>1){ continue; } //ensure active window is last
      if(cur==0){ cur = wins[i]; } //first one
      else if(wins[i]->pos().x() < cur->pos().x()){ cur = wins[i]; }
    }
    if(cur==0){
      //Note: This should **never** happen
      qDebug() << "No windows found left of x=:" << xpos;
      //need to move the reference point
      QRect bounding = total.boundingRect();
      xpos+= (bounding.width()/2);
    }else{
      if(total.isNull()){
        //First window handled
        if(!activeonly || cur==active){ cur->move(xpos, cur->pos().y()); }
      }else{
        int newx = xpos;
        bool overlap = true;
        while(overlap){
          QRegion tmp(newx, cur->pos().y(), cur->width(), cur->height());
          QRegion diff = tmp.subtracted(total);
          overlap = (diff.boundingRect()!=tmp.boundingRect() || diff.rects().length()>1);
          //qDebug() << "Check X Overlap:" << newx << overlap << total.rects() << tmp.boundingRect() << diff.boundingRect();
          if(overlap){
	   QVector<QRect> rects = diff.rects();
            QRect bound = diff.boundingRect();
            //qDebug() << " - got X overlap:" << bound << rects;
            if( bound.isNull() || rects.isEmpty() ){ newx+=cur->width(); }
            else{
             int orig = newx;
              newx = bound.left();
              for(int i=0; i<rects.length(); i++){
                //qDebug() << " - Check Rect:" << newx << rects[i] << cur->width();
                if(rects[i].width()==cur->width()){ continue; } //skip this one - just the same width
                if(rects[i].left()>newx || newx==bound.right()){ newx=rects[i].left(); }
              }
              if(orig==newx){ newx = bound.right()+1; } //make sure it always changes - no infinite loops!!
            }
          }
        }
        if(!activeonly || cur==active){ cur->move(newx, cur->pos().y()); }
      }
      total = total.united(cur->geometry());
      wins.removeAll(cur);
    }
  }
}

void MainUI::tileScreens(){
  tileScreensY();
  tileScreensX();
}

void MainUI::tileSingleScreen(QAction* act){
  if(act->whatsThis()=="X"){
    tileScreensX(true);
  }else if(act->whatsThis()=="Y"){
    tileScreensY(true);
  }else if(act->whatsThis()=="XY"){
    tileScreensX(true);
    tileScreensY(true);
  }else if(act->whatsThis()=="YX"){
    tileScreensY(true);
    tileScreensX(true);
  }
}

void MainUI::DeactivateScreen(){
  QMdiSubWindow *cur = ui->mdiArea->currentSubWindow();
  if(cur==0){ return; }
  cur->widget()->setEnabled( !cur->widget()->isEnabled() ); //toggle it between enabled/disabled
}

void MainUI::ActivateScreen(){
  //Assemble the command;
  QString ID = ui->combo_availscreens->currentText();
  QStringList res = ui->combo_resolutions->currentText().split("x");
  //Find the screen infor associated with this ID
  for(int i=0; i<SCREENS.length(); i++){
    if(SCREENS[i].ID==ID){
      SCREENS[i].isactive = true;
      SCREENS[i].geom.setSize(  QSize(res[0].toInt(), res[1].toInt()) );
      SCREENS[i].applyChange = 2; //need to activate this monitor
      AddScreenToWidget(SCREENS[i]);
      break;
    }
  }
  tileScreensX(true);
  //Now remove that option from the "new" list
  ui->combo_availscreens->removeItem(ui->combo_availscreens->currentIndex());
  if(ui->combo_availscreens->count()<1){
    ui->group_avail->setVisible(false);
    ui->tabWidget->setCurrentIndex(0);
    ui->tabWidget->setTabEnabled(1,false);
  }else{
    ui->group_avail->setVisible(true);
    ui->tabWidget->setTabEnabled(1,true);
  }
}

void MainUI::ApplyChanges(){
  SyncBackend();
  //Now run the command
  RRSettings::Apply(SCREENS);
  //And update the UI and WM in a moment
  QTimer::singleShot(500, this, SLOT(UpdateScreens()) );
  QTimer::singleShot(1000, this, SLOT(RestartFluxbox()) );
}

void MainUI::SaveSettings(bool quiet){
  SyncBackend();
  bool ok = RRSettings::SaveScreens(SCREENS);
  if(quiet){ return; } //do not show the popup info boxes.
  if(ok){
    QMessageBox::information(this, tr("Settings Saved"), tr("Screen configuration saved as the default for future use"));
  }else{
    QMessageBox::warning(this, tr("Settings Error"), tr("Screen configuration could not be saved. Please check file permissions and try again."));
  }
}

void MainUI::RestartFluxbox(){
  QProcess::startDetached("killall fluxbox");
}

void MainUI::removeProfile(){
  QString cur = ui->combo_profiles->currentText();
  RRSettings::removeProfile(cur);
  updateProfiles();
}

void MainUI::updateProfiles(){
  QStringList profiles = RRSettings::savedProfiles();
  ui->combo_profiles->clear();
  profiles.sort();
  ui->combo_profiles->addItems(profiles);
  //Update the profiles menu as needed
  profilesMenu->clear();
  for(int i=0; i<profiles.length(); i++){
    profilesMenu->addAction(profiles[i])->setWhatsThis(profiles[i]);
  }
  if(!profiles.isEmpty()){ profilesMenu->addSeparator(); }
  profilesMenu->addAction(tr("New Profile") );

  //Now update the tab as needed
  ui->tabWidget->setTabEnabled(2,!profiles.isEmpty());
  if(ui->tabWidget->currentIndex()==2){ ui->tabWidget->setCurrentIndex(0); }
}

void MainUI::loadProfile(){
  QString cur = ui->combo_profiles->currentText();
  UpdateScreens(cur);
}

void MainUI::saveAsProfile(QAction *act){
  QString profile = act->whatsThis();
  if(profile.isEmpty()){
    //Need to prompt for a profile name
    QStringList known = RRSettings::savedProfiles();
    while(known.contains(profile) || profile.isEmpty()){
      bool ok = false;
      profile = QInputDialog::getText(this, tr("Create Screen Profile"), profile.isEmpty() ? tr("Profile Name") : tr("Profile exists - different name:"), QLineEdit::Normal, profile, &ok);
      if(!ok || profile.isEmpty()){ return; } //cancelled
    }
  }
  bool ok = RRSettings::SaveScreens(SCREENS, profile);
  updateProfiles();
  if(ok){
    QMessageBox::information(this, tr("Profile Created"), tr("Current screen configuration saved as profile:")+"\n\n"+profile);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Class__c</name>
    <help>Suoritettavan luokan nimi.</help>
    <label>Luokka</label>
</CustomFieldTranslation>

redpajama_set_name: RedPajamaGithub


text:
def myFilter(L, num): return [x for x in L if x%num != 0]

## Problem 2
def myLists(L): return [[y for y in range(1, x+1)] for x in L]

## Problem 3
def myFunctionComposition(f, g): return {k:g[f[k]] for k in f}

## Problem 4
# Please only enter your numerical solution.

complex_addition_a = 5+3j
complex_addition_b = 1j
complex_addition_c = -1+0.001j
complex_addition_d = 0.001+9j

## Problem 5
GF2_sum_1 = 1
GF2_sum_2 = 0
GF2_sum_3 = 0

## Problem 6
def mySum(L):
    current = 0
    for x in L:
        current += x
    return current

## Problem 7
def myProduct(L):
    current = 1
    for x in L:
        current *= x
    return current

## Problem 8
def myMin(L):
    current = L[0]
    for x in L[1:]:
        if x < current:
            current = x
    return current

## Problem 9
def myConcat(L):
    current = ''
    for x in L:
        current += x
    return current

## Problem 10
def myUnion(L):
    current = set()
    for x in L:
        current = current.union(x)
    return current


text:
"use strict";
(function(){

  var minifyUrl = "http://closure-compiler.appspot.com/compile";

  function init() {
    Espruino.Core.Config.add("MINIFICATION_LEVEL", {
      section : "Communications",
      name : "Minification",
      description : "Automatically minify sent code? This will save Espruino's memory and may increase execution speed, but it will make debugging harder.",
      type : { "":"No Minification",
               "WHITESPACE_ONLY":"Whitespace Only",
               "SIMPLE_OPTIMIZATIONS":"Simple Optimizations",
               "ADVANCED_OPTIMIZATIONS":"Advanced Optimizations (not recommended)"},
      defaultValue : ""
    });
    Espruino.Core.Config.add("MODULE_MINIFICATION_LEVEL", {
      section : "Communications",
      name : "Module Minification",
      description : "Automatically minify modules? This will save Espruino's memory and may increase execution speed, but it will make debugging modules harder. Modules with the extension .min.js will not be minified by default.",
      type : { "":"No Minification",
               "WHITESPACE_ONLY":"Whitespace Only",
               "SIMPLE_OPTIMIZATIONS":"Simple Optimizations",
               "ADVANCED_OPTIMIZATIONS":"Advanced Optimizations (not recommended)"},
      defaultValue : "WHITESPACE_ONLY"
    });

    // When code is sent to Espruino, search it for modules and add extra code required to load them
    Espruino.addProcessor("transformForEspruino", minifyEspruino);
   // When code is sent to Espruino, search it for modules and add extra code required to load them
    Espruino.addProcessor("transformModuleForEspruino", minifyModule);
  }

  function closureCompiler(code, minificationLevel, output_info, callback) {
    var minifyObj = $.param({
      compilation_level: minificationLevel,
      output_format: "text",
      output_info: output_info,
      js_code: code
    });
    $.post(minifyUrl, minifyObj, function(minifiedCode) {
      code = minifiedCode;
    },"text")
      .error(function() {
        Espruino.Core.Notifications.error("HTTP error while minifying.");
      })
      .complete(function() {
        // ensure we call the callback even if minification failes
        callback(code);
    });
  }

  function removeBinaryNumbers(code) {
    // replace all binary numbers with parseInt
    return code.replace(/0b([01][01]*)/g, "parseInt(\"$1\",2)");
  }

  function minifyCode(code, callback, minificationLevel) {
    closureCompiler(removeBinaryNumbers(code), minificationLevel, 'compiled_code', function(minified) {
      if (minified.trim()!="") {
        console.log("Minification complete. Code Size reduced from " + code.length + " to " + minified.length);
        console.log(JSON.stringify(minified));
        callback(minified);
      } else {
        Espruino.Core.Notifications.warning("Errors while minifying - sending unminified code.");
        callback(code);
        // get errors...
        closureCompiler(code, minificationLevel, 'errors', function(errors) {
          console.log("Closure compiler errors: "+errors);
          errors.split("\n").forEach(function (err) {
            if (err.trim()!="")
              Espruino.Core.Notifications.error(err.trim());
          });
        });
      }
    });
  }

  function minifyEspruino(code, callback) {
    if (Espruino.Config.MINIFICATION_LEVEL != "") {
      // if we've been asked to minify...
      minifyCode(code, callback, Espruino.Config.MINIFICATION_LEVEL);
    } else {
      // just pass code onwards
      callback(code);
    }
  }

  function minifyModule(code, callback) {
    if (Espruino.Config.MODULE_MINIFICATION_LEVEL != "") {
      /* we add a header and footer to make sure that the closure compiler
      can rename non-public constants, but NOT the `exports` variable.*/
      var header = "(function(){";
      var footer = "})();";
      // if we've been asked to minify...
      minifyCode(header+code+footer, function(minified) {
       callback(minified.substr(header.length, minified.length-(header.length+footer.length+1)));
      }, Espruino.Config.MODULE_MINIFICATION_LEVEL);
    } else {
      // just pass code onwards
      callback(code);
    }
  }

  Espruino.Plugins.Minify = {
    init : init,
  };
}());


text:
<!DOCTYPE html>

	<link href="js/bootstrap.min.css" rel="stylesheet"type="text/css">
	<link href="css/moncss.css" rel="stylesheet"type="text/css">

	<title>Comparison of ADC software -  General </title>
	<meta charset="utf-8">

Comparison of ADC software -  General

			<fieldset>

					<form action="" method="post">
						<legend style="color:red;font-weight: bold;font-style:italic;text-align: center;" >Formulaire</legend>

								ADC client :
 <input id="0" type="text" name="Feature">

								Active :

 <input type="radio" name="FeatureActive" value="oui">Yes <input type="radio" name="FeatureActive" value = "non">No <input type="radio" name="FeatureActive" value = "non">Partial

											<input  style="display:none;" id ="id2Active"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Active','id2Active');">Changer type</button>

								Software license :
 <input id="1" type="text" name="Feature">

								FOSS :

 <input type="radio" name="FeatureFOSS" value="oui">Yes <input type="radio" name="FeatureFOSS" value = "non">No <input type="radio" name="FeatureFOSS" value = "non">Partial

											<input  style="display:none;" id ="id2FOSS"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1FOSS','id2FOSS');">Changer type</button>

<input type="submit" class="btn btn-info" value="Ajouter un produit" />
					</form>

			</fieldset>


text:
package org.apache.maven.continuum.xmlrpc.client;

import org.apache.maven.continuum.xmlrpc.project.BuildResult;
import org.apache.maven.continuum.xmlrpc.project.BuildResultSummary;
import org.apache.maven.continuum.xmlrpc.project.ProjectGroupSummary;
import org.apache.maven.continuum.xmlrpc.project.ProjectSummary;

import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * Utility class to purge old build results.
 * The easiest way to use it is to change the exec plugin config in the pom to execute this class instead of
 * SampleClient, change RETENTION_DAYS if desired, and type 'mvn clean install exec:exec'
 */
public class BuildResultsPurge
{

    private static ContinuumXmlRpcClient client;

    private static long RETENTION_DAYS = 60;

    private static long DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;

    public static void main( String[] args )
        throws Exception
    {

        client = new ContinuumXmlRpcClient( new URL( args[0] ), args[1], args[2] );

        long today = new Date().getTime();

        System.out.println( "Today is " + new Date( today ) );

        long purgeDate = today - ( RETENTION_DAYS * DAY_IN_MILLISECONDS );
        //long purgeDate = today - 1000;  // 1 second ago (for testing)

        System.out.println( "Purging build results older than " + new Date( purgeDate ) );

        List<ProjectGroupSummary> groups = client.getAllProjectGroups();

        for ( ProjectGroupSummary group : groups )
        {

            System.out.println( "Project Group [" + group.getId() + "] " + group.getName() );

            List<ProjectSummary> projects = client.getProjects( group.getId() );

            for ( ProjectSummary project : projects )
            {

                System.out.println( " Project [" + project.getId() + "] " + project.getName() );

                int batchSize = 100, offset = 0;
                List<BuildResultSummary> results;

                do
                {
                    int retained = 0;
                    results = client.getBuildResultsForProject( project.getId(), offset, batchSize );

                    for ( BuildResultSummary brs : results )
                    {

                        BuildResult br = client.getBuildResult( project.getId(), brs.getId() );

                        System.out.print( "  Build Result [" + br.getId() + "] ended " + new Date( br.getEndTime() ) );

                        if ( br.getEndTime() > 0 && br.getEndTime() < purgeDate )
                        {

                            client.removeBuildResult( br );
                            System.out.println( " ...removed." );
                        }
                        else
                        {
                            System.out.println( " ...retained." );
                            retained++;
                        }
                    }

                    offset += retained;  // Only need to advance past items we keep
                }
                while ( results != null && results.size() == batchSize );
            }

        }
    }
}


text:
const ethUtil = require('ethereumjs-util')
const ethAbi = require('ethereumjs-abi')

module.exports = {

  concatSig: function (v, r, s) {
    const rSig = ethUtil.fromSigned(r)
    const sSig = ethUtil.fromSigned(s)
    const vSig = ethUtil.bufferToInt(v)
    const rStr = padWithZeroes(ethUtil.toUnsigned(rSig).toString('hex'), 64)
    const sStr = padWithZeroes(ethUtil.toUnsigned(sSig).toString('hex'), 64)
    const vStr = ethUtil.stripHexPrefix(ethUtil.intToHex(vSig))
    return ethUtil.addHexPrefix(rStr.concat(sStr, vStr)).toString('hex')
  },

  normalize: function (input) {
    if (!input) return

    if (typeof input === 'number') {
      const buffer = ethUtil.toBuffer(input)
      input = ethUtil.bufferToHex(buffer)
    }

    if (typeof input !== 'string') {
      var msg = 'eth-sig-util.normalize() requires hex string or integer input.'
      msg += ' received ' + (typeof input) + ': ' + input
      throw new Error(msg)
    }

    return ethUtil.addHexPrefix(input.toLowerCase())
  },

  personalSign: function (privateKey, msgParams) {
    var message = ethUtil.toBuffer(msgParams.data)
    var msgHash = ethUtil.hashPersonalMessage(message)
    var sig = ethUtil.ecsign(msgHash, privateKey)
    var serialized = ethUtil.bufferToHex(this.concatSig(sig.v, sig.r, sig.s))
    return serialized
  },

  recoverPersonalSignature: function (msgParams) {
    const publicKey = getPublicKeyFor(msgParams)
    const sender = ethUtil.publicToAddress(publicKey)
    const senderHex = ethUtil.bufferToHex(sender)
    return senderHex
  },

  extractPublicKey: function (msgParams) {
    const publicKey = getPublicKeyFor(msgParams)
    return '0x' + publicKey.toString('hex')
  },

  typedSignatureHash: function (typedData) {
    const hashBuffer = typedSignatureHash(typedData)
    return ethUtil.bufferToHex(hashBuffer)
  },

  signTypedData: function (privateKey, msgParams) {
    const msgHash = typedSignatureHash(msgParams.data)
    const sig = ethUtil.ecsign(msgHash, privateKey)
    return ethUtil.bufferToHex(this.concatSig(sig.v, sig.r, sig.s))
  },

  recoverTypedSignature: function (msgParams) {
    const msgHash = typedSignatureHash(msgParams.data)
    const publicKey = recoverPublicKey(msgHash, msgParams.sig)
    const sender = ethUtil.publicToAddress(publicKey)
    return ethUtil.bufferToHex(sender)
  }

}

/**
 * @param typedData - Array of data along with types, as per EIP712.
 * @returns Buffer
 */
function typedSignatureHash(typedData) {
  const error = new Error('Expect argument to be non-empty array')
  if (typeof typedData !== 'object' || !typedData.length) throw error

  const data = typedData.map(function (e) {
    return e.type === 'bytes' ? ethUtil.toBuffer(e.value) : e.value
  })
  const types = typedData.map(function (e) { return e.type })
  const schema = typedData.map(function (e) {
    if (!e.name) throw error
    return e.type + ' ' + e.name
  })

  return ethAbi.soliditySHA3(
    ['bytes32', 'bytes32'],
    [
      ethAbi.soliditySHA3(new Array(typedData.length).fill('string'), schema),
      ethAbi.soliditySHA3(types, data)
    ]
  )
}

function recoverPublicKey(hash, sig) {
  const signature = ethUtil.toBuffer(sig)
  const sigParams = ethUtil.fromRpcSig(signature)
  return ethUtil.ecrecover(hash, sigParams.v, sigParams.r, sigParams.s)
}

function getPublicKeyFor (msgParams) {
  const message = ethUtil.toBuffer(msgParams.data)
  const msgHash = ethUtil.hashPersonalMessage(message)
  return recoverPublicKey(msgHash, msgParams.sig)
}

function padWithZeroes (number, length) {
  var myString = '' + number
  while (myString.length < length) {
    myString = '0' + myString
  }
  return myString
}


text:
import React from 'react';
import { graphql } from 'gatsby';
import { links } from '../config';
import ChangelogLink from '../components/changelog-link';
import ChangelogListItem from '../components/changelog-list-item';
import Link from '../components/link';

export default ({
                  data: {
                    allFile: { edges },
                  },
                }) => (
  <React.Fragment>

Insomnia Changelog

              Subscribe via RSS

    {edges
      .filter(
        ({
           node: {
             childMarkdownRemark: { frontmatter },
           },
         }) => frontmatter.channel !== 'beta' && frontmatter.channel !== 'alpha',
      )
      .sort((a, b) => {
        const tsA = new Date(
          a.node.childMarkdownRemark.frontmatter.date_iso,
        ).getTime();
        const tsB = new Date(
          b.node.childMarkdownRemark.frontmatter.date_iso,
        ).getTime();
        return tsB - tsA;
      })
      .map(({ node: { childMarkdownRemark: { frontmatter, excerpt } } }) => (
        <article key={`${frontmatter.app}@${frontmatter.slug}`} className="article--preview container">

              <ChangelogLink frontmatter={frontmatter}>

                  Insomnia {frontmatter.app === 'com.insomnia.designer' ? 'Designer' : ''}
                  {' '}
                  {frontmatter.slug}

              </ChangelogLink>

                <time dateTime={frontmatter.date}>{frontmatter.date}</time>

                {excerpt &&
{excerpt}
}
                {frontmatter.major && (

                    {frontmatter.major.map(c => (

                        <ChangelogListItem text={c} />

                    ))}

                )}
                {frontmatter.minor && (

                    {frontmatter.minor.map(c => (

                        <ChangelogListItem text={c} />

                    ))}

                )}
                {frontmatter.fixes && (

                    {frontmatter.fixes.map(c => (

                        <ChangelogListItem text={c} />

                    ))}

                )}

                {(frontmatter.tags || []).map(tag => (
                  <Link
                    key={tag}
                    className="button tags__tag"
                    to={`tags/${tag}`}
                  >
                    {tag}
                  </Link>
                ))}

                <ChangelogLink frontmatter={frontmatter}>
                  Continue Reading »
                </ChangelogLink>

      ))}
  </React.Fragment>
);

export const pageQuery = graphql`
  query ChangelogCoreIndexQuery {
    allFile(filter: { sourceInstanceName: { eq: "changelog" } }) {
      edges {
        node {
          childMarkdownRemark {
            excerpt(pruneLength: 240)
            frontmatter {
              app
              date(formatString: "MMMM DD, YYYY")
              date_iso: date
              channel
              fixes
              link
              major
              minor
              slug
              summary
            }
          }
        }
      }
    }
  }
`;


text:
<?php

namespace Elastica\Test\Aggregation;

use Elastica\Aggregation\Avg;
use Elastica\Aggregation\PercentilesBucket;
use Elastica\Aggregation\Terms;
use Elastica\Document;
use Elastica\Index;
use Elastica\Query;

/**
 * @internal
 */
class PercentilesBucketTest extends BaseAggregationTest
{
    /**
     * @group functional
     */
    public function testPercentilesBucketAggregation(): void
    {
        $query = Query::create([])
            ->addAggregation(
                (new Terms('pages'))
                    ->setField('page')
                    ->setSize(3)
                    ->addAggregation(
                        (new Avg('avg_likes'))
                            ->setField('likes')
                    )
            )
            ->addAggregation(
                (new PercentilesBucket('percentiles_likes_by_page'))
                    ->setBucketsPath('pages>avg_likes')
                    ->setPercents([5, 50, 95])
            )
        ;

        $results = $this->_getIndexForTest()->search($query)->getAggregations();

        $this->assertEquals(5, $results['pages']['buckets'][0]['avg_likes']['value']);
        $this->assertEquals(100, $results['pages']['buckets'][1]['avg_likes']['value']);
        $this->assertEquals(150, $results['pages']['buckets'][2]['avg_likes']['value']);
        $this->assertEquals(
            ['5.0' => 5, '50.0' => 100, '95.0' => 150],
            $results['percentiles_likes_by_page']['values']
        );
    }

    /**
     * @group unit
     */
    public function testConstructThroughSetters(): void
    {
        $serialDiffAgg = new PercentilesBucket('percentiles_bucket');

        $serialDiffAgg
            ->setBucketsPath('pages>avg_likes_by_page')
            ->setFormat('test_format')
            ->setPercents([10, 80])
            ->setGapPolicy(10)
            ->setKeyed(false)
        ;

        $expected = [
            'percentiles_bucket' => [
                'buckets_path' => 'pages>avg_likes_by_page',
                'format' => 'test_format',
                'gap_policy' => 10,
                'percents' => [10, 80],
                'keyed' => false,
            ],
        ];

        $this->assertEquals($expected, $serialDiffAgg->toArray());
    }

    /**
     * @group unit
     */
    public function testToArrayInvalidBucketsPath(): void
    {
        $this->expectException(\Elastica\Exception\InvalidException::class);

        $serialDiffAgg = new PercentilesBucket('avg_bucket');
        $serialDiffAgg->toArray();
    }

    protected function _getIndexForTest(): Index
    {
        $index = $this->_createIndex();

        $index->addDocuments([
            Document::create(['page' => 1, 'likes' => 5]),
            Document::create(['page' => 2, 'likes' => 100]),
            Document::create(['page' => 3, 'likes' => 150]),
        ]);

        $index->refresh();

        return $index;
    }
}


text:
from __future__ import unicode_literals

from .. import Tags, Warning, register

@register(Tags.compatibility)
def check_1_7_compatibility(**kwargs):
    errors = []
    errors.extend(_check_middleware_classes(**kwargs))
    return errors

def _check_middleware_classes(app_configs=None, **kwargs):
    """
    Checks if the user has *not* overridden the ``MIDDLEWARE_CLASSES`` setting &
    warns them about the global default changes.
    """
    from django.conf import settings

    # MIDDLEWARE_CLASSES is overridden by default by startproject. If users
    # have removed this override then we'll warn them about the default changes.
    if not settings.is_overridden('MIDDLEWARE_CLASSES'):
        return [
            Warning(
                "MIDDLEWARE_CLASSES is not set.",
                hint=("Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. "
                      "django.contrib.sessions.middleware.SessionMiddleware, "
                      "django.contrib.auth.middleware.AuthenticationMiddleware, and "
                      "django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. "
                      "If your project needs these middleware then you should configure this setting."),
                obj=None,
                id='1_7.W001',
            )
        ]
    else:
        return []


text:
Components
==========

`disk-image-create [-a i386|amd64|armhf|arm64] -o filename {element} [{element} ...]`

    Create an image of element {element}, optionally mixing in other elements.
    Element dependencies are automatically included. Support for other
    architectures depends on your environment being able to run binaries of
    that platform and/or packages being available for the architecture. For
    instance, to enable armhf on Ubuntu install the qemu-user-static package,
    or to enable arm64 on CentOS setup the RDO aarch64 package repositories.
    The default output format from disk-image-create is qcow2. To instead
    output a tarball pass in "-t tar". This tarball could then be used as an
    image for a linux container(see docs/docker.md).

`ramdisk-image-create -o filename {element} [{element} ...]`

    Create a kernel+ ramdisk pair for running maintenance on bare metal
    machines (deployment, inventory, burnin etc).

    To generate kernel+ramdisk pair for use with nova-baremetal, use::

        ramdisk-image-create -o deploy.ramdisk deploy-baremetal

    To generate kernel+ramdisk pair for use with ironic, use::

        ramdisk-image-create -o deploy.ramdisk ironic-agent

`element-info`

    Extract information about elements.

`tests/run_functests.sh`

    This runs a set of functional tests for diskimage-builder.

elements can be found in the top level elements directory.


text:
INCLUDE(CheckLibraryExists)
INCLUDE(CheckSymbolExists)

CHECK_LIBRARY_EXISTS("socket" getsockname "" VTK_HAVE_LIBSOCKET)

IF("VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T" MATCHES "^VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T$")
  IF(VTK_HAVE_LIBSOCKET)
    SET(VTK_GETSOCKNAME_LIBS "socket")
  ELSE(VTK_HAVE_LIBSOCKET)
    SET(VTK_GETSOCKNAME_LIBS)
  ENDIF(VTK_HAVE_LIBSOCKET)
  MESSAGE(STATUS "Checking for getsockname with socklen_t")
  TRY_COMPILE(VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T
    ${VTK_BINARY_DIR}/CMakeTmp/SocklenT
    ${VTK_CMAKE_DIR}/vtkTestSocklenT.cxx
    CMAKE_FLAGS "-DLINK_LIBRARIES:STRING=${VTK_GETSOCKNAME_LIBS}"
    OUTPUT_VARIABLE OUTPUT)
  IF(VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T)
    MESSAGE(STATUS "Checking for getsockname with socklen_t -- yes")
    SET(VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T 1 CACHE INTERNAL "Support for getsockname with socklen_t")
    WRITE_FILE(${CMAKE_BINARY_DIR}/CMakeFiles/CMakeOutput.log
      "Determining if getsockname accepts socklen_t type  "
      "passed with the following output:\n"
      "${OUTPUT}\n" APPEND)
  ELSE(VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T)
    MESSAGE(STATUS "Checking for getsockname with socklen_t -- no")
    SET(VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T 0 CACHE INTERNAL "Support for getsockname with socklen_t")
    WRITE_FILE(${CMAKE_BINARY_DIR}/CMakeFiles/CMakeError.log
      "Determining if getsockname accepts socklen_t type  "
      "failed with the following output:\n"
      "${OUTPUT}\n" APPEND)
  ENDIF(VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T)
ENDIF("VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T" MATCHES "^VTK_HAVE_GETSOCKNAME_WITH_SOCKLEN_T$")

# e.g. IBM BlueGene/L doesn't have SO_REUSEADDR, because "setsockopt is not needed for
# BlueGene/L applications" according to the BlueGene/L Application Development handbook
CHECK_SYMBOL_EXISTS(SO_REUSEADDR "sys/types.h;sys/socket.h" VTK_HAVE_SO_REUSEADDR)

SET(HAVE_SOCKETS TRUE)
# Cray Xt3/ Catamount doesn't have any socket support
# this could also be determined by doing something like
# check_symbol_exists(socket "sys/types.h;sys/socket.h" HAVE_SOCKETS)
IF(CMAKE_SYSTEM MATCHES Catamount)
  SET(HAVE_SOCKETS FALSE)
ENDIF(CMAKE_SYSTEM MATCHES Catamount)


text:
To use Cocoa's text input system, e.g. the 2-Set Korean input, your view has to implement the [NSTextInputClient](https://developer.apple.com/reference/appkit/nstextinputclient) protocol. Apple's documentation is very scarce, so we're writing down some of our findings.

## Simple Case

For simple cases like `ü`, which can be entered by `Opt-u` + `u`, it's quite straightforward:

1. Enter `Opt-u`.
1. `hasMarkedText()` is called to check whether we already have marked text.
1. `setMarkedText("¨", selectedRange NSRange(1, 0), replacementRange: NSRange(NSNotFound, 0))` is called. In this case the first argument is an `NSString`, `selectedRange` tells us where to put the cursor relative to the string: in this case after `¨`. The range `replacemenRange` tells us whether the string should replace some of the existing text. In this case no replacement is required.
1. Enter `u`.
1. `hasMarkedText()` is called again.
1. `insertText("ü", replacementRange: NSRange(NSNotFound, 0))` is called to finalize the input. It seems that for the replacement range `(NSNotFound, 0)` we should replace the previously marked text with the final string. So in this case we must first delete `¨` and insert `ü`.

## Korean (Hangul, 한글)

Let's move to a bit more complicated case: Korean. In this case more methods are involved:

* `selectedRange()`: all other additional methods seem to rely on this method. Ideally we should return `NSRange(CursorPosition, 0)` when nothing is selected or `NSRange(SelectionBegin, SelectionLength)` when there's a selection.
* `attributedSubstringForProposedRange(_:actualRange:)`: for entering only Hangul, this method can be ignored.

Let's assume we want to enter `하태원`: (`hasMarkedText()` is called here and there...)

1. `selectedRange()` is called multiple times when changing the input method from US to Korean. This is also the case when starting the app with Korean input selected.
1. Enter `ㅎ`.
1. `setMarkedText("ㅎ", selectedRange: NSRange(1, 0) replacementRange:NSRange(NotFound, 0))` is called.
1. Enter `ㅏ`.
1. `attributedSubstringForProposedRange(_:actualRange:)` and `selectedRange()` are called multiple times: again, for only Hangul, ignorable.
1. `setMarkedText("하", selectedRange: NSRange(1, 0), replacementRange: NSRange(NotFound, 0))` is called: delete `ㅎ` and insert `하`; not yet finalized.
1. Enter `ㅌ`
1. `attributedSubstringForProposedRange(_:actualRange:)` and `selectedRange()` are called multiple times: ignore.
1. `setMarkedText("핱", selectedRange: NSRange(1, 0), replacementRange: NSRange(NotFound, 0))` is called: delete `하` and insert `핱`; not yet finalized.
1. Enter `ㅐ`
1. `attributedSubstringForProposedRange(_:actualRange:)` and `selectedRange()` are called multiple times: ignore.
1. `setMarkedText("하", selectedRange: NSRange(1, 0), replacementRange: NSRange(NotFound, 0))` is called: delete `핱` and insert `하`; not yet finalized.
1. `insertText("하", replacementRange: NSRange(NotFound, 0))` is called to finalize the input of `하`.
1. `attributedSubstringForProposedRange(_:actualRange:)` and `selectedRange()` are called multiple times: ignore.
1. `setMarkedText("태", selectedRange: NSRange(1, 0), replacementRange: NSRange(NotFound, 0))` is called: Since the replacement range is `NotFound`, append the marked text `태` to the freshly finalized `하`.
1. ...

## Hanja (한자)

Let's consider the even more complicated case: Hanja in Korean. In this case the `selectedRange()` and `attributedSubstringForProposedRange(_:actualRange:)` play a vital role and also

* `firstRectForCharacterRange(_:actualRange)`: this method is used to determine where to show the Hanja popup. The character range is determined by `selectedRange()`.

Let's assume we want to enter `河`: (again `hasMarkedText()` is called here and there...)

1. Enter `ㅎ`.
1. `setMarkedText("ㅎ", selectedRange: NSRange(1, 0) replacementRange:NSRange(NotFound, 0))` is called.
1. Enter `ㅏ`.
1. `attributedSubstringForProposedRange(_:actualRange:)`, `selectedRange()` and `hasMarkedText()` are called multiple times: again, for only Hangul, ignorable.
1. `setMarkedText("하", selectedRange: NSRange(1, 0), replacementRange: NSRange(NotFound, 0))` is called: delete `ㅎ` and insert `하`; not yet finalized.
1. Enter `Opt-Return`.
1. `setMarkedText("하", selectedRange: NSRange(1, 0), replacementRange: NSRange(NotFound, 0))` is called again.
1. `selectedRange()` is called: here we should return a range which can be consistently used by `attributedSubstringForProposedRange(_:actualRange)` and `firstRectForCharacterRange(_:actualRange)`.
1. `insertText("하", replacementRange: NSRange(NotFound, 0))` is called even we are not done yet... So our view thinks we finalized the input of `하`.
1. `attributedSubstringForProposedRange(_:actualRange)` is called multiple times to get the Hangul syllable to replace with Hanja. The proposed range can be very different in each call.
1. Only if the range from `selectedRange()` could be somehow consistently used in `attributedSubstringForProposedRange(_:actualRange)`, then the Hanja popup is displayed. Otherwise we get the selector `insertNewlineIgnoringFieldEditor` in `doCommandBySelector()`.
1. `setMarkedText("下" , selectedRange: NSRange(1, 0), replacementRange: NSRange(1, 1))` is called: the replacement range is not `NotFound` which means that we first have to delete the text in the given range, in this case the finalized `하` and then append the marked text.
1. Selecting different Hanja calls the usual `setMarkedText(_:selectedRange:actualRange)` and `Return` finalizes the input of `河`.

## Chinese Pinyin

suppose we want to enter 中国

1. we should enter the pinyin `zhongguo`, then `<Space>` to confirm it.
2. each char input triggers: setMarkedText, markedRange, firstRect, attributedSubstringForProposedRange
3. finally setMarkedText("zhong guo", selectedRange: NSRange(10, 0), replacementRange: NSRange(NotFound, 0)) iscalled:
4. then after `<Space>` enter, insertText("中国", replacementRange: NSRange(NotFound, 0)) is called
5. many selectedRange and attributedSubstring(forProposedRange:actualRange:) calls.

this seems right simple. but when in markedtext state(before confirming it),
1. we can use number to select other candidates
2. we can use `=`, `-`, `<UP>`, `<DOWN>`, `<Left>`, `<Right>` to choose candidate, and vim shouldn't handle it.
3. we can use `<Left>`, `<Right>` to move in marked text, and insert char in middle of markedText. even complicate, the move is not by char, but by word.

each marked text or marked cursor changes, setMarkedText will called, with selectedRange point to the marked cursor position(may be middle, not the text end)

so these key shouldn't be handle by vim directly when in marked text state.

and finally we confirmed all markedtext, then a `insertText` will be called

## Other Writing System

Not a clue, since I only know Latin alphabet and Korean (+Hanja)...


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package emo;

import java.io.Serializable;

/**
 *
 * @author Haitham
 */
public class Variable implements Serializable {

    private String name;

    public Variable(String name) {
        this.name = name;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format(
                "%-6s",
                this.getName());
    }
}


text:
  PIP: PIP-0025
  Title: Quick Sync
  Type: Front-End
  Impact: None - GUI
  Author: Jason Knapp <jmknapp80@gmail.com>
  Comments-URI:
  Status: Active
  Created: 2018/09-26

## Summary

Allow a node that has been offline for a while an option to "Quick Sync".

## Motivation

Installing a fresh node will quickly sync because it downloads the SafeBox from the network. If a node is not fresh and has not synced in a while, the node will download the blockchain files and will take longer to sync. It has been known that deleting the files in the Data folder will force the node to retrieve the latest SafeBox instead of downloading blockchain files. This allows the node to sync quickly.

## Specification

Give the user an option upon startup if they want to Quick Sync after x amount of days. The user can toggle this option and set the x amount of days in the Options Menu. If the user wants to Quick Sync, then the files in the Data folder will be removed and a fresh SafeBox will be downloaded.

## Rationale

A feature of this coin is that it syncs quickly, but if the node has been offline for some time, the sync takes longer. The removal of needing to download the blockchain files could relieve unnecessary network congestion.

## Backwards Compatibility

N/A

## Reference Implementation

N/A

## Links

N/A


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\UiBundle\Registry;

/**
 * @experimental
 */
final class TemplateBlock
{
    /** @var string */
    private $name;

    /** @var string */
    private $eventName;

    /** @var string|null */
    private $template;

    /** @var array|null */
    private $context;

    /** @var int|null */
    private $priority;

    /** @var bool|null */
    private $enabled;

    public function __construct(
        string $name,
        string $eventName,
        ?string $template,
        ?array $context,
        ?int $priority,
        ?bool $enabled
    ) {
        $this->name = $name;
        $this->eventName = $eventName;
        $this->template = $template;
        $this->context = $context;
        $this->priority = $priority;
        $this->enabled = $enabled;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getEventName(): string
    {
        return $this->eventName;
    }

    public function getTemplate(): string
    {
        if ($this->template === null) {
            throw new \DomainException(sprintf(
                'There is no template defined for block "%s" in event "%s".',
                $this->name,
                $this->eventName
            ));
        }

        return $this->template;
    }

    public function getContext(): array
    {
        return $this->context ?? [];
    }

    public function getPriority(): int
    {
        return $this->priority ?? 0;
    }

    public function isEnabled(): bool
    {
        return $this->enabled ?? true;
    }

    public function overwriteWith(self $block): self
    {
        if ($this->name !== $block->name) {
            throw new \DomainException(sprintf(
                'Trying to overwrite block "%s" with block "%s".',
                $this->name,
                $block->name
            ));
        }

        return new self(
            $this->name,
            $block->eventName,
            $block->template ?? $this->template,
            $block->context ?? $this->context,
            $block->priority ?? $this->priority,
            $block->enabled ?? $this->enabled
        );
    }
}


text:
import argparse
import coinach
import csv
import csv_util
import os

_OUTPUT_FILE = "hunt.ts"

def update_german(list, search, replace):
    output = []
    for name in list:
        if search not in name:
            output.append(name)
            continue
        for repl in replace:
            output.append(name.replace(search, repl))
    return output

def parse_data(monsters, notorious, lang, name_map):
    print(f"Processing {lang} hunt names language...")

    for nm_id, nm_info in notorious.items():
        base = nm_info["BNpcBase"]
        rank_id = nm_info["Rank"]
        name_id = nm_info["BNpcName"]
        if not name_id:
            continue

        if name_map is None:
            name = name_id
        else:
            name = name_map[name_id]["Singular"]

        if not name:
            continue

        if lang == "de":
            name = [name.replace("[p]", "")]
            name = update_german(name, "[t]", ["der", "die", "das"])
            name = update_german(name, "[a]", ["e", "er", "es"])
            name = update_german(name, "[A]", ["e", "er", "es"])
            if len(name) == 1:
                name = name[0]

        # SaintCoinach prefaces ids with a comment
        # Other dumps just have the int.
        base = base.replace("BNpcBase#", "")

        if base in ["10422", "13775"]:
            rank = "SS+"
        elif base in ["10755", "13938"]:
            rank = "SS-"
        elif rank_id == "3":
            rank = "S"
        elif rank_id == "2":
            rank = "A"
        else:
            rank = "B"

        if nm_id in monsters:
            assert monsters[nm_id]["id"] == name_id
            assert monsters[nm_id]["rank"] == rank
        else:
            monsters[nm_id] = {"id": name_id, "rank": rank, "name": {}}

        monsters[nm_id]["name"][lang] = name

def update_coinach(monsters, reader):
    notorious_keys = ["#", "BNpcBase", "Rank", "BNpcName"]
    notorious = csv_util.make_map(reader.rawexd("NotoriousMonster"), notorious_keys)

    languages = ["en", "de", "fr", "ja"]
    for locale in languages:
        name_map = csv_util.make_map(reader.exd("BNpcName", lang=locale), ["#", "Singular"])
        parse_data(monsters, notorious, locale, name_map)
    return monsters

def update_raw_csv(monsters, locale):
    notorious_keys = ["#", "BNpcBase", "Rank", "BNpcName"]
    notorious = csv_util.get_locale_table("NotoriousMonster", locale, notorious_keys)
    name_map = csv_util.get_locale_table("BNpcName", locale, ["#", "Singular"])
    parse_data(monsters, notorious, locale, name_map)

def get_from_coinach(_ffxiv_game_path, _saint_conainch_cmd_path, _cactbot_path):
    reader = coinach.CoinachReader(
        coinach_path=_saint_conainch_cmd_path, ffxiv_path=_ffxiv_game_path
    )
    monsters = {}
    update_coinach(monsters, reader)
    update_raw_csv(monsters, "cn")
    update_raw_csv(monsters, "ko")

    all_monsters = {}
    for (_, info) in monsters.items():
        all_monsters[info["name"]["en"]] = info

    writer = coinach.CoinachWriter(cactbot_path=_cactbot_path)

    header = """import { LocaleObject } from '../types/trigger';

type LocaleTextOrArray = LocaleObject<string | string[]>;

export type Rank = 'S' | 'SS+' | 'SS-' | 'A' | 'B';

// Optional values are supported in `Options.CustomMonsters`.
export type HuntEntry = {
  id: string;
  name: LocaleTextOrArray | string | string[];
  rank?: Rank;
  regex?: RegExp;
  hp?: number;
};

export type HuntMap = {
  [huntName: string]: HuntEntry;
};"""

    writer.writeTypeScript(
        filename=os.path.join("resources", _OUTPUT_FILE),
        scriptname=os.path.basename(os.path.abspath(__file__)),
        header=header,
        type="HuntMap",
        as_const=False,
        data=all_monsters,
    )

    print(f"File '{_OUTPUT_FILE}' successfully created.")

if __name__ == "__main__":
    example_usage = r"python .\gen_hunt_data.py -fp 'E:\FINAL FANTASY XIV - A Realm Reborn' -scp 'F:\SaintCoinach\SaintCoinach.Cmd\bin\Release' -cp 'F:\cactbot'"

    parser = argparse.ArgumentParser(
        description="Creates hunt.js for the Radar overlay",
        epilog=example_usage,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument(
        "-fp", "--ffxiv-path", help="Path to FFXIV installation (None == Default location)"
    )
    parser.add_argument(
        "-scp",
        "--saint-coinach-cmd-path",
        help="Path to SaintCoinach.cmd (None == Default location)",
    )
    parser.add_argument("-cp", "--cactbot-path", help="Path to CACTBOT (None == Default location)")

    args = parser.parse_args()
    get_from_coinach(args.ffxiv_path, args.saint_coinach_cmd_path, args.cactbot_path)


text:
from __future__ import unicode_literals
__author__ = 'setten'


text:
import proto  # type: ignore

__protobuf__ = proto.module(
    package="google.ads.googleads.v11.resources",
    marshal="google.ads.googleads.v11",
    manifest={"CustomerLabel",},
)

class CustomerLabel(proto.Message):
    r"""Represents a relationship between a customer and a label.
    This customer may not have access to all the labels attached to
    it. Additional CustomerLabels may be returned by increasing
    permissions with login-customer-id.

    Attributes:
        resource_name (str):
            Immutable. Name of the resource. Customer label resource
            names have the form:
            ``customers/{customer_id}/customerLabels/{label_id}``
        customer (str):
            Output only. The resource name of the
            customer to which the label is attached. Read
            only.

            This field is a member of `oneof`_ ``_customer``.
        label (str):
            Output only. The resource name of the label
            assigned to the customer.
            Note: the Customer ID portion of the label
            resource name is not validated when creating a
            new CustomerLabel.

            This field is a member of `oneof`_ ``_label``.
    """

    resource_name = proto.Field(proto.STRING, number=1,)
    customer = proto.Field(proto.STRING, number=4, optional=True,)
    label = proto.Field(proto.STRING, number=5, optional=True,)

__all__ = tuple(sorted(__protobuf__.manifest))


text:
#ifndef VICE_UIAUTOSTART_H
#define VICE_UIAUTOSTART_H

extern void ui_autostart_settings_dialog(HWND hwnd);

#endif


text:
const int COW_NUM_MAX=100,SMART_MIN=-1000,SMART_MAX=1000;
const int SMART_SUM_MIN=COW_NUM_MAX*SMART_MIN,SMART_SUM_MAX=COW_NUM_MAX*SMART_MAX;
const int SMART_SUM_RANGE=SMART_SUM_MAX-SMART_SUM_MIN+1;

int cowNum,funSumMax[2][SMART_SUM_RANGE],smarts[COW_NUM_MAX],funs[COW_NUM_MAX];

int currentLine=0;
bool legal(int smart){return smart>=SMART_SUM_MIN && smart<=SMART_SUM_MAX;}
int &current(int smart){return funSumMax[currentLine][smart-SMART_SUM_MIN];}
int &prev(int smart){return funSumMax[1-currentLine][smart-SMART_SUM_MIN];}
void swap(){currentLine=1-currentLine;}

int main(){
	for(int i=0;i<2;i++)
		std::fill(funSumMax[i],funSumMax[i]+SMART_SUM_RANGE,INT_MIN);
	current(0)=0;
	scanf("%d",&cowNum);
	int smartSumMax=0,smartSumMin=0;
	for(int i=0;i<cowNum;i++){
		scanf("%d%d",smarts+i,funs+i);
		if(smarts[i]<0)
			smartSumMin+=smarts[i];
		if(smarts[i]>0)
			smartSumMax+=smarts[i];
	}
	for(int i=0;i<cowNum;i++){
		swap();
		for(int smartSum=smartSumMin;smartSum<=smartSumMax;smartSum++){
			current(smartSum)=prev(smartSum);
			if(legal(smartSum-smarts[i]) && prev(smartSum-smarts[i])!=INT_MIN && current(smartSum)<prev(smartSum-smarts[i])+funs[i])
				current(smartSum)=prev(smartSum-smarts[i])+funs[i];
		}
	}
	int sumMax=0;
	for(int smartSum=0;smartSum<=SMART_SUM_MAX;smartSum++)
		if(current(smartSum)>=0 && sumMax<smartSum+current(smartSum))
			sumMax=smartSum+current(smartSum);
	printf("%d\n",sumMax);
	return 0;
}


text:
using System;

using x2net;

namespace hello
{
    public class OutputCase : Case
    {
        protected override void Setup()
        {
            Bind(new HelloResp(), OnHelloResp);
        }

        void OnHelloResp(HelloResp e)
        {
            Console.WriteLine(e.Message);
        }
    }
}


text:
// This is a modified file from the Matrix Template Library. See LICENSE for details.
// Modified 2006, Francis Russell

#include <complex>

/* namespace polution from <sys/sysmacros.h> */
#undef major
#undef minor


text:
namespace Talifun.Commander.Command.Configuration
{
    public delegate void BindToElementEventHandler(object sender, BindToElementEventArgs e);
}


text:
// .NAME vtkHyperTreeCursor - Objects that can traverse hypertree nodes.
// .SECTION Description
// Objects that can traverse hyper3TREE nodes. It is an abstract class.
// Cursors are created by the hyper3TREE.
// .SECTION See Also
// vtkDataObject vtkFieldData vtkHyper3TREEAlgorithm
// .SECTION Thanks
// This class was written by Philippe Pebay, Joachim Pouderoux and Charles Law,
// Kitware 2013
// This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF)

#ifndef vtkHyperTreeCursor_h
#define vtkHyperTreeCursor_h

#include "vtkCommonDataModelModule.h" // For export macro
#include "vtkObject.h"

enum
{
  VTK_3TREE_CHILD_ZMIN_YMIN_XMIN=0,
  VTK_3TREE_CHILD_ZMIN_YMIN_XMAX,
  VTK_3TREE_CHILD_ZMIN_YMAX_XMIN,
  VTK_3TREE_CHILD_ZMIN_YMAX_XMAX,
  VTK_3TREE_CHILD_ZMAX_YMIN_XMIN,
  VTK_3TREE_CHILD_ZMAX_YMIN_XMAX,
  VTK_3TREE_CHILD_ZMAX_YMAX_XMIN,
  VTK_3TREE_CHILD_ZMAX_YMAX_XMAX
};

const int VTK_2TREE_CHILD_SW=VTK_3TREE_CHILD_ZMIN_YMIN_XMIN;
const int VTK_2TREE_CHILD_SE=VTK_3TREE_CHILD_ZMIN_YMIN_XMAX;
const int VTK_2TREE_CHILD_NW=VTK_3TREE_CHILD_ZMIN_YMAX_XMIN;
const int VTK_2TREE_CHILD_NE=VTK_3TREE_CHILD_ZMIN_YMAX_XMAX;

const int VTK_1TREE_TREE_CHILD_LEFT=VTK_2TREE_CHILD_SW;
const int VTK_1TREE_TREE_CHILD_RIGHT=VTK_2TREE_CHILD_SE;

class vtkHyperTree;

class VTKCOMMONDATAMODEL_EXPORT vtkHyperTreeCursor : public vtkObject
{
public:
  vtkTypeMacro(vtkHyperTreeCursor,vtkObject);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Return the HyperTree on which the cursor points to.
  virtual vtkHyperTree* GetTree() = 0;

  // Description:
  // Return the index of the current leaf in the data arrays.
  // \pre is_leaf: IsLeaf()
  virtual vtkIdType GetLeafId() = 0;

  // Description:
  // Return the index of the current node in the data arrays.
  virtual vtkIdType GetNodeId() = 0;

  // Description:
  // Is the node pointed by the cursor a leaf?
  virtual bool IsLeaf() = 0;

  // Are the children of the current node all leaves?
  // This query can be called also on a leaf node.
  // \post compatible: result implies !IsLeaf()
  virtual bool IsTerminalNode() = 0;

  // Description:
  // Is the node pointed by the cursor the root?
  virtual bool IsRoot() = 0;

  // Description:
  // Return the level of the node pointed by the cursor.
  // \post positive_result: result>=0
  virtual int GetCurrentLevel() = 0;

  // Description:
  // Return the child number of the current node relative to its parent.
  // \pre not_root: !IsRoot().
  // \post valid_range: result>=0 && result<GetNumberOfChildren()
  virtual int GetChildIndex() = 0;

  // Description:
  // Move the cursor to the root node.
  // \pre can be root
  // \post is_root: IsRoot()
  virtual void ToRoot() = 0;

  // Description:
  // Move the cursor to the parent of the current node.
  // \pre not_root: !IsRoot()
  virtual void ToParent() = 0;

  // Description:
  // Move the cursor to child `child' of the current node.
  // \pre not_leaf: !IsLeaf()
  // \pre valid_child: child>=0 && child<this->GetNumberOfChildren()
  virtual void ToChild( int child ) = 0;

  // Description:
  // Move the cursor to the same node pointed by `other'.
  // \pre other_exists: other!=0
  // \pre same_hyper3TREE: this->SameTree(other);
  // \post equal: this->IsEqual(other)
  virtual void ToSameNode( vtkHyperTreeCursor* other ) = 0;

  // Description:
  // Is `this' equal to `other'?
  // \pre other_exists: other!=0
  // \pre same_hyper3TREE: this->SameTree(other);
  virtual bool IsEqual( vtkHyperTreeCursor* other ) = 0;

  // Description:
  // Create a copy of `this'.
  // \post results_exists:result!=0
  // \post same_tree: result->SameTree(this)
  virtual vtkHyperTreeCursor* Clone() = 0;

  // Description:
  // Are `this' and `other' pointing on the same hyper3TREE?
  // \pre other_exists: other!=0
  virtual int SameTree( vtkHyperTreeCursor* other ) = 0;

  // Description:
  // Return the index in dimension `d', as if the node was a cell of a
  // uniform grid of 1<<GetCurrentLevel() cells in each dimension.
  // \pre valid_range: d>=0 && d<GetDimension()
  // \post valid_result: result>=0 && result<(1<<GetCurrentLevel())
  virtual int GetIndex( int d ) = 0;

  // Description:
  // Return the number of children for each node of the tree.
  // \post positive_number: result>0
  virtual int GetNumberOfChildren() = 0;

  // Description:
  // Return the dimension of the tree.
  // \post positive_result: result>0
  virtual int GetDimension() = 0;

  // Description:
  // Move to the node described by its indices in each dimension and
  // at a given level. If there is actually a node or a leaf at this
  // location, Found() returns true. Otherwise, Found() returns false and the
  // cursor moves to the closest parent of the query. It can be the root in the
  // worst case.
  // \pre indices_exists: indices!=0
  // \pre valid_size: sizeof(indices)==GetDimension()
  // \pre valid_level: level>=0
  virtual void MoveToNode( int* indices, int level ) = 0;

  // Description
  // Did the last call to MoveToNode succeed?
  virtual bool Found() = 0;

protected:
  // Constructor.
  vtkHyperTreeCursor();
  virtual ~vtkHyperTreeCursor();

private:
  vtkHyperTreeCursor(const vtkHyperTreeCursor&);  // Not implemented.
  void operator=(const vtkHyperTreeCursor&);    // Not implemented.
};
#endif


text:
'use strict';

const mongoose = require('mongoose');
const Residence = require('./residence.js');

const incidentSchema = mongoose.Schema({
  userId: { type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true },
  timeStamp: { type: Date, default: Date.now() },
  type: { type: String, required: true },
  description: { type: String, required: true },
  residenceId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'residence',
    required: true
  },
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'comment', }]
});

incidentSchema.pre('save', function(next) {
  Residence.findById(this.residence)
    .then(() => next())
    .catch(() =>
      next(
        new Error(
          'Validation failed - failed to create Incident, residence does not exist'
        )
      )
    );
});

incidentSchema.post('save', function(doc, next) {
  Residence.findById(doc.residenceId)
    .then(residence => {
      let incidentIDSet = new Set(residence.incidents);
      incidentIDSet.add(this._id.toString());
      residence.incidents = Array.from(incidentIDSet);
      return residence.save();
    })
    .then(() => next())
    .catch(next);
});

module.exports = mongoose.model('incident', incidentSchema);


text:
package io.cattle.platform.core.constants;

public class CommonStatesConstants {

    public static final String CREATED = "created";
    public static final String CREATING = "creating";
    public static final String ACTIVE = "active";
    public static final String INACTIVE = "inactive";
    public static final String ACTIVATING = "activating";
    public static final String DEACTIVATING = "deactivating";
    public static final String PURGED = "purged";
    public static final String PURGING = "purging";
    public static final String REMOVING = "removing";
    public static final String REQUESTED = "requested";
    public static final String REGISTERING = "registering";
    public static final String UPDATING_ACTIVE = "updating-active";
    public static final String REMOVED = "removed";
    public static final String UPDATING_INACTIVE = "updating-inactive";
    public static final String RESTORING = "restoring";
}


text:
// Copyright 2018 The Bazel 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.
package com.google.devtools.build.lib.skyframe;

import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.devtools.build.lib.skyframe.RecursivePackageProviderBackedTargetPatternResolver.MAX_PACKAGES_BULK_GET;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.concurrent.ParallelVisitor;
import com.google.devtools.build.lib.concurrent.ParallelVisitor.UnusedException;
import com.google.devtools.build.lib.concurrent.ThreadSafeBatchCallback;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.RootedPath;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import com.google.devtools.build.skyframe.WalkableGraph;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** Looks up values under {@link TraversalInfo}s of given roots in a {@link WalkableGraph}. */
public class TraversalInfoRootPackageExtractor implements RootPackageExtractor {

  private static final Comparator<TraversalInfo> TRAVERSAL_INFO_COMPARATOR =
      Comparator.comparing(ti -> ti.rootedDir.getRootRelativePath());

  private static final int PACKAGE_ID_OUTPUT_BATCH_SIZE = 100;
  private static final int DEFAULT_THREAD_COUNT = Runtime.getRuntime().availableProcessors();

  @Override
  public void streamPackagesFromRoots(
      ThreadSafeBatchCallback<PackageIdentifier, UnusedException> results,
      WalkableGraph graph,
      List<Root> roots,
      ExtendedEventHandler eventHandler,
      RepositoryName repository,
      PathFragment directory,
      ImmutableSet<PathFragment> blacklistedSubdirectories,
      ImmutableSet<PathFragment> excludedSubdirectories)
      throws InterruptedException {
    TreeSet<TraversalInfo> dirsToCheckForPackages = new TreeSet<>(TRAVERSAL_INFO_COMPARATOR);
    for (Root root : roots) {
      RootedPath rootedDir = RootedPath.toRootedPath(root, directory);
      dirsToCheckForPackages.add(
          new TraversalInfo(rootedDir, blacklistedSubdirectories, excludedSubdirectories));
    }
    PackageCollectingParallelVisitor visitor =
        new PackageCollectingParallelVisitor(
            results,
            /*visitBatchSize=*/ MAX_PACKAGES_BULK_GET,
            /*processResultsBatchSize=*/ PACKAGE_ID_OUTPUT_BATCH_SIZE,
            /*minPendingTasks=*/ 3 * DEFAULT_THREAD_COUNT,
            /*resultBatchSize=*/ PACKAGE_ID_OUTPUT_BATCH_SIZE,
            eventHandler,
            repository,
            graph);
    visitor.visitAndWaitForCompletion(dirsToCheckForPackages);
  }

  private static final ExecutorService PACKAGE_ID_COLLECTING_EXECUTOR =
      Executors.newFixedThreadPool(
          /*numThreads=*/ DEFAULT_THREAD_COUNT,
          new ThreadFactoryBuilder().setNameFormat("package-id-traversal-%d").build());

  /**
   * A ParallelVisitor that reports every {@link PackageIdentifier} by querying the WalkableGraph
   * for a {@link CollectPackagesUnderDirectoryValue} for each {@link TraversalInfo} it visits.
   */
  static class PackageCollectingParallelVisitor
      extends ParallelVisitor<
          TraversalInfo,
          TraversalInfo,
          TraversalInfo,
          PackageIdentifier,
          UnusedException,
          ThreadSafeBatchCallback<PackageIdentifier, UnusedException>> {

    private final ExtendedEventHandler eventHandler;
    private final RepositoryName repository;
    private final WalkableGraph graph;

    PackageCollectingParallelVisitor(
        ThreadSafeBatchCallback<PackageIdentifier, UnusedException> callback,
        int visitBatchSize,
        int processResultsBatchSize,
        int minPendingTasks,
        int resultBatchSize,
        ExtendedEventHandler eventHandler,
        RepositoryName repository,
        WalkableGraph graph) {
      super(
          callback,
          UnusedException.class,
          visitBatchSize,
          processResultsBatchSize,
          minPendingTasks,
          resultBatchSize,
          PACKAGE_ID_COLLECTING_EXECUTOR);
      this.eventHandler = eventHandler;
      this.repository = repository;
      this.graph = graph;
    }

    @Override
    protected Iterable<PackageIdentifier> outputKeysToOutputValues(
        Iterable<TraversalInfo> targetKeys) {
      ImmutableList.Builder<PackageIdentifier> results =
          ImmutableList.builderWithExpectedSize(resultBatchSize);
      for (TraversalInfo resultInfo : targetKeys) {
        results.add(
            PackageIdentifier.create(repository, resultInfo.rootedDir.getRootRelativePath()));
      }
      return results.build();
    }

    @Override
    protected Visit getVisitResult(Iterable<TraversalInfo> dirsToCheckForPackages)
        throws InterruptedException {
      ImmutableMap.Builder<TraversalInfo, SkyKey> traversalToKeyMapBuilder = ImmutableMap.builder();
      for (TraversalInfo traversalInfo : dirsToCheckForPackages) {
        traversalToKeyMapBuilder.put(
            traversalInfo,
            CollectPackagesUnderDirectoryValue.key(
                repository, traversalInfo.rootedDir, traversalInfo.blacklistedSubdirectories));
      }
      ImmutableMap<TraversalInfo, SkyKey> traversalToKeyMap = traversalToKeyMapBuilder.build();
      Map<SkyKey, SkyValue> values = graph.getSuccessfulValues(traversalToKeyMap.values());

      // NOTE: Use a TreeSet to ensure a deterministic (sorted) iteration order when we recurse.
      List<TraversalInfo> resultPackageIds = new ArrayList<>();
      TreeSet<TraversalInfo> subdirsToCheckForPackages = new TreeSet<>(TRAVERSAL_INFO_COMPARATOR);
      for (Map.Entry<TraversalInfo, SkyKey> entry : traversalToKeyMap.entrySet()) {
        TraversalInfo info = entry.getKey();
        SkyKey key = entry.getValue();
        SkyValue val = values.get(key);
        CollectPackagesUnderDirectoryValue collectPackagesValue =
            (CollectPackagesUnderDirectoryValue) val;
        if (collectPackagesValue != null) {
          if (collectPackagesValue.isDirectoryPackage()) {
            resultPackageIds.add(info);
          }

          if (collectPackagesValue.getErrorMessage() != null) {
            eventHandler.handle(Event.error(collectPackagesValue.getErrorMessage()));
          }

          ImmutableMap<RootedPath, Boolean> subdirectoryTransitivelyContainsPackages =
              collectPackagesValue.getSubdirectoryTransitivelyContainsPackagesOrErrors();
          for (RootedPath subdirectory : subdirectoryTransitivelyContainsPackages.keySet()) {
            if (subdirectoryTransitivelyContainsPackages.get(subdirectory)) {
              PathFragment subdirectoryRelativePath = subdirectory.getRootRelativePath();
              ImmutableSet<PathFragment> blacklistedSubdirectoriesBeneathThisSubdirectory =
                  info.blacklistedSubdirectories.stream()
                      .filter(pathFragment -> pathFragment.startsWith(subdirectoryRelativePath))
                      .collect(toImmutableSet());
              ImmutableSet<PathFragment> excludedSubdirectoriesBeneathThisSubdirectory =
                  info.excludedSubdirectories.stream()
                      .filter(pathFragment -> pathFragment.startsWith(subdirectoryRelativePath))
                      .collect(toImmutableSet());
              if (!excludedSubdirectoriesBeneathThisSubdirectory.contains(
                  subdirectoryRelativePath)) {
                subdirsToCheckForPackages.add(
                    new TraversalInfo(
                        subdirectory,
                        blacklistedSubdirectoriesBeneathThisSubdirectory,
                        excludedSubdirectoriesBeneathThisSubdirectory));
              }
            }
          }
        }
      }
      return new Visit(
          /*keysToUseForResult=*/ resultPackageIds, /*keysToVisit=*/ subdirsToCheckForPackages);
    }

    @Override
    protected Iterable<TraversalInfo> preprocessInitialVisit(Iterable<TraversalInfo> infos) {
      return infos;
    }

    @Override
    protected Iterable<TraversalInfo> noteAndReturnUniqueVisitationKeys(
        Iterable<TraversalInfo> prospectiveVisitationKeys) {
      return prospectiveVisitationKeys;
    }
  }

  /** Value type used as visitation and output key for {@link PackageCollectingParallelVisitor}. */
  private static final class TraversalInfo {
    final RootedPath rootedDir;
    // Set of blacklisted directories. The graph is assumed to be prepopulated with
    // CollectPackagesUnderDirectoryValue nodes whose keys have blacklisted packages embedded in
    // them. Therefore, we need to be careful to request and use the same sort of keys here in our
    // traversal.
    final ImmutableSet<PathFragment> blacklistedSubdirectories;
    // Set of directories, targets under which should be excluded from the traversal results.
    // Excluded directory information isn't part of the graph keys in the prepopulated graph, so we
    // need to perform the filtering ourselves.
    final ImmutableSet<PathFragment> excludedSubdirectories;

    private TraversalInfo(
        RootedPath rootedDir,
        ImmutableSet<PathFragment> blacklistedSubdirectories,
        ImmutableSet<PathFragment> excludedSubdirectories) {
      this.rootedDir = rootedDir;
      this.blacklistedSubdirectories = blacklistedSubdirectories;
      this.excludedSubdirectories = excludedSubdirectories;
    }

    @Override
    public int hashCode() {
      return Objects.hashCode(rootedDir, blacklistedSubdirectories, excludedSubdirectories);
    }

    @Override
    public boolean equals(Object obj) {
      if (this == obj) {
        return true;
      }
      if (obj instanceof TraversalInfo) {
        TraversalInfo otherTraversal = (TraversalInfo) obj;
        return Objects.equal(rootedDir, otherTraversal.rootedDir)
            && Objects.equal(blacklistedSubdirectories, otherTraversal.blacklistedSubdirectories)
            && Objects.equal(excludedSubdirectories, otherTraversal.excludedSubdirectories);
      }
      return false;
    }
  }
}