text:
<?php

namespace Drupal\Tests\update\Functional;

use Drupal\Core\Url;

/**
 * Tests the Update Manager module through a series of functional tests using
 * mock XML data.
 *
 * @group update
 */
class UpdateSemverCoreTest extends UpdateSemverTestBase {

  /**
   * {@inheritdoc}
   */
  protected $updateTableLocator = 'table.update';

  /**
   * {@inheritdoc}
   */
  protected $updateProject = 'drupal';

  /**
   * {@inheritdoc}
   */
  protected $projectTitle = 'Drupal';

  /**
   * Sets the version to x.x.x when no project-specific mapping is defined.
   *
   * @param string $version
   *   The version.
   */
  protected function setProjectInstalledVersion($version) {
    $setting = [
      '#all' => [
        'version' => $version,
      ],
    ];
    $this->config('update_test.settings')->set('system_info', $setting)->save();
  }

  /**
   * Tests the security coverage messages for Drupal core versions.
   *
   * @param string $installed_version
   *   The installed Drupal version to test.
   * @param string $fixture
   *   The test fixture that contains the test XML.
   * @param string $requirements_section_heading
   *   The requirements section heading.
   * @param string $message
   *   The expected coverage message.
   * @param string $mock_date
   *   The mock date to use if needed in the format CCYY-MM-DD. If an empty
   *   string is provided, no mock date will be used.
   *
   * @dataProvider securityCoverageMessageProvider
   */
  public function testSecurityCoverageMessage($installed_version, $fixture, $requirements_section_heading, $message, $mock_date) {
    \Drupal::state()->set('update_test.mock_date', $mock_date);
    $this->setProjectInstalledVersion($installed_version);
    $this->refreshUpdateStatus(['drupal' => $fixture]);
    $this->drupalGet('admin/reports/status');

    if (empty($requirements_section_heading)) {
      $this->assertSession()->pageTextNotContains('Drupal core security coverage');
      return;
    }

    $all_requirements_details = $this->getSession()->getPage()->findAll(
      'css',
      'details.system-status-report__entry:contains("Drupal core security coverage")'
    );
    // Ensure we only have 1 security message section.
    $this->assertCount(1, $all_requirements_details);
    $requirements_details = $all_requirements_details[0];
    // Ensure that messages are under the correct heading which could be
    // 'Checked', 'Warnings found', or 'Errors found'.
    $requirements_section_element = $requirements_details->getParent();
    $this->assertCount(1, $requirements_section_element->findAll('css', "h3:contains('$requirements_section_heading')"));
    $actual_message = $requirements_details->find('css', 'div.system-status-report__entry__value')->getText();
    $this->assertNotEmpty($actual_message);
    $this->assertEquals($message, $actual_message);
  }

  /**
   * Data provider for testSecurityCoverageMessage().
   *
   * These test cases rely on the following fixtures containing the following
   * releases:
   * - drupal.sec.2.0_3.0-rc1.xml
   *   - 8.2.0
   *   - 8.3.0-rc1
   * - drupal.sec.2.0.xml
   *   - 8.2.0
   * - drupal.sec.2.0_9.0.0.xml
   *   - 8.2.0
   *   - 9.0.0
   * - drupal.sec.9.5.0.xml
   *   - 9.4.0
   *   - 9.5.0
   * - drupal.sec.10.5.0.xml
   *   - 10.4.0
   *   - 10.5.0
   */
  public function securityCoverageMessageProvider() {
    $release_coverage_message = 'Visit the release cycle overview for more information on supported releases.';
    $coverage_ended_message = 'Coverage has ended';
    $update_asap_message = 'Update to a supported minor as soon as possible to continue receiving security updates.';
    $update_soon_message = 'Update to a supported minor version soon to continue receiving security updates.';
    $test_cases = [
      '8.0.0, unsupported' => [
        'installed_version' => '8.0.0',
        'fixture' => 'sec.2.0_3.0-rc1',
        'requirements_section_heading' => 'Errors found',
        'message' => "$coverage_ended_message $update_asap_message $release_coverage_message",
        'mock_date' => '',
      ],
      '8.1.0, supported with 3rc' => [
        'installed_version' => '8.1.0',
        'fixture' => 'sec.2.0_3.0-rc1',
        'requirements_section_heading' => 'Warnings found',
        'message' => "Covered until 8.3.0 Update to 8.2 or higher soon to continue receiving security updates. $release_coverage_message",
        'mock_date' => '',
      ],
      '8.1.0, supported' => [
        'installed_version' => '8.1.0',
        'fixture' => 'sec.2.0',
        'requirements_section_heading' => 'Warnings found',
        'message' => "Covered until 8.3.0 Update to 8.2 or higher soon to continue receiving security updates. $release_coverage_message",
        'mock_date' => '',
      ],
      '8.2.0, supported with 3rc' => [
        'installed_version' => '8.2.0',
        'fixture' => 'sec.2.0_3.0-rc1',
        'requirements_section_heading' => 'Checked',
        'message' => "Covered until 8.4.0 $release_coverage_message",
        'mock_date' => '',
      ],
      '8.2.0, supported' => [
        'installed_version' => '8.2.0',
        'fixture' => 'sec.2.0',
        'requirements_section_heading' => 'Checked',
        'message' => "Covered until 8.4.0 $release_coverage_message",
        'mock_date' => '',
      ],
      // Ensure we don't show messages for pre-release or dev versions.
      '8.2.0-beta2, no message' => [
        'installed_version' => '8.2.0-beta2',
        'fixture' => 'sec.2.0_3.0-rc1',
        'requirements_section_heading' => '',
        'message' => '',
        'mock_date' => '',
      ],
      '8.1.0-dev, no message' => [
        'installed_version' => '8.1.0-dev',
        'fixture' => 'sec.2.0_3.0-rc1',
        'requirements_section_heading' => '',
        'message' => '',
        'mock_date' => '',
      ],
      // Ensures the message is correct if the next major version has been
      // released and the additional minors indicated by
      // CORE_MINORS_WITH_SECURITY_COVERAGE minors have been released.
      '8.0.0, 9 unsupported' => [
        'installed_version' => '8.0.0',
        'fixture' => 'sec.2.0_9.0.0',
        'requirements_section_heading' => 'Errors found',
        'message' => "$coverage_ended_message $update_asap_message $release_coverage_message",
        'mock_date' => '',
      ],
      // Ensures the message is correct if the next major version has been
      // released and the additional minors indicated by
      // CORE_MINORS_WITH_SECURITY_COVERAGE minors have not been released.
      '8.2.0, 9 warning' => [
        'installed_version' => '8.2.0',
        'fixture' => 'sec.2.0_9.0.0',
        'requirements_section_heading' => 'Warnings found',
        'message' => "Covered until 8.4.0 Update to 8.3 or higher soon to continue receiving security updates. $release_coverage_message",
        'mock_date' => '',
      ],
    ];

    // Drupal 9.4.x test cases.
    $test_cases += [
      // Ensure that a message is displayed during 9.4's active support.
      '9.4.0, supported' => [
        'installed_version' => '9.4.0',
        'fixture' => 'sec.9.5.0',
        'requirements_section_heading' => 'Checked',
        'message' => "Covered until 2023-Jun-21 $release_coverage_message",
        'mock_date' => '2022-12-13',
      ],
      // Ensure a warning is displayed if less than six months remain until the
      // end of 9.4's security coverage.
      '9.4.0, supported, 6 months warn' => [
        'installed_version' => '9.4.0',
        'fixture' => 'sec.9.5.0',
        'requirements_section_heading' => 'Warnings found',
        'message' => "Covered until 2023-Jun-21 $update_soon_message $release_coverage_message",
        'mock_date' => '2022-12-14',
      ],
    ];
    // Ensure that the message does not change, including on the last day of
    // security coverage.
    $test_cases['9.4.0, supported, last day warn'] = $test_cases['9.4.0, supported, 6 months warn'];
    $test_cases['9.4.0, supported, last day warn']['mock_date'] = '2023-06-20';

    // Ensure that if the 9.4 support window is finished a message is
    // displayed.
    $test_cases['9.4.0, support over'] = [
      'installed_version' => '9.4.0',
      'fixture' => 'sec.9.5.0',
      'requirements_section_heading' => 'Errors found',
      'message' => "$coverage_ended_message $update_asap_message $release_coverage_message",
      'mock_date' => '2023-06-22',
    ];

    // Drupal 9.5 test cases.
    $test_cases['9.5.0, supported'] = [
      'installed_version' => '9.5.0',
      'fixture' => 'sec.9.5.0',
      'requirements_section_heading' => 'Checked',
      'message' => "Covered until 2023-Nov $release_coverage_message",
      'mock_date' => '2023-01-01',
    ];
    // Ensure a warning is displayed if less than six months remain until the
    // end of 9.5's security coverage.
    $test_cases['9.5.0, supported, 6 months warn'] = [
      'installed_version' => '9.5.0',
      'fixture' => 'sec.9.5.0',
      'requirements_section_heading' => 'Warnings found',
      'message' => "Covered until 2023-Nov $update_soon_message $release_coverage_message",
      'mock_date' => '2023-05-15',
    ];

    // Ensure that the message does not change, including on the last day of
    // security coverage.
    $test_cases['9.5.0, supported, last day warn'] = $test_cases['9.5.0, supported, 6 months warn'];
    $test_cases['9.5.0, supported, last day warn']['mock_date'] = '2023-10-31';

    // Ensure that if the support window is finished a message is displayed.
    $test_cases['9.5.0, support over'] = [
      'installed_version' => '9.5.0',
      'fixture' => 'sec.9.5.0',
      'requirements_section_heading' => 'Errors found',
      'message' => "$coverage_ended_message $update_asap_message $release_coverage_message",
      'mock_date' => '2023-11-01',
    ];

    // Drupal 9 test cases.
    $test_cases += [
      // Ensure the end dates for 9.4 and 9.5 only apply to major version 9.
      '10.5.0' => [
        'installed_version' => '10.5.0',
        'fixture' => 'sec.10.5.0',
        'requirements_section_heading' => 'Checked',
        'message' => "Covered until 10.7.0 $release_coverage_message",
        'mock_date' => '',
      ],
      '10.4.0' => [
        'installed_version' => '10.4.0',
        'fixture' => 'sec.10.5.0',
        'requirements_section_heading' => 'Warnings found',
        'message' => "Covered until 10.6.0 Update to 10.5 or higher soon to continue receiving security updates. $release_coverage_message",
        'mock_date' => '',
      ],
    ];
    return $test_cases;

  }

  /**
   * Ensures proper results where there are date mismatches among modules.
   */
  public function testDatestampMismatch() {
    $system_info = [
      '#all' => [
        // We need to think we're running a -dev snapshot to see dates.
        'version' => '8.1.0-dev',
        'datestamp' => time(),
      ],
      'block' => [
        // This is 2001-09-09 01:46:40 GMT, so test for "2001-Sep-".
        'datestamp' => '1000000000',
      ],
    ];
    $this->config('update_test.settings')->set('system_info', $system_info)->save();
    $this->refreshUpdateStatus(['drupal' => 'dev']);
    $this->assertSession()->pageTextNotContains('2001-Sep-');
    $this->assertSession()->pageTextContains('Up to date');
    $this->assertSession()->pageTextNotContains('Update available');
    $this->assertSession()->pageTextNotContains('Security update required!');
  }

  /**
   * Checks that running cron updates the list of available updates.
   */
  public function testModulePageRunCron() {
    $this->setProjectInstalledVersion('8.0.0');
    $this->config('update.settings')
      ->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
      ->save();
    $this->config('update_test.settings')
      ->set('xml_map', ['drupal' => '0.0'])
      ->save();

    $this->cronRun();
    $this->drupalGet('admin/modules');
    $this->assertSession()->pageTextNotContains('No update information available.');
  }

  /**
   * Checks that clearing the disk cache works.
   */
  public function testClearDiskCache() {
    $directories = [
      _update_manager_cache_directory(FALSE),
      _update_manager_extract_directory(FALSE),
    ];
    // Check that update directories does not exists.
    foreach ($directories as $directory) {
      $this->assertDirectoryDoesNotExist($directory);
    }

    // Method must not fail if update directories do not exists.
    update_clear_update_disk_cache();
  }

  /**
   * Checks the messages at admin/modules when the site is up to date.
   */
  public function testModulePageUpToDate() {
    $this->setProjectInstalledVersion('8.0.0');
    // Instead of using refreshUpdateStatus(), set these manually.
    $this->config('update.settings')
      ->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
      ->save();
    $this->config('update_test.settings')
      ->set('xml_map', ['drupal' => '0.0'])
      ->save();

    $this->drupalGet('admin/reports/updates');
    $this->clickLink('Check manually');
    $this->checkForMetaRefresh();
    $this->assertSession()->pageTextContains('Checked available update data for one project.');
    $this->drupalGet('admin/modules');
    $this->assertSession()->pageTextNotContains('There are updates available for your version of Drupal.');
    $this->assertSession()->pageTextNotContains('There is a security update available for your version of Drupal.');
  }

  /**
   * Checks the messages at admin/modules when an update is missing.
   */
  public function testModulePageRegularUpdate() {
    $this->drupalLogin($this->drupalCreateUser([
      'administer site configuration',
      'administer modules',
      'view update notifications',
    ]));
    $this->setProjectInstalledVersion('8.0.0');
    // Instead of using refreshUpdateStatus(), set these manually.
    $this->config('update.settings')
      ->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
      ->save();
    $this->config('update_test.settings')
      ->set('xml_map', ['drupal' => '0.1'])
      ->save();

    $this->drupalGet('admin/reports/updates');
    $this->clickLink('Check manually');
    $this->checkForMetaRefresh();
    $this->assertSession()->pageTextContains('Checked available update data for one project.');
    $this->drupalGet('admin/modules');
    $this->assertSession()->pageTextContains('There are updates available for your version of Drupal.');
    $this->assertSession()->pageTextNotContains('There is a security update available for your version of Drupal.');

    // A user without the "view update notifications" permission shouldn't be
    // notified about available updates.
    $this->drupalLogin($this->drupalCreateUser([
      'administer site configuration',
      'administer modules',
    ]));
    $this->drupalGet('admin/modules');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextNotContains('There are updates available for your version of Drupal.');
  }

  /**
   * Checks the messages at admin/modules when a security update is missing.
   */
  public function testModulePageSecurityUpdate() {
    $this->drupalLogin($this->drupalCreateUser([
      'administer site configuration',
      'administer modules',
      'administer themes',
      'view update notifications',
    ]));
    $this->setProjectInstalledVersion('8.0.0');
    // Instead of using refreshUpdateStatus(), set these manually.
    $this->config('update.settings')
      ->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
      ->save();
    $this->config('update_test.settings')
      ->set('xml_map', ['drupal' => 'sec.0.2'])
      ->save();

    $this->drupalGet('admin/reports/updates');
    $this->clickLink('Check manually');
    $this->checkForMetaRefresh();
    $this->assertSession()->pageTextContains('Checked available update data for one project.');
    $this->drupalGet('admin/modules');
    $this->assertSession()->pageTextNotContains('There are updates available for your version of Drupal.');
    $this->assertSession()->pageTextContains('There is a security update available for your version of Drupal.');

    // Make sure admin/appearance warns you you're missing a security update.
    $this->drupalGet('admin/appearance');
    $this->assertSession()->pageTextNotContains('There are updates available for your version of Drupal.');
    $this->assertSession()->pageTextContains('There is a security update available for your version of Drupal.');

    // Make sure duplicate messages don't appear on Update status pages.
    $this->drupalGet('admin/reports/status');
    $this->assertSession()->pageTextContainsOnce('There is a security update available for your version of Drupal.');

    $this->drupalGet('admin/reports/updates');
    $this->assertSession()->pageTextNotContains('There is a security update available for your version of Drupal.');

    $this->drupalGet('admin/reports/updates/settings');
    $this->assertSession()->pageTextNotContains('There is a security update available for your version of Drupal.');
  }

  /**
   * Tests the Update Manager module when the update server returns 503 errors.
   */
  public function testServiceUnavailable() {
    $this->refreshUpdateStatus([], '503-error');
    // Ensure that no "Warning: SimpleXMLElement..." parse errors are found.
    $this->assertSession()->pageTextNotContains('SimpleXMLElement');
    $this->assertSession()->pageTextContainsOnce('Failed to get available update data for one project.');
  }

  /**
   * Tests that exactly one fetch task per project is created and not more.
   */
  public function testFetchTasks() {
    $projecta = [
      'name' => 'aaa_update_test',
    ];
    $projectb = [
      'name' => 'bbb_update_test',
    ];
    $queue = \Drupal::queue('update_fetch_tasks');
    $this->assertEquals(0, $queue->numberOfItems(), 'Queue is empty');
    update_create_fetch_task($projecta);
    $this->assertEquals(1, $queue->numberOfItems(), 'Queue contains one item');
    update_create_fetch_task($projectb);
    $this->assertEquals(2, $queue->numberOfItems(), 'Queue contains two items');
    // Try to add a project again.
    update_create_fetch_task($projecta);
    $this->assertEquals(2, $queue->numberOfItems(), 'Queue still contains two items');

    // Clear storage and try again.
    update_storage_clear();
    update_create_fetch_task($projecta);
    $this->assertEquals(2, $queue->numberOfItems(), 'Queue contains two items');
  }

  /**
   * Checks language module in core package at admin/reports/updates.
   */
  public function testLanguageModuleUpdate() {
    $this->setProjectInstalledVersion('8.0.0');
    // Instead of using refreshUpdateStatus(), set these manually.
    $this->config('update.settings')
      ->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
      ->save();
    $this->config('update_test.settings')
      ->set('xml_map', ['drupal' => '0.1'])
      ->save();

    $this->drupalGet('admin/reports/updates');
    $this->assertSession()->pageTextContains('Language');
  }

  /**
   * Ensures that the local actions appear.
   */
  public function testLocalActions() {
    $admin_user = $this->drupalCreateUser([
      'administer site configuration',
      'administer modules',
      'administer software updates',
      'administer themes',
    ]);
    $this->drupalLogin($admin_user);

    $this->drupalGet('admin/modules');
    $this->clickLink('Add new module');
    $this->assertSession()->addressEquals('admin/modules/install');

    $this->drupalGet('admin/appearance');
    $this->clickLink('Add new theme');
    $this->assertSession()->addressEquals('admin/theme/install');

    $this->drupalGet('admin/reports/updates');
    $this->clickLink('Add new module or theme');
    $this->assertSession()->addressEquals('admin/reports/updates/install');
  }

  /**
   * Checks that Drupal recovers after problems connecting to update server.
   */
  public function testBrokenThenFixedUpdates() {
    $this->drupalLogin($this->drupalCreateUser([
      'administer site configuration',
      'view update notifications',
      'access administration pages',
    ]));
    $this->setProjectInstalledVersion('8.0.0');
    // Instead of using refreshUpdateStatus(), set these manually.
    $this->config('update.settings')
      ->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
      ->save();
    // Use update XML that has no information to simulate a broken response from
    // the update server.
    $this->config('update_test.settings')
      ->set('xml_map', ['drupal' => 'broken'])
      ->save();

    // This will retrieve broken updates.
    $this->cronRun();
    $this->drupalGet('admin/reports/status');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains('There was a problem checking available updates for Drupal.');
    $this->config('update_test.settings')
      ->set('xml_map', ['drupal' => 'sec.0.2'])
      ->save();
    // Simulate the update_available_releases state expiring before cron is run
    // and the state is used by \Drupal\update\UpdateManager::getProjects().
    \Drupal::keyValueExpirable('update_available_releases')->deleteAll();
    // This cron run should retrieve fixed updates.
    $this->cronRun();
    $this->drupalGet('admin/structure');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains('There is a security update available for your version of Drupal.');
  }

}


text:
var InputMask = function ( opts ) {
  if ( opts && opts.masked ) {
    // Make it easy to wrap this plugin and pass elements instead of a selector
    opts.masked = typeof opts.masked === string ? document.querySelectorAll( opts.masked ) : opts.masked;
  }

  if ( opts ) {
    this.opts = {
      masked: opts.masked || document.querySelectorAll( this.d.masked ),
      mNum: opts.mNum || this.d.mNum,
      mChar: opts.mChar || this.d.mChar,
      error: opts.onError || this.d.onError
    }
  } else {
    this.opts = this.d;
    this.opts.masked = document.querySelectorAll( this.opts.masked );
  }

  this.refresh( true );
};

var inputMask = {

  // Default Values
  d: {
    masked : '.masked',
    mNum : 'XdDmMyY9',
    mChar : '_',
    onError: function(){}
  },

  refresh: function(init) {
    var t, parentClass;

    if ( !init ) {
      this.opts.masked = document.querySelectorAll( this.opts.masked );
    }

    for(i = 0; i < this.opts.masked.length; i++) {
      t = this.opts.masked[i]
      parentClass = t.parentNode.getAttribute('class');

      if ( !parentClass || ( parentClass && parentClass.indexOf('shell') === -1 ) ) {
        this.createShell(t);
        this.activateMasking(t);
      }
    }
  },

  // replaces each masked t with a shall containing the t and it's mask.
  createShell : function (t) {
    var wrap = document.createElement('span'),
        mask = document.createElement('span'),
        emphasis = document.createElement('i'),
        tClass = t.getAttribute('class'),
        pTxt = t.getAttribute('placeholder'),
        placeholder = document.createTextNode(pTxt);

    t.setAttribute('maxlength', placeholder.length);
    t.setAttribute('data-placeholder', pTxt);
    t.removeAttribute('placeholder');

    if ( !tClass || ( tClass && tClass.indexOf('masked') === -1 ) ) {
      t.setAttribute( 'class', tClass + ' masked');
    }

    mask.setAttribute('aria-hidden', 'true');
    mask.setAttribute('id', t.getAttribute('id') + 'Mask');
    mask.appendChild(emphasis);
    mask.appendChild(placeholder);

    wrap.setAttribute('class', 'shell');
    wrap.appendChild(mask);
    t.parentNode.insertBefore( wrap, t );
    wrap.appendChild(t);
  },

  setValueOfMask : function (e) {
    var value = e.target.value,
        placeholder = e.target.getAttribute('data-placeholder');

    return "<i>" + value + "</i>" + placeholder.substr(value.length);
  },

  // add event listeners
  activateMasking : function (t) {
    var that = this;
    if (t.addEventListener) { // remove "if" after death of IE 8
      t.addEventListener('keyup', function(e) {
        that.handleValueChange.call(that,e);
      }, false);
    } else if (t.attachEvent) { // For IE 8
        t.attachEvent('onkeyup', function(e) {
        e.target = e.srcElement;
        that.handleValueChange.call(that, e);
      });
    }
  },

  handleValueChange : function (e) {
    var id = e.target.getAttribute('id');

    if(e.target.value == document.querySelector('#' + id + 'Mask i').innerHTML) {
      return; // Continue only if value hasn't changed
    }

    document.getElementById(id).value = this.handleCurrentValue(e);
    document.getElementById(id + 'Mask').innerHTML = this.setValueOfMask(e);

  },

  handleCurrentValue : function (e) {
    var isCharsetPresent = e.target.getAttribute('data-charset'),
        placeholder = isCharsetPresent || e.target.getAttribute('data-placeholder'),
        value = e.target.value, l = placeholder.length, newValue = '',
        i, j, isInt, isLetter, strippedValue;

    // strip special characters
    strippedValue = isCharsetPresent ? value.replace(/\W/g, "") : value.replace(/\D/g, "");

    for (i = 0, j = 0; i < l; i++) {
        isInt = !isNaN(parseInt(strippedValue[j]));
        isLetter = strippedValue[j] ? strippedValue[j].match(/[A-Z]/i) : false;
        matchesNumber = this.opts.mNum.indexOf(placeholder[i]) >= 0;
        matchesLetter = this.opts.mChar.indexOf(placeholder[i]) >= 0;
        if ((matchesNumber && isInt) || (isCharsetPresent && matchesLetter && isLetter)) {
                newValue += strippedValue[j++];
          } else if ((!isCharsetPresent && !isInt && matchesNumber) || (isCharsetPresent && ((matchesLetter && !isLetter) || (matchesNumber && !isInt)))) {
                //this.opts.onError( e ); // write your own error handling function
                return newValue;
        } else {
            newValue += placeholder[i];
        }
        // break if no characters left and the pattern is non-special character
        if (strippedValue[j] == undefined) {
          break;
        }
    }
    if (e.target.getAttribute('data-valid-example')) {
      return this.validateProgress(e, newValue);
    }
    return newValue;
  },

  validateProgress : function (e, value) {
    var validExample = e.target.getAttribute('data-valid-example'),
        pattern = new RegExp(e.target.getAttribute('pattern')),
        placeholder = e.target.getAttribute('data-placeholder'),
        l = value.length, testValue = '';

    //convert to months
    if (l == 1 && placeholder.toUpperCase().substr(0,2) == 'MM') {
      if(value > 1 && value < 10) {
        value = '0' + value;
      }
      return value;
    }
    // test the value, removing the last character, until what you have is a submatch
    for ( i = l; i >= 0; i--) {
      testValue = value + validExample.substr(value.length);
      if (pattern.test(testValue)) {
        return value;
      } else {
        value = value.substr(0, value.length-1);
      }
    }

    return value;
  }
};

for ( var property in inputMask ) {
  if (inputMask.hasOwnProperty(property)) {
    InputMask.prototype[ property ] = inputMask[ property ];
  }
}

//  Declaritive initalization
(function(){
  var scripts = document.getElementsByTagName('script'),
      script = scripts[ scripts.length - 1 ];
  if ( script.getAttribute('data-autoinit') ) {
    new InputMask();
  }
})();

redpajama_set_name: RedPajamaGithub


text:
These are the configuration files that I use in my daily setup.

You can install using GNU Stow or by adjusting `HELPERS_DIR` in the
preferred config file and then sourcing it.

For a new Mac:
* Download XCode and command line tools if necessary
* Run `mac-setup/setup-dev.sh`.

Released under the MIT license (see `LICENSE`).

## Add-ons after setup

* [Adblock Plus Chrome Extension](https://adblockplus.org/)
* [Source Code Pro font](https://github.com/adobe-fonts/source-code-pro)
* Sublime Text
  * [Solarized](https://github.com/SublimeColors/Solarized)
  * [Package Control](https://sublime.wbond.net/installation)
* iTerm 2
  * [Solarized](https://github.com/altercation/solarized/tree/master/iterm2-colors-solarized)
  * Disable "Draw bold text in bright colors" in Preferences > Profiles > Text


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

    <bean id="date" class="org.apache.camel.routepolicy.quartz.SimpleDate"/>

    <bean id="defaultPolicy" class="org.apache.camel.routepolicy.quartz.SimpleScheduledRoutePolicy"/>

    <bean id="startPolicy" class="org.apache.camel.routepolicy.quartz.SimpleScheduledRoutePolicy">
    	<property name="routeStartDate" ref="date"/>
    	<property name="routeStartRepeatCount" value="1"/>
    	<property name="routeStartRepeatInterval" value="3000"/>
    </bean>

    <bean id="stopPolicy" class="org.apache.camel.routepolicy.quartz.SimpleScheduledRoutePolicy">
    	<property name="routeStopDate" ref="date"/>
    	<property name="routeStopRepeatCount" value="1"/>
    	<property name="routeStopRepeatInterval" value="3000"/>
	</bean>

	<bean id="suspendPolicy" class="org.apache.camel.routepolicy.quartz.SimpleScheduledRoutePolicy">
    	<property name="routeSuspendDate" ref="date"/>
    	<property name="routeSuspendRepeatCount" value="1"/>
    	<property name="routeSuspendRepeatInterval" value="3000"/>
  	</bean>

  	<bean id="resumePolicy" class="org.apache.camel.routepolicy.quartz.SimpleScheduledRoutePolicy">
       	<property name="routeResumeDate" ref="date"/>
    	<property name="routeResumeRepeatCount" value="1"/>
    	<property name="routeResumeRepeatInterval" value="3000"/>
 	</bean>

    <routeContext id="testRouteContext" xmlns="http://camel.apache.org/schema/spring">
        <route id="testRoute" routePolicyRef="policy">
            <from uri="direct:start"/>
            <to uri="mock:success"/>
        </route>
    </routeContext>

</beans>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Anansi: inc/MessageQueue.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Anansi

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

 All Classes Files Functions Variables Typedefs Macros

MessageQueue.h

Go to the documentation of this file.

    1 #ifndef MessageQueue_h

    2 #define MessageQueue_h

    3

    4 #include <Message.h>

    5 #include <iostream>

    6 class MessageQueue {

    7

    8     deque<Message> _queue;

    9

   10 public:

   11     void addMessage(Message m);

   12     void addPriorityMessage(Message m);

   13

   14     deque<Message> getMessageQueue();

   15     Message popMessage();

   16     int queueSize();

   17 };

   18

   19 #endif

MessageQueue

Definition: MessageQueue.h:6

MessageQueue::addPriorityMessage

void addPriorityMessage(Message m)

Definition: MessageQueue.cpp:11

Message.h

Message

Definition: Message.h:9

MessageQueue::queueSize

int queueSize()

Definition: MessageQueue.cpp:28

MessageQueue::popMessage

Message popMessage()

Definition: MessageQueue.cpp:16

MessageQueue::addMessage

void addMessage(Message m)

Definition: MessageQueue.cpp:3

MessageQueue::_queue

deque< Message > _queue

Definition: MessageQueue.h:8

MessageQueue::getMessageQueue

deque< Message > getMessageQueue()

Definition: MessageQueue.cpp:24

inc

MessageQueue.h

Generated on Thu May 4 2017 13:21:40 for Anansi by

     1.8.6


text:
<?php

namespace SilexMarkdown\Composer;

use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;

class Script
{
    /**
     * install
     *
     * @return void
     */
    public static function install()
    {
        $output = new ConsoleOutput();
        $style = new OutputFormatterStyle('green');
        $output->getFormatter()->setStyle('green', $style);

        $assets = array('resources/cache', 'resources/log','web/assets');
        foreach ($assets as $asset) {
            self::createAndChmod($asset, 0777);
                $output->writeln(sprintf('<green>Generating "%s" asset dir</green>', $asset));
        }
        exec('php console assetic:dump');

    }

    /**
     * createAndChmod
     *
     * @param string $directory
     * @param int $chmod
     * @return void
     */
    public static function createAndChmod($directory, $chmod)
    {
        if (!is_dir($directory)) {
            if (false === @mkdir($directory, $chmod, true)) {
                throw new FileException(sprintf('Unable to create the "%s" directory with "%d" ', $directory, $chmod));
            }
        } elseif (!is_writable($directory)) {
            throw new FileException(sprintf('Unable to write in the "%s" directory', $directory));
        }
        if(false === @chmod($directory, $chmod)) {
            throw new FileException(sprintf('Unable to chmod %d the "%s" directory', $directory, $chmod));
        }
    }
}


text:
package org.opensingular.requirement.connector.sei30.ws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Classe Java de Observacao complex type.
 *
 *
O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe.
 *
 *

 * <complexType name="Observacao">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <all>
 *         <element name="Descricao" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="Unidade" type="{Sei}Unidade"/>
 *       </all>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Observacao", propOrder = {

})
public class Observacao {

    @XmlElement(name = "Descricao", required = true)
    protected String descricao;
    @XmlElement(name = "Unidade", required = true)
    protected Unidade unidade;

    /**
     * Obtém o valor da propriedade descricao.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDescricao() {
        return descricao;
    }

    /**
     * Define o valor da propriedade descricao.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDescricao(String value) {
        this.descricao = value;
    }

    /**
     * Obtém o valor da propriedade unidade.
     *
     * @return
     *     possible object is
     *     {@link Unidade }
     *
     */
    public Unidade getUnidade() {
        return unidade;
    }

    /**
     * Define o valor da propriedade unidade.
     *
     * @param value
     *     allowed object is
     *     {@link Unidade }
     *
     */
    public void setUnidade(Unidade value) {
        this.unidade = value;
    }

}


text:
    Specify the file location of the JSON format config file to setup your node.
    This file must have json extension and will be passed to the grid with the -nodeConfig parameter.
    This config file path can be configured with any scheme
    the URL java class understands. (file:, http:, ftp:, etc.)


text:
using absl::make_unique;
using std::string;

namespace s2polyline_alignment {

Window::Window(const std::vector<ColumnStride>& strides) {
  S2_DCHECK(!strides.empty()) << "Cannot construct empty window.";
  S2_DCHECK(strides[0].start == 0) << "First element of start_cols is non-zero.";
  strides_ = strides;
  rows_ = strides.size();
  cols_ = strides.back().end;
  S2_DCHECK(this->IsValid()) << "Constructor validity check fail.";
}

Window::Window(const WarpPath& warp_path) {
  S2_DCHECK(!warp_path.empty()) << "Cannot construct window from empty warp path.";
  S2_DCHECK(warp_path.front() == std::make_pair(0, 0)) << "Must start at (0, 0).";
  rows_ = warp_path.back().first + 1;
  S2_DCHECK(rows_ > 0) << "Must have at least one row.";
  cols_ = warp_path.back().second + 1;
  S2_DCHECK(cols_ > 0) << "Must have at least one column.";
  strides_.resize(rows_);

  int prev_row = 0;
  int curr_row = 0;
  int stride_start = 0;
  int stride_stop = 0;
  for (const auto& pair : warp_path) {
    curr_row = pair.first;
    if (curr_row > prev_row) {
      strides_[prev_row] = {stride_start, stride_stop};
      stride_start = pair.second;
      prev_row = curr_row;
    }
    stride_stop = pair.second + 1;
  }
  S2_DCHECK_EQ(curr_row, rows_ - 1);
  strides_[rows_ - 1] = {stride_start, stride_stop};
  S2_DCHECK(this->IsValid()) << "Constructor validity check fail.";
}

Window Window::Upsample(const int new_rows, const int new_cols) const {
  S2_DCHECK(new_rows >= rows_) << "Upsampling: New_rows < current_rows";
  S2_DCHECK(new_cols >= cols_) << "Upsampling: New_cols < current_cols";
  const double row_scale = static_cast<double>(new_rows) / rows_;
  const double col_scale = static_cast<double>(new_cols) / cols_;
  std::vector<ColumnStride> new_strides(new_rows);
  ColumnStride from_stride;
  for (int row = 0; row < new_rows; ++row) {
    from_stride = strides_[static_cast<int>((row + 0.5) / row_scale)];
    new_strides[row] = {static_cast<int>(col_scale * from_stride.start + 0.5),
                        static_cast<int>(col_scale * from_stride.end + 0.5)};
  }
  return Window(new_strides);
}

// This code takes advantage of the fact that the dilation window is square to
// ensure that we can compute the stride for each output row in constant time.
// TODO (mrdmnd): a potential optimization might be to combine this method and
// the Upsample method into a single "Expand" method. For the sake of
// testing, I haven't done that here, but I think it would be fairly
// straightforward to do so. This method generally isn't very expensive so it
// feels unnecessary to combine them.
Window Window::Dilate(const int radius) const {
  S2_DCHECK(radius >= 0) << "Negative dilation radius.";
  std::vector<ColumnStride> new_strides(rows_);
  int prev_row, next_row;
  for (int row = 0; row < rows_; ++row) {
    prev_row = std::max(0, row - radius);
    next_row = std::min(row + radius, rows_ - 1);
    new_strides[row] = {std::max(0, strides_[prev_row].start - radius),
                        std::min(strides_[next_row].end + radius, cols_)};
  }
  return Window(new_strides);
}

// Debug string implemented primarily for testing purposes.
string Window::DebugString() const {
  std::stringstream buffer;
  for (int row = 0; row < rows_; ++row) {
    for (int col = 0; col < cols_; ++col) {
      buffer << (strides_[row].InRange(col) ? " *" : " .");
    }
    buffer << std::endl;
  }
  return buffer.str();
}

// Valid Windows require the following structural conditions to hold:
// 1) All rows must consist of a single contiguous stride of `true` values.
// 2) All strides are greater than zero length (i.e. no empty rows).
// 3) The index of the first `true` column in a row must be at least as
//    large as the index of the first `true` column in the previous row.
// 4) The index of the last `true` column in a row must be at least as large
//    as the index of the last `true` column in the previous row.
// 5) strides[0].start = 0 (the first cell is always filled).
// 6) strides[n_rows-1].end = n_cols (the last cell is filled).
bool Window::IsValid() const {
  if (rows_ <= 0 || cols_ <= 0 || strides_.front().start != 0 ||
      strides_.back().end != cols_) {
    return false;
  }

  ColumnStride prev = {-1, -1};
  for (const auto& curr : strides_) {
    if (curr.end <= curr.start || curr.start < prev.start ||
        curr.end < prev.end) {
      return false;
    }
    prev = curr;
  }
  return true;
}

inline double BoundsCheckedTableCost(const int row, const int col,
                                     const ColumnStride& stride,
                                     const CostTable& table) {
  if (row < 0 && col < 0) {
    return 0.0;
  } else if (row < 0 || col < 0 || !stride.InRange(col)) {
    return DOUBLE_MAX;
  } else {
    return table[row][col];
  }
}

// Perform dynamic timewarping by filling in the DP table on cells that are
// inside our search window. For an exact (all-squares) evaluation, this
// incurs bounds checking overhead - we don't need to ensure that we're inside
// the appropriate cells in the window, because it's guaranteed. Structuring
// the program to reuse code for both the EXACT and WINDOWED cases by
// abstracting EXACT as a window with full-covering strides is done for
// maintainability reasons. One potential optimization here might be to overload
// this function to skip bounds checking when the window is full.
//
// As a note of general interest, the Dynamic Timewarp algorithm as stated here
// prefers shorter warp paths, when two warp paths might be equally costly. This
// is because it favors progressing in the sequences simultaneously due to the
// equal weighting of a diagonal step in the cost table with a horizontal or
// vertical step. This may be counterintuitive, but represents the standard
// implementation of this algorithm. TODO(user) - future implementations could
// allow weights on the lookup costs to mitigate this.
//
// This is the hottest routine in the whole package, please be careful to
// profile any future changes made here.
//
// This method takes time proportional to the number of cells in the window,
// which can range from O(max(a, b)) cells (best) to O(a*b) cells (worst)
VertexAlignment DynamicTimewarp(const S2Polyline& a, const S2Polyline& b,
                                const Window& w) {
  const int rows = a.num_vertices();
  const int cols = b.num_vertices();
  auto costs = CostTable(rows, std::vector<double>(cols));

  ColumnStride curr;
  ColumnStride prev = ColumnStride::All();
  for (int row = 0; row < rows; ++row) {
    curr = w.GetColumnStride(row);
    for (int col = curr.start; col < curr.end; ++col) {
      double d_cost = BoundsCheckedTableCost(row - 1, col - 1, prev, costs);
      double u_cost = BoundsCheckedTableCost(row - 1, col - 0, prev, costs);
      double l_cost = BoundsCheckedTableCost(row - 0, col - 1, curr, costs);
      costs[row][col] = std::min({d_cost, u_cost, l_cost}) +
                        (a.vertex(row) - b.vertex(col)).Norm2();
    }
    prev = curr;
  }

  // Now we walk back through the cost table and build up the warp path.
  // Somewhat surprisingly, it is faster to recover the path this way than it
  // is to save the comparisons from the computation we *already did* to get the
  // direction we came from. The author speculates that this behavior is
  // assignment-cost-related: to persist direction, we have to do extra
  // stores/loads of "directional" information, and the extra assignment cost
  // this incurs is larger than the cost to simply redo the comparisons.
  // It's probably worth revisiting this assumption in the future.
  // As it turns out, the following code ends up effectively free.
  WarpPath warp_path;
  warp_path.reserve(std::max(a.num_vertices(), b.num_vertices()));
  int row = a.num_vertices() - 1;
  int col = b.num_vertices() - 1;
  curr = w.GetCheckedColumnStride(row);
  prev = w.GetCheckedColumnStride(row - 1);
  while (row >= 0 && col >= 0) {
    warp_path.push_back({row, col});
    double d_cost = BoundsCheckedTableCost(row - 1, col - 1, prev, costs);
    double u_cost = BoundsCheckedTableCost(row - 1, col - 0, prev, costs);
    double l_cost = BoundsCheckedTableCost(row - 0, col - 1, curr, costs);
    if (d_cost <= u_cost && d_cost <= l_cost) {
      row -= 1;
      col -= 1;
      curr = w.GetCheckedColumnStride(row);
      prev = w.GetCheckedColumnStride(row - 1);
    } else if (u_cost <= l_cost) {
      row -= 1;
      curr = w.GetCheckedColumnStride(row);
      prev = w.GetCheckedColumnStride(row - 1);
    } else {
      col -= 1;
    }
  }
  std::reverse(warp_path.begin(), warp_path.end());
  return VertexAlignment(costs.back().back(), warp_path);
}

std::unique_ptr<S2Polyline> HalfResolution(const S2Polyline& in) {
  const int n = in.num_vertices();
  std::vector<S2Point> vertices;
  vertices.reserve(n / 2);
  for (int i = 0; i < n; i += 2) {
    vertices.push_back(in.vertex(i));
  }
  return make_unique<S2Polyline>(vertices);
}

// Helper methods for GetMedoidPolyline and GetConsensusPolyline to auto-select
// appropriate cost function / alignment functions.
double CostFn(const S2Polyline& a, const S2Polyline& b, bool approx) {
  return approx ? GetApproxVertexAlignment(a, b).alignment_cost
                : GetExactVertexAlignmentCost(a, b);
}

VertexAlignment AlignmentFn(const S2Polyline& a, const S2Polyline& b,
                            bool approx) {
  return approx ? GetApproxVertexAlignment(a, b)
                : GetExactVertexAlignment(a, b);
}

// PUBLIC API IMPLEMENTATION DETAILS

// This is the constant-space implementation of Dynamic Timewarp that can
// compute the alignment cost, but not the warp path.
double GetExactVertexAlignmentCost(const S2Polyline& a, const S2Polyline& b) {
  const int a_n = a.num_vertices();
  const int b_n = b.num_vertices();
  S2_CHECK(a_n > 0) << "A is empty polyline.";
  S2_CHECK(b_n > 0) << "B is empty polyline.";
  std::vector<double> cost(b_n, DOUBLE_MAX);
  double left_diag_min_cost = 0;
  for (int row = 0; row < a_n; ++row) {
    for (int col = 0; col < b_n; ++col) {
      double up_cost = cost[col];
      cost[col] = std::min(left_diag_min_cost, up_cost) +
                  (a.vertex(row) - b.vertex(col)).Norm2();
      left_diag_min_cost = std::min(cost[col], up_cost);
    }
    left_diag_min_cost = DOUBLE_MAX;
  }
  return cost.back();
}

VertexAlignment GetExactVertexAlignment(const S2Polyline& a,
                                        const S2Polyline& b) {
  const int a_n = a.num_vertices();
  const int b_n = b.num_vertices();
  S2_CHECK(a_n > 0) << "A is empty polyline.";
  S2_CHECK(b_n > 0) << "B is empty polyline.";
  const auto w = Window(std::vector<ColumnStride>(a_n, {0, b_n}));
  return DynamicTimewarp(a, b, w);
}

VertexAlignment GetApproxVertexAlignment(const S2Polyline& a,
                                         const S2Polyline& b,
                                         const int radius) {
  // Determined experimentally, through benchmarking, as about the points at
  // which ExactAlignment is faster than ApproxAlignment, so we use these as
  // our switchover points to exact computation mode.
  const int kSizeSwitchover = 32;
  const double kDensitySwitchover = 0.85;
  const int a_n = a.num_vertices();
  const int b_n = b.num_vertices();
  S2_CHECK(a_n > 0) << "A is empty polyline.";
  S2_CHECK(b_n > 0) << "B is empty polyline.";
  S2_CHECK(radius >= 0) << "Radius is negative.";

  // If we've hit the point where doing a full, direct solve is guaranteed to
  // be faster, then terminate the recursion and do that.
  if (a_n - radius < kSizeSwitchover || b_n - radius < kSizeSwitchover) {
    return GetExactVertexAlignment(a, b);
  }

  // If we've hit the point where the window will be probably be so full that we
  // might as well compute an exact solution, then terminate recursion to do so.
  if (std::max(a_n, b_n) * (2 * radius + 1) > a_n * b_n * kDensitySwitchover) {
    return GetExactVertexAlignment(a, b);
  }

  // Otherwise, shrink the input polylines, recursively compute the vertex
  // alignment using this method, and then compute the final alignment using
  // the projected alignment `proj` on an upsampled, dilated window.
  const auto a_half = HalfResolution(a);
  const auto b_half = HalfResolution(b);
  const auto proj = GetApproxVertexAlignment(*a_half, *b_half, radius);
  const auto w = Window(proj.warp_path).Upsample(a_n, b_n).Dilate(radius);
  return DynamicTimewarp(a, b, w);
}

// This method calls the approx method with a reasonable default for radius.
VertexAlignment GetApproxVertexAlignment(const S2Polyline& a,
                                         const S2Polyline& b) {
  const int max_length = std::max(a.num_vertices(), b.num_vertices());
  const int radius = static_cast<int>(std::pow(max_length, 0.25));
  return GetApproxVertexAlignment(a, b, radius);
}

// We use some of the symmetry of our metric to avoid computing all N^2
// alignments. Specifically, because cost_fn(a, b) = cost_fn(b, a), and
// cost_fn(a, a) = 0, we can compute only the lower triangle of cost matrix
// and then mirror it across the diagonal to save on cost_fn invocations.
int GetMedoidPolyline(const std::vector<std::unique_ptr<S2Polyline>>& polylines,
                      const MedoidOptions options) {
  const int num_polylines = polylines.size();
  const bool approx = options.approx();
  S2_CHECK_GT(num_polylines, 0);

  // costs[i] stores total cost of aligning [i] with all other polylines.
  std::vector<double> costs(num_polylines, 0.0);
  for (int i = 0; i < num_polylines; ++i) {
    for (int j = i + 1; j < num_polylines; ++j) {
      double cost = CostFn(*polylines[i], *polylines[j], approx);
      costs[i] += cost;
      costs[j] += cost;
    }
  }
  return std::min_element(costs.begin(), costs.end()) - costs.begin();
}

// Implements Iterative Dynamic Timewarp Barycenter Averaging algorithm from
//
// https://pdfs.semanticscholar.org/a596/8ca9488199291ffe5473643142862293d69d.pdf
//
// Algorithm:
// Initialize consensus sequence with either the medoid or an arbitrary
// element (chosen here to be the first element in the input collection).
// While the consensus polyline `consensus` hasn't converged and we haven't
// exceeded our iteration cap:
//   For each polyline `p` in the input,
//     Compute vertex alignment from the current consensus to `p`.
//     For each (c_index, p_index) pair in the warp path,
//       Add the S2Point pts->vertex(p_index) to S2Point consensus[c_index]
//   Normalize (compute centroid) of each consensus point.
//   Determine if consensus is converging; if no vertex has moved or we've hit
//   the iteration cap, halt.
//
//  This algorithm takes O(iteration_cap * num_polylines) pairwise alignments.

std::unique_ptr<S2Polyline> GetConsensusPolyline(
    const std::vector<std::unique_ptr<S2Polyline>>& polylines,
    const ConsensusOptions options) {
  const int num_polylines = polylines.size();
  S2_CHECK_GT(num_polylines, 0);
  const bool approx = options.approx();

  // Seed a consensus polyline, either arbitrarily with first element, or with
  // the medoid. If seeding with medoid, inherit approx parameter from options.
  int seed_index = 0;
  if (options.seed_medoid()) {
    MedoidOptions medoid_options;
    medoid_options.set_approx(approx);
    seed_index = GetMedoidPolyline(polylines, medoid_options);
  }
  auto consensus = std::unique_ptr<S2Polyline>(polylines[seed_index]->Clone());
  const int num_consensus_vertices = consensus->num_vertices();
  S2_DCHECK_GT(num_consensus_vertices, 1);

  bool converged = false;
  int iterations = 0;
  while (!converged && iterations < options.iteration_cap()) {
    std::vector<S2Point> points(num_consensus_vertices, S2Point());
    for (const auto& polyline : polylines) {
      const auto alignment = AlignmentFn(*consensus, *polyline, approx);
      for (const auto& pair : alignment.warp_path) {
        points[pair.first] += polyline->vertex(pair.second);
      }
    }
    for (S2Point& p : points) {
      p = p.Normalize();
    }

    ++iterations;
    auto new_consensus = make_unique<S2Polyline>(points);
    converged = new_consensus->ApproxEquals(*consensus);
    consensus = std::move(new_consensus);
  }
  return consensus;
}
}  // namespace s2polyline_alignment


text:
function EEG = re_ref(EEG, ref_type)

if ischar(ref_type) && strcmpi(ref_type, 'average')
	EEG = pop_reref(EEG, []);
	EEG = eeg_checkset(EEG);
else
	if iscellstr(ref_type)
		ref_ind = lix_elecfind(EEG.chanlocs, ref_type);
		EEG = pop_reref(EEG, ref_ind);
		EEG = eeg_checkset(EEG);
	else
		disp('ref_type must be string or cell string array')
		return
	end
end


text:
package sage.media.format;

/**
 *
 * @author Narflex
 */
public class ID3Parser
{
  public static final String[] ID3V1_GENRES = { "Blues", "Classic Rock", "Country", "Dance", "Disco", "Funk",
    "Grunge", "Hip-Hop", "Jazz", "Metal", "New Age", "Oldies", "Other", "Pop", "R&B", "Rap", "Reggae", "Rock",
    "Techno", "Industrial", "Alternative", "Ska", "Death Metal", "Pranks", "Soundtrack", "Euro-Techno",
    "Ambient", "Trip-Hop", "Vocal", "Jazz+Funk", "Fusion", "Trance", "Classical", "Instrumental",
    "Acid", "House", "Game", "Sound Clip", "Gospel", "Noise", "AlternRock", "Bass", "Soul", "Punk",
    "Space", "Meditative", "Instrumental Pop", "Instrumental Rock", "Ethnic", "Gothic", "Darkwave",
    "Techno-Industrial", "Electronic", "Pop-Folk", "Eurodance", "Dream", "Southern Rock", "Comedy", "Cult",
    "Gangsta", "Top 40", "Christian Rap", "Pop/Funk", "Jungle", "Native American", "Cabaret", "New Wave",
    "Psychadelic", "Rave", "Showtunes", "Trailer", "Lo-Fi", "Tribal", "Acid Punk", "Acid Jazz", "Polka",
    "Retro", "Musical", "Rock & Roll", "Hard Rock", "Folk", "Folk-Rock", "National Folk", "Swing",
    "Fast Fusion", "Bebob", "Latin", "Revival", "Celtic", "Bluegrass", "Avantgarde", "Gothic Rock",
    "Progressive Rock", "Psychedelic Rock", "Symphonic Rock", "Slow Rock", "Big Band", "Chorus",
    "Easy Listening", "Acoustic", "Humour", "Speech", "Chanson", "Opera", "Chamber Music", "Sonata",
    "Symphony", "Booty Bass", "Primus", "Porn Groove", "Satire", "Slow Jam", "Club", "Tango", "Samba",
    "Folklore", "Ballad", "Power Ballad", "Rhythmic Soul", "Freestyle", "Duet", "Punk Rock",
    "Drum Solo", "A capella", "Euro-House", "Dance Hall" };

  private ID3Parser()
  {
  }

  // This will extract any additional ID3V1/V2 metadata from the file and put it in the returned Map
  public static java.util.Map extractID3MetaData(java.io.File f)
  {
    try
    {
      if (f.length() > 128)
      {
        // First look for the ID3V2 tags
        java.util.HashMap rv = parseID3V2Tag(f);
        if (rv != null && !rv.isEmpty())
          return rv;
        rv = parseID3V1Tag(f);
        if (rv != null)
          return rv;
      }
      /*String parsePlugins = Sage.get("mediafile_metadata_parser_plugins", "");
			if (Sage.WINDOWS_OS)
				parsePlugins += ";sage.WMATagParser";
			java.util.StringTokenizer toker = new java.util.StringTokenizer(parsePlugins, ",;");
			while (toker.hasMoreTokens())
			{
				try
				{
					MediaFileMetadataParser parsie = (MediaFileMetadataParser) Class.forName(toker.nextToken()).newInstance();
					metaAir = (Airing)parsie.extractMetadata(theFile, namePrefix);
					if (metaAir != null)
					{
						infoAiringID = metaAir.getID();
						myAiring = metaAir;
						return metaAir;
					}
				}
				catch (Exception e1)
				{
					if (Sage.DBG) System.out.println("Error instantiating metadata parser plugin of:" + e1);
				}
			}
			return metaAir;*/
      return null;
    }
    catch (Exception e)
    {
      if (sage.Sage.DBG) System.out.println("Error parsing metadata in file " + f + " of:" + e);
      return null;
    }
  }

  private static long getMpegAudioBitrate(byte[] data, int offset)
  {
    // First synchronize on the syncword 0xFF F?
    while ((offset + 1 < data.length) && (((data[offset] & 0xFF) != 0xFF) || ((data[offset+1]&0xF0) != 0xF0)))
      offset++;
    if (((data[offset] & 0xFF) != 0xFF) || ((data[offset+1]&0xF0) != 0xF0) || (data.length - offset < 3))
    {
      //if (sage.Sage.DBG) System.out.println("Couldn't find MPEG audio syncword");
      return 0;
    }
    int level = ((data[offset+1]&0x08) == 0x08) ? 1 : 2;
    int layer = (data[offset+1]&0x06) >> 1;
    if (layer == 3)
      layer = 1;
    else if (layer != 2)
      layer = 3;
    int bitrateIndex = (data[offset+2]&0xF0) >> 4;
    // First index is the input
    // Second index is MPEG level and layer
    // (MPEG-1, layer 1; MPEG-1, layer 2; MPEG-1, layer3;
    //  MPEG-2, layer 1; MPEG-2, layer 2; MPEG-2, layer3)
    int [][]convert = {
        {   0,   0,   0,   0,   0,   0 },
        {  32,  32,  32,  32,  32,   8 },
        {  64,  48,  40,  64,  48,  16 },
        {  96,  56,  48,  96,  56,  24 },
        { 128,  64,  56, 128,  64,  32 },
        { 160,  80,  64, 160,  80,  64 },
        { 192,  96,  80, 192,  96,  80 },
        { 224, 112,  96, 224, 112,  56 },
        { 256, 128, 112, 256, 128,  64 },
        { 288, 160, 128, 288, 160, 128 },
        { 320, 192, 160, 320, 192, 160 },
        { 352, 224, 192, 352, 224, 112 },
        { 384, 256, 224, 384, 256, 128 },
        { 416, 320, 256, 416, 320, 256 },
        { 448, 384, 320, 448, 384, 320 },
        {   0,   0,   0,   0,   0,   0 }
    };

    int index2 = (level - 1) * 3 + layer - 1;

    if (bitrateIndex < convert.length && bitrateIndex >= 0 && index2 >= 0 && index2 < convert[bitrateIndex].length)
      return convert[bitrateIndex][index2];
    else
      return 0;
  }

  private static String cleanString(String s)
  {
    StringBuffer rv = new StringBuffer();
    for (int i = 0; i < s.length(); i++)
    {
      if (s.charAt(i) != 0)
        rv.append(s.charAt(i));
      else if (rv.length() != 0)
        break;
    }
    return rv.toString().trim();
  }

  public static java.util.HashMap parseID3V1Tag(java.io.File theFile) throws java.io.IOException
  {
    // Don't use FastRandomFile here because it allocates a big buffer to read which we don't need
    java.io.RandomAccessFile randy = new java.io.RandomAccessFile(theFile, "r");
    try
    {
      byte[] buf = new byte[128];
      randy.seek(randy.length() - 128);
      randy.readFully(buf);
      String tag = new String(buf, 0, 3).trim();
      if (!"TAG".equals(tag))
        return null;
      String textEncoding = sage.Sage.get("id3_default_text_encoding", "ISO-8859-1");
      String title = cleanString(new String(buf, 3, 30, textEncoding));
      if (title.length() == 0) return null;
      String artist = cleanString(new String(buf, 33, 30, textEncoding));
      String album = cleanString(new String(buf, 63, 30, textEncoding));
      //if (album.length() == 0) album = sage.Sage.rez("Music_Single");
      String year = cleanString(new String(buf, 93, 4, textEncoding));
      String comment = cleanString(new String(buf, 97, 28, textEncoding));
      int track = (buf[125] & 0xFF);
      int genre = (buf[127] & 0xFF);
      String category = "";
      if (genre >= 0 && genre < ID3V1_GENRES.length)
        category = ID3V1_GENRES[genre];
      if (track == 0 && comment.startsWith("Track "))
      {
        try
        {
          track = Integer.parseInt(comment.substring(6));
        }catch (Exception e2){}
      }
      if (sage.Sage.DBG) System.out.println("ID3V1tag=" + tag + " title=" + title + " artist=" + artist + " album=" + album + " year=" + year +
          " comment=" + comment + " track=" + track + " genre=" + category);
      randy.seek(0);
      randy.readFully(buf);
      // Try the updated duration technique
      /*			long theDur = sage.MP3Utils.getMp3Duration(theFile);
			if (theDur == 0)
			{
				long mpegAudioBitrate = getMpegAudioBitrate(buf, 0);
				if (mpegAudioBitrate > 0)
				{
					theDur = 8*(randy.length() - 128)/mpegAudioBitrate;
					if (sage.Sage.DBG) System.out.println("Mpegaudiobitrate=" + mpegAudioBitrate + " theDur=" + theDur);
				}
			}*/
      java.util.HashMap rv = new java.util.HashMap();
      rv.put(MediaFormat.META_TITLE, title);
      rv.put(MediaFormat.META_ALBUM, album);
      rv.put(MediaFormat.META_YEAR, year);
      rv.put(MediaFormat.META_COMMENT, comment);
      rv.put(MediaFormat.META_ARTIST, artist);
      rv.put(MediaFormat.META_GENRE, category);
      if (track != 0)
        rv.put(MediaFormat.META_TRACK, Integer.toString(track));
      //			if (theDur > 0)
      //				rv.put(MediaFormat.META_DURATION, Long.toString(theDur));
      return rv;
    }
    finally
    {
      randy.close();
    }
    /*if (theDur == 0)
			theDur = VideoFrame.getFileDuration(theFile.toString());
		if (theDur == 0)
			theDur = 1;*/
    /*if (!isMusicFile())
		{
			title = namePrefix + title;
			String temp = title;
			title = album;
			album = temp;
		}*/
    //		if (artist.length() > 0)
    //			myAiring = Wizard.getInstance().addAiring(Wizard.getInstance().addShow(album, null, title,
    //				"", 0, category, null, new String[] { artist }, new byte[] { (mediaType == MEDIATYPE_AUDIO) ? Show.ARTIST_ROLE : Show.ACTOR_ROLE }, null, null,
    //				year, null, null, "MP3" + Integer.toString(id), "English", 0), 0/*1000000 + id*/,
    //				theFile.lastModified() - theDur, theDur, (byte)track, (byte)0, (byte)0);
    //		else
    //			myAiring = Wizard.getInstance().addAiring(Wizard.getInstance().addShow(album, null, title,
    //				"", 0, category, null, new String[0], new byte[0], null, null,
    //				year, null, null, "MP3" + Integer.toString(id), "English", 0), 0/*1000000 + id*/,
    //				theFile.lastModified() - theDur, theDur, (byte)track, (byte)0, (byte)0);
    //		infoAiringID = myAiring.id;
    //		return myAiring;
  }

  private static int getSyncSafeInt(byte[] buf, int offset, boolean unsync)
  {
    if (unsync)
    {
      if (buf[offset] < 0 || buf[offset+1] < 0 || buf[offset+2] < 0 || buf[offset+3] < 0) return -1; // unsynched size bytes
      return (((int)buf[offset]) << 21) + (((int)buf[offset+1]) << 14) + (((int)buf[offset+2]) << 7) + buf[offset+3];
    }
    else
    {
      return ((buf[offset] & 0xFF) << 24) + ((buf[offset+1] & 0xFF) << 16) + ((buf[offset+2] & 0xFF) << 8) + (buf[offset+3] & 0xFF);
    }
  }

  public static java.util.HashMap parseID3V2Tag(java.io.File theFile) throws java.io.IOException
  {
    if (theFile.length() < 128) return null;
    // Don't use FastRandomFile here because it allocates a big buffer to read which we don't need
    java.io.RandomAccessFile randy = new java.io.RandomAccessFile(theFile, "r");
    try
    {
      byte[] buf = new byte[128];
      randy.readFully(buf);
      String tag = new String(buf, 0, 3).trim();
      if (!"ID3".equals(tag))
        return null;
      //if (Sage.DBG) System.out.println("ID3V2." + buf[3] + "." + buf[4] + " tag detected");
      short version = buf[3];
      if ((buf[3] & 0xFF) == 0xFF) return null; // incompatible version
      boolean unsync = (buf[5] & 0x80) == 0x80;
      boolean extHdr = (buf[5] & 0x40) == 0x40;
      boolean experimental = (buf[5] & 0x20) == 0x20;
      boolean footerPresent = (buf[5] & 0x10) == 0x10;
      if ((buf[5] & 0x0F) != 0) return null; // unknown flags
      int tagSize = getSyncSafeInt(buf, 6, true);
      if (tagSize < 0) return null;
      int fullHeaderSize = tagSize + 10 + (footerPresent ? 10 : 0);
      buf = new byte[fullHeaderSize];
      randy.seek(0);
      randy.readFully(buf);
      //if (Sage.DBG) System.out.println("unsync=" + unsync + " extHdr=" + extHdr + " footer=" + footerPresent + " size=" + tagSize);
      int offset = 10;
      if (extHdr)
      {
        int extHdrSize = getSyncSafeInt(buf, offset, version >= 4 /*V2.4 added unsync here*/);
        if (extHdrSize < 0) return null;
        int numFlagBytes = buf[14];
        offset += 5;
        //if (Sage.DBG) System.out.println("extHdrSize=" + extHdrSize + " numFlagBytes=" + numFlagBytes);
        if (numFlagBytes != 1) return null;
        boolean tagUpdate = (buf[offset] & 0x40) == 0x40;
        boolean crcPresent = (buf[offset] & 0x20) == 0x20;
        boolean tagRestrictions = (buf[offset] & 0x10) == 0x10;
        if (tagUpdate)
        {
          int extTagLength = buf[offset] + 1;
          offset += 1 + extTagLength;
        }
        if (crcPresent)
        {
          int extTagLength = buf[offset] + 1;
          offset += 1 + extTagLength;
        }
        if (tagRestrictions)
        {
          int extTagLength = buf[offset] + 1;
          offset += 1 + extTagLength;
        }
        //if (Sage.DBG) System.out.println("tagUpdate=" + tagUpdate + " crc=" + crcPresent + " tagRes=" + tagRestrictions);
      }
      java.util.HashMap rv = new java.util.HashMap();
      long duration = 0;
      frame_processing:
        while (offset < tagSize) // +10 for the initial header and -10 for the next frame header
        {
          String frameCode = new String(buf, offset, (version <= 2) ? 3 : 4);
          for (int i = 0; i < 3; i++)
          {
            char c = frameCode.charAt(i);
            if ((c < '0' || c > '9') && (c < 'A' || c > 'Z'))
              break frame_processing;
          }
          int frameSize;
          if (version <= 2)
          {
            frameSize = ((buf[offset + 3] & 0xFF) << 16) | ((buf[offset + 4] & 0xFF) << 8) | (buf[offset + 5] & 0xFF);
          }
          else
            frameSize = getSyncSafeInt(buf, offset + 4, unsync || version >= 4); // V2.4 made all frame sizes synched ints
          //if (Sage.DBG) System.out.println("FrameCode=" + frameCode + " frameSize=" + frameSize);
          if (frameSize == -1) break;
          if (version <= 2)
            offset += 6;
          else
          {
            int frameFlag1 = buf[offset+8]&0xFF;
            int frameFlag2 = buf[offset+9]&0xFF;
            if ((frameFlag2 & 0x4F) != 0)
            {
              //if (Sage.DBG) System.out.println("Unknown frame format flags");
              offset += frameSize;
              break;
            }
            boolean groupIdentity = (frameFlag2 & 0x40) == 0x40;
            boolean compressed = (frameFlag2 & 0x08) == 0x08;
            boolean encryption = (frameFlag2 & 0x04) == 0x04;
            boolean unsynchronization = (frameFlag2 & 0x02) == 0x02;
            boolean dataLengthIndicator = (frameFlag2 & 0x01) == 0x01;
            offset += 10;
          }

          String textEncoding;
          boolean doubleByteEncoding = false;
          if (buf[offset] == 3)
            textEncoding = "UTF-8";
          else if (buf[offset] == 2)
          {
            doubleByteEncoding = true;
            // We don't need to specify big endian since the byte order mark (BOM) will be there
            textEncoding = "UTF-16";
          }
          else if (buf[offset] == 1)
          {
            doubleByteEncoding = true;
            textEncoding = "UTF-16";
          }
          else
            textEncoding = sage.Sage.get("id3_default_text_encoding", "ISO-8859-1");
          // Skip one for the character encoding byte
          if (frameCode.equals("TLEN"))
          {
            String currStr = cleanString(new String(buf, offset + 1, frameSize - 1, textEncoding));
            //if (Sage.DBG) System.out.println("TLEN(length)=" + currStr);
            try
            {
              duration = Long.parseLong(currStr);
              rv.put(MediaFormat.META_DURATION, Long.toString(duration));
            }
            catch(Exception e){}
          }
          else if (frameCode.equals("TIT2") || frameCode.equals("TT2"))
          {
            rv.put(MediaFormat.META_TITLE, cleanString(new String(buf, offset + 1, frameSize - 1, textEncoding)));
            //if (Sage.DBG) System.out.println("TIT2(title)=" + title);
          }
          else if (frameCode.equals("TCOM") || frameCode.equals("TCM"))
          {
            rv.put(MediaFormat.META_COMPOSER, cleanString(new String(buf, offset + 1, frameSize - 1, textEncoding)));
          }
          else if (frameCode.equals("TRCK") || frameCode.equals("TRK"))
          {
            String currStr = cleanString(new String(buf, offset + 1, frameSize - 1, textEncoding));
            //if (Sage.DBG) System.out.println("TRCK(track#)=" + currStr);
            rv.put(MediaFormat.META_TRACK, currStr);
          }
          else if (frameCode.equals("TPE1") || frameCode.equals("TP1"))
          {
            rv.put(MediaFormat.META_ARTIST, cleanString(new String(buf, offset + 1, frameSize - 1, textEncoding)));
            //if (Sage.DBG) System.out.println("TPE1(artist)=" + artist);
          }
          else if (frameCode.equals("TPE2") || frameCode.equals("TP2"))
          {
            rv.put(MediaFormat.META_ALBUM_ARTIST, cleanString(new String(buf, offset + 1, frameSize - 1, textEncoding)));
          }
          else if (frameCode.equals("TCON") || frameCode.equals("TCO"))
          {
            String category = cleanString(new String(buf, offset + 1, frameSize - 1, textEncoding));
            //if (Sage.DBG) System.out.println("TCON(content type)=" + category);
            // Check for a number in parethesis for the category. If this is there with no other text,
            // then we use that to look up the genre in the ID3V1 array. Otherwise if it's there with text
            // we just strip off the number and the parenthesis
            int paren1 = category.indexOf('(');
            if (paren1 != -1)
            {
              int paren2 = category.indexOf(')');
              if (paren2 > paren1)
              {
                String numText = category.substring(paren1 + 1, paren2);
                try
                {
                  int catNum = Integer.parseInt(numText);
                  if (sage.Sage.DBG) System.out.println("Converting numeric category of " + catNum);
                  String newCategory = (category.substring(0, paren1) + category.substring(paren2 + 1)).trim();
                  if (newCategory.length() == 0 && catNum >= 0 && catNum < ID3V1_GENRES.length)
                  {
                    category = ID3V1_GENRES[catNum];
                  }
                  else
                    category = newCategory;
                }
                catch (NumberFormatException e)
                {
                  if (sage.Sage.DBG) System.out.println("Error extracing numeric category:" + e);
                }
              }
            }
            else
            {
              // Check for a straight numeric category
              try
              {
                int catNum = Integer.parseInt(category);
                if (catNum >= 0 && catNum < ID3V1_GENRES.length)
                  category = ID3V1_GENRES[catNum];
              }
              catch (NumberFormatException e)
              {
                // This can happen normally if the category is non-numeric, which is allowed
              }
            }
            rv.put(MediaFormat.META_GENRE, category);
          }
          else if (frameCode.equals("TALB") || frameCode.equals("TAL"))
          {
            rv.put(MediaFormat.META_ALBUM, cleanString(new String(buf, offset + 1, frameSize - 1, textEncoding)));
            //if (Sage.DBG) System.out.println("TALB(album)=" + album);
          }
          else if (frameCode.equals("TYER") || frameCode.equals("TORY") || frameCode.equals("TYE") || frameCode.equals("TOR") ||
              frameCode.equals("TDAT") || frameCode.equals("TDRC") || frameCode.equals("TIME") || frameCode.equals("TRDA"))
          {
            String yearStr = cleanString(new String(buf, offset + 1, frameSize - 1, textEncoding));
            if (yearStr != null && (yearStr.length() == 4 || (yearStr.length() > 4 && yearStr.charAt(4) == '-')))
            {
              if (yearStr.length() > 4)
                yearStr = yearStr.substring(0, 4);
              rv.put(MediaFormat.META_YEAR, yearStr);
            }
            //if (Sage.DBG) System.out.println(frameCode + "(year)=" + year);
          }
          else if (frameCode.equals("APIC") || frameCode.equals("PIC"))
          {
            String mimeType;
            if (version <= 2)
              mimeType = "XX";
            else
              mimeType = cleanString(new String(buf, offset + 1, 128, textEncoding));
            byte pictureType = buf[offset + 2 + mimeType.length()];
            String pictureDesc;
            if (buf[offset + 3 + mimeType.length()] == 0)
              pictureDesc = "";
            else
              pictureDesc = cleanString(new String(buf, offset + 3 + mimeType.length(), 65, textEncoding));
            if (pictureDesc.length() > 0)
              rv.put(MediaFormat.META_THUMBNAIL_DESC, pictureDesc);
            int pictureOffset = offset + 3 + mimeType.length();
            if (doubleByteEncoding)
              pictureOffset += pictureDesc.length()*2 + 2;
            else
              pictureOffset += pictureDesc.length() + 1;
            int pictureLength = frameSize - (pictureOffset - offset);
            //thumbnailFile = theFile;
            //thumbnailOffset = pictureOffset;
            //thumbnailSize = pictureLength;
            // 10 is just an arbitrary, number. Basically something that's not just empty.
            if (pictureLength > 10)
            {
              rv.put(MediaFormat.META_THUMBNAIL_SIZE, Integer.toString(pictureLength));
              rv.put(MediaFormat.META_THUMBNAIL_OFFSET, Integer.toString(pictureOffset));
            }
            //if (Sage.DBG) System.out.println("Picture unicode="+unicodeText + " mime=" + mimeType + " picType=" + pictureType +
            //	" desc=" + pictureDesc + " offset=" + pictureOffset + " length=" + pictureLength);
          }
          offset += frameSize;
        }

      // Calculate the actual duration
      /*			randy.readFully(buf);
			duration = sage.MP3Utils.getMp3Duration(theFile);
			if (duration == 0)
			{
				long mpegAudioBitrate = getMpegAudioBitrate(buf, 0);
				if (mpegAudioBitrate > 0)
				{
					duration = 8*(randy.length() - fullHeaderSize)/mpegAudioBitrate;
					if (sage.Sage.DBG) System.out.println("Mpegaudiobitrate=" + mpegAudioBitrate + " duration=" + duration);
				}
			}
			if (duration != 0)
				rv.put(MediaFormat.META_DURATION, Long.toString(duration));*/
      /*if (duration == 0)
				duration = VideoFrame.getFileDuration(theFile.toString());
			if (duration == 0)
				duration = 1;
			if (title != null)
			{
				if (album == null)
					album = Sage.rez("Music_Single");
				if (artist != null && artist.length() == 0)
					artist = null;
				if (mediaType != MEDIATYPE_AUDIO)
				{
					title = namePrefix + title;
					String temp = album;
					album = title;
					title = temp;
				}
				if (artist != null)
					myAiring = Wizard.getInstance().addAiring(Wizard.getInstance().addShow(album, null, title,
						"", 0, category, null, new String[] { artist }, new byte[] { (mediaType == MEDIATYPE_AUDIO) ? Show.ARTIST_ROLE : Show.ACTOR_ROLE }, null, null,
       *///						year, null, null, "MP3" + Integer.toString(id), "English", 0), 0/*1000000 + id*/,
      //						theFile.lastModified() - duration, duration, (byte)track, (byte)0, (byte)0);
      //				else
      //					myAiring = Wizard.getInstance().addAiring(Wizard.getInstance().addShow(album, null, title,
      //						"", 0, category, null, new String[0] , new byte[0], null, null,
      //						year, null, null, "MP3" + Integer.toString(id), "English", 0), 0/*1000000 + id*/,
      //						theFile.lastModified() - duration, duration, (byte)track, (byte)0, (byte)0);
      //				infoAiringID = myAiring.id;
      //				return myAiring;
      //			}
      //			return null;
      return rv;
    }
    finally
    {
      randy.close();
    }
  }

}


text:
package org.gearvrf.animation;

import org.gearvrf.GVRHybridObject;
import org.gearvrf.GVRSceneObject;
import org.gearvrf.GVRTransform;

/** Animate an object's position. */
public class GVRRelativeMotionAnimation extends GVRTransformAnimation
{

    private final float mStartX, mDeltaX, mStartY, mDeltaY, mStartZ, mDeltaZ;

    /**
     * Animate a move by delta x/y/z.
     *
     * @param target
     *            {@link GVRTransform} to animate
     * @param duration
     *            The animation duration, in seconds.
     * @param deltaX
     *            The value to add to x
     * @param deltaY
     *            The value to add to y
     * @param deltaZ
     *            The value to add to z
     */
    public GVRRelativeMotionAnimation(GVRTransform target, float duration,
            float deltaX, float deltaY, float deltaZ) {
        super(target, duration);

        mStartX = mPosition.x;
        mStartY = mPosition.y;
        mStartZ = mPosition.z;

        mDeltaX = deltaX;
        mDeltaY = deltaY;
        mDeltaZ = deltaZ;
    }

    /**
     * Animate a move by delta x/y/z.
     *
     * @param target
     *            {@link GVRSceneObject} containing a {@link GVRTransform}
     * @param duration
     *            The animation duration, in seconds.
     * @param deltaX
     *            The value to add to x
     * @param deltaY
     *            The value to add to y
     * @param deltaZ
     *            The value to add to z
     */
    public GVRRelativeMotionAnimation(GVRSceneObject target, float duration,
            float deltaX, float deltaY, float deltaZ) {
        this(target.getTransform(), duration, deltaX, deltaY, deltaZ);
    }

    @Override
    protected void animate(GVRHybridObject target, float ratio) {
        mTransform.setPosition(mStartX + mDeltaX * ratio, //
                mStartY + mDeltaY * ratio, //
                mStartZ + mDeltaZ * ratio);
    }
}


text:
{-# LANGUAGE BangPatterns, OverloadedStrings #-}

-- |
-- Module:      Database.PostgreSQL.Simple.QueryResults
-- Copyright:   (c) 2011 Chris Done, 2011 MailRank, Inc.
-- License:     BSD3
-- Maintainer:  Chris Done <chrisdone@gmail.com>
-- Stability:   experimental
-- Portability: portable
--
-- The 'QueryResults' typeclass, for converting a row of results
-- returned by a SQL query into a more useful Haskell representation.
--
-- Predefined instances are provided for tuples containing up to ten
-- elements.

module Database.PostgreSQL.Simple.QueryResults
    ( QueryResults(..)
    , convertError
    ) where

import Control.Exception (throw)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B
import Database.PostgreSQL.Base.Types (Field(fieldType))
import Database.PostgreSQL.Simple.Result (ResultError(..), Result(..))
import Database.PostgreSQL.Simple.Types (Only(..))

-- | A collection type that can be converted from a list of strings.
--
-- Instances should use the 'convert' method of the 'Result' class
-- to perform conversion of each element of the collection.
--
-- This example instance demonstrates how to convert a two-column row
-- into a Haskell pair. Each field in the metadata is paired up with
-- each value from the row, and the two are passed to 'convert'.
--
-- @
-- instance ('Result' a, 'Result' b) => 'QueryResults' (a,b) where
--     'convertResults' [fa,fb] [va,vb] = (a,b)
--         where !a = 'convert' fa va
--               !b = 'convert' fb vb
--     'convertResults' fs vs  = 'convertError' fs vs
-- @
--
-- Notice that this instance evaluates each element to WHNF before
-- constructing the pair. By doing this, we guarantee two important
-- properties:
--
-- * Keep resource usage under control by preventing the construction
--   of potentially long-lived thunks.
--
-- * Ensure that any 'ResultError' that might arise is thrown
--   immediately, rather than some place later in application code
--   that cannot handle it.
--
-- You can also declare Haskell types of your own to be instances of
-- 'QueryResults'.
--
-- @
-- data User { firstName :: String, lastName :: String }

-- instance 'QueryResults' User where
--    'convertResults' [fa,fb] [va,vb] = User a b
--        where !a = 'convert' fa va
--              !b = 'convert' fb vb
--    'convertResults' fs vs  = 'convertError' fs vs
-- @

class QueryResults a where
    convertResults :: [Field] -> [Maybe ByteString] -> a
    -- ^ Convert values from a row into a Haskell collection.
    --
    -- This function will throw a 'ResultError' if conversion of the
    -- collection fails.

instance (Result a) => QueryResults (Only a) where
    convertResults [fa] [va] = Only a
        where !a = convert fa va
    convertResults fs vs  = convertError fs vs 1

instance (Result a, Result b) => QueryResults (a,b) where
    convertResults [fa,fb] [va,vb] = (a,b)
        where !a = convert fa va; !b = convert fb vb
    convertResults fs vs  = convertError fs vs 2

instance (Result a, Result b, Result c) => QueryResults (a,b,c) where
    convertResults [fa,fb,fc] [va,vb,vc] = (a,b,c)
        where !a = convert fa va; !b = convert fb vb; !c = convert fc vc
    convertResults fs vs  = convertError fs vs 3

instance (Result a, Result b, Result c, Result d) =>
    QueryResults (a,b,c,d) where
    convertResults [fa,fb,fc,fd] [va,vb,vc,vd] = (a,b,c,d)
        where !a = convert fa va; !b = convert fb vb; !c = convert fc vc
              !d = convert fd vd
    convertResults fs vs  = convertError fs vs 4

instance (Result a, Result b, Result c, Result d, Result e) =>
    QueryResults (a,b,c,d,e) where
    convertResults [fa,fb,fc,fd,fe] [va,vb,vc,vd,ve] = (a,b,c,d,e)
        where !a = convert fa va; !b = convert fb vb; !c = convert fc vc
              !d = convert fd vd; !e = convert fe ve
    convertResults fs vs  = convertError fs vs 5

instance (Result a, Result b, Result c, Result d, Result e, Result f) =>
    QueryResults (a,b,c,d,e,f) where
    convertResults [fa,fb,fc,fd,fe,ff] [va,vb,vc,vd,ve,vf] = (a,b,c,d,e,f)
        where !a = convert fa va; !b = convert fb vb; !c = convert fc vc
              !d = convert fd vd; !e = convert fe ve; !f = convert ff vf
    convertResults fs vs  = convertError fs vs 6

instance (Result a, Result b, Result c, Result d, Result e, Result f,
          Result g) =>
    QueryResults (a,b,c,d,e,f,g) where
    convertResults [fa,fb,fc,fd,fe,ff,fg] [va,vb,vc,vd,ve,vf,vg] =
        (a,b,c,d,e,f,g)
        where !a = convert fa va; !b = convert fb vb; !c = convert fc vc
              !d = convert fd vd; !e = convert fe ve; !f = convert ff vf
              !g = convert fg vg
    convertResults fs vs  = convertError fs vs 7

instance (Result a, Result b, Result c, Result d, Result e, Result f,
          Result g, Result h) =>
    QueryResults (a,b,c,d,e,f,g,h) where
    convertResults [fa,fb,fc,fd,fe,ff,fg,fh] [va,vb,vc,vd,ve,vf,vg,vh] =
        (a,b,c,d,e,f,g,h)
        where !a = convert fa va; !b = convert fb vb; !c = convert fc vc
              !d = convert fd vd; !e = convert fe ve; !f = convert ff vf
              !g = convert fg vg; !h = convert fh vh
    convertResults fs vs  = convertError fs vs 8

instance (Result a, Result b, Result c, Result d, Result e, Result f,
          Result g, Result h, Result i) =>
    QueryResults (a,b,c,d,e,f,g,h,i) where
    convertResults [fa,fb,fc,fd,fe,ff,fg,fh,fi] [va,vb,vc,vd,ve,vf,vg,vh,vi] =
        (a,b,c,d,e,f,g,h,i)
        where !a = convert fa va; !b = convert fb vb; !c = convert fc vc
              !d = convert fd vd; !e = convert fe ve; !f = convert ff vf
              !g = convert fg vg; !h = convert fh vh; !i = convert fi vi
    convertResults fs vs  = convertError fs vs 9

instance (Result a, Result b, Result c, Result d, Result e, Result f,
          Result g, Result h, Result i, Result j) =>
    QueryResults (a,b,c,d,e,f,g,h,i,j) where
    convertResults [fa,fb,fc,fd,fe,ff,fg,fh,fi,fj]
                   [va,vb,vc,vd,ve,vf,vg,vh,vi,vj] =
        (a,b,c,d,e,f,g,h,i,j)
        where !a = convert fa va; !b = convert fb vb; !c = convert fc vc
              !d = convert fd vd; !e = convert fe ve; !f = convert ff vf
              !g = convert fg vg; !h = convert fh vh; !i = convert fi vi
              !j = convert fj vj
    convertResults fs vs  = convertError fs vs 10

-- | Throw a 'ConversionFailed' exception, indicating a mismatch
-- between the number of columns in the 'Field' and row, and the
-- number in the collection to be converted to.
convertError :: [Field] -> [Maybe ByteString] -> Int -> a
convertError fs vs n = throw $ ConversionFailed
    (show (length fs) ++ " values: " ++ show (zip (map fieldType fs)
                                                  (map (fmap ellipsis) vs)))
    (show n ++ " slots in target type")
    "mismatch between number of columns to convert and number in target type"

ellipsis :: ByteString -> ByteString
ellipsis bs
    | B.length bs > 15 = B.take 10 bs `B.append` "[...]"
    | otherwise        = bs


text:
# I worked on this challenge [by myself].

# smallest_integer is a method that takes an array of integers as its input
# and returns the smallest integer in the array
#
# +list_of_nums+ is an array of integers
# smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+
#
# If +list_of_nums+ is empty the method should return nil

# Your Solution Below
def smallest_integer(list_of_nums)
	list_of_nums.sort!
	return list_of_nums[0]
end


text:
'use strict';

define([
  'angular',
  'camunda-bpm-sdk'],
function(
  angular,
  CamSDK
) {
  var apiModule = angular.module('cam.casemanager.client', []);

  apiModule.value('HttpClient', CamSDK.Client);

  apiModule.value('CamForm', CamSDK.Form);

  apiModule.factory('camAPIHttpClient', [
           '$rootScope',
  function($rootScope) {

    function AngularClient(config) {
      this._wrapped = new CamSDK.Client.HttpClient(config);
    }

    angular.forEach(['post', 'get', 'load', 'put', 'del'], function(name) {
      AngularClient.prototype[name] = function(path, options) {
        if (!options.done) {
          return;
        }

        var original = options.done;

        options.done = function(err, result) {
          $rootScope.$apply(function() {
            original(err, result);
          });
        };

        this._wrapped[name](path, options);
      };
    });

    angular.forEach(['on', 'once', 'off', 'trigger'], function(name) {
      AngularClient.prototype[name] = function() {
        this._wrapped[name].apply(this, arguments);
      };
    });

    return AngularClient;
  }]);

  apiModule.factory('camAPI', [
          'camAPIHttpClient',
  function(camAPIHttpClient) {
    var conf = {
      apiUri:     'engine-rest/engine',
      HttpClient: camAPIHttpClient
    };

    if (window.casemanagerConf) {
      for (var c in window.casemanagerConf) {
        conf[c] = window.casemanagerConf[c];
      }
    }

    return new CamSDK.Client(conf);
  }]);

  return apiModule;
});


text:
package ua.in.badparking.ui.fragments;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import ua.in.badparking.BuildConfig;
import ua.in.badparking.services.ClaimService;
import ua.in.badparking.utils.LogHelper;

import static ua.in.badparking.utils.LogHelper.CLAIM_STATE_TAG;

/**
 * Created by Dima Kovalenko on 7/4/16.
 */
public class BaseFragment extends Fragment {

    private InputMethodManager inputManager;
    protected boolean isTablet;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inputManager = (InputMethodManager)getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        boolean large = ((getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
        boolean xlarge = ((getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
        isTablet = large || xlarge;
    }

    public void removePhoneKeypad() {
        IBinder binder = getView().getWindowToken();
        inputManager.hideSoftInputFromWindow(binder,
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    protected void claimStateLogging(){
        String log = LogHelper.getClaimStateLog(this.getClass(), ClaimService.INST.getClaim());
        Log.d(CLAIM_STATE_TAG, log);

        if (!BuildConfig.DEBUG) {
            Toast toast = Toast.makeText(getContext(), log, Toast.LENGTH_LONG);
            toast.show();
        }
    }
}


text:
<?php

namespace Pluma\Models;

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Pluma\Support\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use SoftDeletes;

    protected $fillable = ['email', 'username', 'password'];
}