text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {addEntries, ENTRIES, RootPath, sendTestMessage, TestEntryInfo} from '../test_util.js';
import {testcase} from '../testcase.js';

import {isSinglePartitionFormat, navigateWithDirectoryTree, openNewWindow, remoteCall, setupAndWaitUntilReady} from './background.js';
import {BASIC_ANDROID_ENTRY_SET, BASIC_ANDROID_ENTRY_SET_WITH_HIDDEN, BASIC_DRIVE_ENTRY_SET, BASIC_DRIVE_ENTRY_SET_WITH_HIDDEN, BASIC_LOCAL_ENTRY_SET, BASIC_LOCAL_ENTRY_SET_WITH_HIDDEN, COMPLEX_DOCUMENTS_PROVIDER_ENTRY_SET} from './test_data.js';

/**
 * Gets the common steps to toggle hidden files in the Files app
 * @param {!Array<!TestEntryInfo>} basicSet Files expected before showing hidden
 * @param {!Array<!TestEntryInfo>} hiddenEntrySet Files expected after showing
 * hidden
 */
function runHiddenFilesTest(appId, basicSet, hiddenEntrySet) {
  return runHiddenFilesTestWithMenuItem(
      appId, basicSet, hiddenEntrySet, '#gear-menu-toggle-hidden-files');
}

/**
 * Gets the common steps to toggle Android hidden files in the Files app
 * @param {!Array<!TestEntryInfo>} basicSet Files expected before showing hidden
 * @param {!Array<!TestEntryInfo>} hiddenEntrySet Files expected after showing
 * hidden
 */
function runAndroidHiddenFilesTest(appId, basicSet, hiddenEntrySet) {
  return runHiddenFilesTestWithMenuItem(
      appId, basicSet, hiddenEntrySet,
      '#gear-menu-toggle-hidden-android-folders');
}

/**
 * Gets the common steps to toggle hidden files in the Files app
 * @param {!Array<!TestEntryInfo>} basicSet Files expected before showing hidden
 * @param {!Array<!TestEntryInfo>} hiddenEntrySet Files expected after showing
 * hidden
 * @param {string} toggleMenuItemSelector Selector for the menu item that
 * toggles hidden file visibility
 */
async function runHiddenFilesTestWithMenuItem(
    appId, basicSet, hiddenEntrySet, toggleMenuItemSelector) {
  await remoteCall.waitForElement(appId, '#gear-button:not([hidden])');

  // Open the gear menu by clicking the gear button.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Wait for menu to not be hidden.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Wait for menu item to appear.
  await remoteCall.waitForElement(
      appId, toggleMenuItemSelector + ':not([disabled])');

  // Wait for menu item to appear.
  await remoteCall.waitForElement(
      appId, toggleMenuItemSelector + ':not([checked])');

  // Click the menu item.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, [toggleMenuItemSelector]));

  // Wait for item to be checked.
  await remoteCall.waitForElement(appId, toggleMenuItemSelector + '[checked]');

  // Check the hidden files are displayed.
  await remoteCall.waitForFiles(
      appId, TestEntryInfo.getExpectedRows(hiddenEntrySet),
      {ignoreFileSize: true, ignoreLastModifiedTime: true});

  // Repeat steps to toggle again.
  await remoteCall.waitForElement(appId, '#gear-button:not([hidden])');
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');
  await remoteCall.waitForElement(
      appId, toggleMenuItemSelector + ':not([disabled])');
  await remoteCall.waitForElement(appId, toggleMenuItemSelector + '[checked]');
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, [toggleMenuItemSelector]));

  await remoteCall.waitForElement(
      appId, toggleMenuItemSelector + ':not([checked])');
  await remoteCall.waitForFiles(
      appId, TestEntryInfo.getExpectedRows(basicSet),
      {ignoreFileSize: true, ignoreLastModifiedTime: true});
}

/**
 * Tests toggling the show-hidden-files menu option on Downloads.
 */
testcase.showHiddenFilesDownloads = async () => {
  const appId = await setupAndWaitUntilReady(
      RootPath.DOWNLOADS, BASIC_LOCAL_ENTRY_SET_WITH_HIDDEN, []);

  await runHiddenFilesTest(
      appId, BASIC_LOCAL_ENTRY_SET, BASIC_LOCAL_ENTRY_SET_WITH_HIDDEN);
};

/**
 * Tests toggling the show-hidden-files menu option on Drive.
 */
testcase.showHiddenFilesDrive = async () => {
  const appId = await setupAndWaitUntilReady(
      RootPath.DRIVE, [], BASIC_DRIVE_ENTRY_SET_WITH_HIDDEN);

  await runHiddenFilesTest(
      appId, BASIC_DRIVE_ENTRY_SET, BASIC_DRIVE_ENTRY_SET_WITH_HIDDEN);
};

/**
 * Tests that toggle-hidden-android-folders menu item exists when "Play files"
 * is selected, but hidden in Recents.
 */
testcase.showToggleHiddenAndroidFoldersGearMenuItemsInMyFiles = async () => {
  // Open Files.App on Play Files.
  const appId = await openNewWindow(RootPath.ANDROID_FILES);
  await addEntries(['android_files'], BASIC_ANDROID_ENTRY_SET);

  // Wait for the file list to appear.
  await remoteCall.waitForElement(appId, '#file-list');
  await remoteCall.waitForFiles(
      appId, TestEntryInfo.getExpectedRows(BASIC_ANDROID_ENTRY_SET));

  // Click the gear menu button.
  const gearButton =
      await remoteCall.waitAndClickElement(appId, '#gear-button:not([hidden])');

  // Check: gear-button has aria-haspopup set to true
  chrome.test.assertEq(gearButton.attributes['aria-haspopup'], 'true');

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // #toggle-hidden-android-folders command should be shown and disabled by
  // default.
  await remoteCall.waitForElement(
      appId,
      '#gear-menu-toggle-hidden-android-folders' +
          ':not([checked]):not([hidden])');

  // Click the file list: the gear menu should hide.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#file-list']));

  // Wait for the gear menu to hide.
  await remoteCall.waitForElement(appId, '#gear-menu[hidden]');

  // Navigate to Recent.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['span[root-type-icon=\'recent\']']));

  // Click the gear menu button.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // #toggle-hidden-android-folders command should be hidden.
  await remoteCall.waitForElement(
      appId, '#gear-menu-toggle-hidden-android-folders[hidden]');
};

/**
 * Tests that "Play files" shows the full set of files after
 * toggle-hidden-android-folders is enabled.
 */
testcase.enableToggleHiddenAndroidFoldersShowsHiddenFiles = async () => {
  // Open Files.App on Play Files.
  const appId = await openNewWindow(RootPath.ANDROID_FILES);
  await addEntries(['android_files'], BASIC_ANDROID_ENTRY_SET_WITH_HIDDEN);

  // Wait for the file list to appear.
  await remoteCall.waitForElement(appId, '#file-list');

  // Wait for the gear menu button to appear.
  await remoteCall.waitForElement(appId, '#gear-button:not([hidden])');
  await runAndroidHiddenFilesTest(
      appId, BASIC_ANDROID_ENTRY_SET, BASIC_ANDROID_ENTRY_SET_WITH_HIDDEN);
};

/**
 * Tests that the current directory is changed to "Play files" after the
 * current directory is hidden by toggle-hidden-android-folders option.
 */
testcase.hideCurrentDirectoryByTogglingHiddenAndroidFolders = async () => {
  const MENU_ITEM_SELECTOR = '#gear-menu-toggle-hidden-android-folders';
  const appId = await openNewWindow(RootPath.ANDROID_FILES);
  await addEntries(['android_files'], BASIC_ANDROID_ENTRY_SET_WITH_HIDDEN);

  // Wait for the file list to appear.
  await remoteCall.waitForElement(appId, '#file-list');
  await remoteCall.waitForFiles(
      appId, TestEntryInfo.getExpectedRows(BASIC_ANDROID_ENTRY_SET));

  // Wait for the gear menu button to appear.
  await remoteCall.waitAndClickElement(appId, '#gear-button:not([hidden])');

  // Wait for menu to not be hidden.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Wait for menu item to appear.
  await remoteCall.waitForElement(
      appId, MENU_ITEM_SELECTOR + ':not([disabled]):not([checked])');

  // Click the menu item.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, [MENU_ITEM_SELECTOR]));

  // Wait for item to be checked.
  await remoteCall.waitForElement(appId, MENU_ITEM_SELECTOR + '[checked]');

  // Check the hidden files are displayed.
  await remoteCall.waitForFiles(
      appId, TestEntryInfo.getExpectedRows(BASIC_ANDROID_ENTRY_SET_WITH_HIDDEN),
      {ignoreFileSize: true, ignoreLastModifiedTime: true});

  // Navigate to "/My files/Play files/A".
  await remoteCall.navigateWithDirectoryTree(
      appId, '/A', 'My files/Play files', 'android_files');

  // Wait until current directory is changed to "/My files/Play files/A".
  await remoteCall.waitUntilCurrentDirectoryIsChanged(
      appId, '/My files/Play files/A');

  // Open the gear menu by clicking the gear button.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Wait for menu to not be hidden.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Wait for menu item to appear.
  await remoteCall.waitForElement(
      appId, MENU_ITEM_SELECTOR + '[checked]:not([disabled])');

  // Click the menu item.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, [MENU_ITEM_SELECTOR]));

  // Wait until the current directory is changed from
  // "/My files/Play files/A" to "/My files/Play files" since
  // "/My files/Play files/A" is invisible now.
  await remoteCall.waitUntilCurrentDirectoryIsChanged(
      appId, '/My files/Play files');
};

/**
 * Tests the paste-into-current-folder menu item.
 */
testcase.showPasteIntoCurrentFolder = async () => {
  const entrySet = [ENTRIES.hello, ENTRIES.world];

  // Add files to Downloads volume.
  await addEntries(['local'], entrySet);

  // Open Files.App on Downloads.
  const appId = await openNewWindow(RootPath.DOWNLOADS);
  await remoteCall.waitForElement(appId, '#file-list');

  // Wait for the files to appear in the file list.
  await remoteCall.waitForFiles(appId, TestEntryInfo.getExpectedRows(entrySet));

  // Wait for the gear menu button to appear.
  await remoteCall.waitForElement(appId, '#gear-button');

  // 1. Before selecting entries: click the gear menu button.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // #paste-into-current-folder command is shown. It should be disabled
  // because no file has been copied to clipboard.
  await remoteCall.waitForElement(
      appId,
      '#gear-menu cr-menu-item' +
          '[command=\'#paste-into-current-folder\']' +
          '[disabled]:not([hidden])');
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#file-list']));

  await remoteCall.waitForElement(appId, '#gear-menu[hidden]');

  // 2. Selecting a single regular file
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'selectFile', appId, [ENTRIES.hello.nameText]));

  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Wait for menu to appear.
  // The command is still shown.
  await remoteCall.waitForElement(
      appId,
      '#gear-menu:not([hidden]) cr-menu-item' +
          '[command=\'#paste-into-current-folder\']' +
          '[disabled]:not([hidden])');
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#file-list']));

  await remoteCall.waitForElement(appId, '#gear-menu[hidden]');

  // 3. When ready to paste a file
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'selectFile', appId, [ENTRIES.hello.nameText]));

  // Ctrl-C to copy the selected file
  await remoteCall.fakeKeyDown(appId, '#file-list', 'c', true, false, false);
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // The command appears enabled.
  await remoteCall.waitForElement(
      appId,
      '#gear-menu:not([hidden])' +
          ' cr-menu-item[command=\'#paste-into-current-folder\']' +
          ':not([disabled]):not([hidden])');
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#file-list']));

  await remoteCall.waitForElement(appId, '#gear-menu[hidden]');
};

/**
 * Tests the "select-all" menu item.
 */
testcase.showSelectAllInCurrentFolder = async () => {
  const entrySet = [ENTRIES.newlyAdded];

  // Open Files.App on Downloads.
  const appId = await openNewWindow(RootPath.DOWNLOADS);
  await remoteCall.waitForElement(appId, '#file-list');

  // Wait for the gear menu button to appear.
  await remoteCall.waitForElement(appId, '#gear-button');

  // Click the gear menu button.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Check: #select-all command is shown, but disabled (no files yet).
  await remoteCall.waitForElement(
      appId,
      '#gear-menu cr-menu-item' +
          '[command=\'#select-all\']' +
          '[disabled]:not([hidden])');

  // Click the file list: the gear menu should hide.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#file-list']));

  // Wait for the gear menu to hide.
  await remoteCall.waitForElement(appId, '#gear-menu[hidden]');

  // Add a new file to Downloads.
  await addEntries(['local'], entrySet);

  // Wait for the file list change.
  await remoteCall.waitForFiles(appId, TestEntryInfo.getExpectedRows(entrySet));

  // Click on the gear button again.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Check: #select-all command is shown, and enabled (there are files).
  await remoteCall.waitForElement(
      appId,
      '#gear-menu:not([hidden]) cr-menu-item' +
          '[command=\'#select-all\']' +
          ':not([disabled]):not([hidden])');

  // Click on the #gear-menu-select-all item.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-menu-select-all']));

  // Check: the file-list should be selected.
  await remoteCall.waitForElement(appId, '#file-list li[selected]');
};

/**
 * Tests that new folder appears in the gear menu with Downloads focused in the
 * directory tree.
 */
testcase.newFolderInDownloads = async () => {
  const appId =
      await setupAndWaitUntilReady(RootPath.DOWNLOADS, [ENTRIES.hello], []);

  // Focus the directory tree.
  await remoteCall.callRemoteTestUtil('focus', appId, ['#directory-tree']);

  // Open the gear menu.
  await remoteCall.waitForElement(appId, '#gear-button');

  // Open the gear meny by a shortcut (Alt-E).
  chrome.test.assertTrue(
      await remoteCall.fakeKeyDown(appId, 'body', 'e', false, false, true));

  // Wait for menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu');

  // Wait for menu to appear, containing new folder.
  await remoteCall.waitForElement(
      appId, '#gear-menu-newfolder:not([disabled]):not([hidden])');
};

/**
 * Tests that Send feedback appears in the gear menu.
 */
testcase.showSendFeedbackAction = async () => {
  const entrySet = [ENTRIES.newlyAdded];

  // Open Files.App on Downloads.
  const appId = await openNewWindow(RootPath.DOWNLOADS);
  await remoteCall.waitForElement(appId, '#file-list');

  // Wait for the gear menu button to appear.
  await remoteCall.waitForElement(appId, '#gear-button');

  // Click the gear menu button.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Check #send-feedback is shown and it's enabled.
  await remoteCall.waitForElement(
      appId,
      '#gear-menu:not([hidden]) cr-menu-item' +
          '[command=\'#send-feedback\']' +
          ':not([disabled]):not([hidden])');
};

/**
 * Tests that clicking the gear menu's help button from a Downloads location
 * navigates the user to the Files app's help page.
 */
testcase.openHelpPageFromDownloadsVolume = async () => {
  // Open Files App on Downloads.
  const appId = await openNewWindow(RootPath.DOWNLOADS);
  await remoteCall.waitForElement(appId, '#file-list');

  // Click the gear menu button.
  await remoteCall.waitAndClickElement(appId, '#gear-button');

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Check that #volume-help is shown and enabled and click it.
  const volumeHelpQuery = '#gear-menu:not([hidden]) ' +
      'cr-menu-item[command=\'#volume-help\']:not([disabled]):not([hidden])';
  await remoteCall.waitAndClickElement(appId, volumeHelpQuery);

  // Check that the last visited URL is the Files app's help page.
  const filesHelpURL = await remoteCall.callRemoteTestUtil(
      'getTranslatedString', appId, ['FILES_APP_HELP_URL']);
  chrome.test.assertEq(
      filesHelpURL,
      await remoteCall.callRemoteTestUtil('getLastVisitedURL', appId, []));
};

/**
 * Tests that clicking the gear menu's help button from a drive location
 * navigates the user to the Google drive help page.
 */
testcase.openHelpPageFromDriveVolume = async () => {
  // Open Files App on Downloads.
  const appId = await openNewWindow(RootPath.DRIVE);
  await remoteCall.waitForElement(appId, '#file-list');

  // Click the gear menu button.
  await remoteCall.waitAndClickElement(appId, '#gear-button');

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Check that #volume-help is shown and enabled and click it.
  const volumeHelpQuery = '#gear-menu:not([hidden]) ' +
      'cr-menu-item[command=\'#volume-help\']:not([disabled]):not([hidden])';
  await remoteCall.waitAndClickElement(appId, volumeHelpQuery);

  // Check that the last visited URL is the Google Drive's help page.
  const driveHelpURL = await remoteCall.callRemoteTestUtil(
      'getTranslatedString', appId, ['GOOGLE_DRIVE_HELP_URL']);
  chrome.test.assertEq(
      driveHelpURL,
      await remoteCall.callRemoteTestUtil('getLastVisitedURL', appId, []));
};

/**
 * Tests that the link of the volume space info item in the gear menu is
 * disabled when the files app is opened on the Google Drive section, and active
 * otherwise. The volume space info item should only link to the storage
 * settings page when the user is navigating within local folders.
 */
testcase.enableDisableStorageSettingsLink = async () => {
  const appId = await setupAndWaitUntilReady(
      RootPath.DRIVE, [], BASIC_DRIVE_ENTRY_SET_WITH_HIDDEN);

  // Click the gear menu button.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Check: volume space info should be disabled for Drive.
  await remoteCall.waitForElement(appId, '#volume-space-info[disabled]');

  // Navigate to Android files.
  await remoteCall.waitAndClickElement(
      appId, '#directory-tree [entry-label="Play files"]');

  // Click the gear menu button.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Check: volume space info should be enabled for Play files.
  await remoteCall.waitForElement(appId, '#volume-space-info:not([disabled])');

  // Mount empty USB volume.
  await sendTestMessage({name: 'mountFakeUsbEmpty'});

  // Wait for the USB mount.
  await remoteCall.waitAndClickElement(
      appId, '#directory-tree [volume-type-icon="removable"]');

  // Click the gear menu button.
  chrome.test.assertTrue(await remoteCall.callRemoteTestUtil(
      'fakeMouseClick', appId, ['#gear-button']));

  // Check: volume space info should be disabled for external volume.
  await remoteCall.waitForElement(appId, '#volume-space-info[disabled]');
};

/**
 * Tests that the "xGB available" message appears in the gear menu for
 * the "My Files" volume.
 */
testcase.showAvailableStorageMyFiles = async () => {
  // Open Files app on Downloads containing ENTRIES.photos.
  const appId =
      await setupAndWaitUntilReady(RootPath.DOWNLOADS, [ENTRIES.photos], []);

  // Wait for the gear menu button to appear and click it.
  await remoteCall.waitAndClickElement(appId, '#gear-button');

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Check #volume-storage is shown and it's enabled.
  await remoteCall.waitForElement(
      appId,
      '#gear-menu:not([hidden]) cr-menu-item' +
          '[command=\'#volume-storage\']' +
          ':not([disabled]):not([hidden])');
};

/**
 * Tests that the "xGB available message appears in the gear menu for
 * the "Google Drive" volume.
 */
testcase.showAvailableStorageDrive = async () => {
  // Open Files app on Drive containing ENTRIES.hello.
  const appId =
      await setupAndWaitUntilReady(RootPath.DRIVE, [], [ENTRIES.hello]);

  // Wait for the gear menu button to appear and click it.
  await remoteCall.waitAndClickElement(appId, '#gear-button');

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Check #volume-storage is shown and disabled (can't manage Drive
  // storage).
  await remoteCall.waitForElement(
      appId,
      '#gear-menu:not([hidden]) cr-menu-item' +
          '[command=\'#volume-storage\']' +
          ':not([hidden])');
};

/**
 * Tests that the "xGB available message appears in the gear menu for
 * an SMB volume.
 */
testcase.showAvailableStorageSmbfs = async () => {
  // Populate Smbfs with some files.
  await addEntries(['smbfs'], BASIC_LOCAL_ENTRY_SET);

  // Mount Smbfs volume.
  await sendTestMessage({name: 'mountSmbfs'});

  // Open Files app on Downloads containing ENTRIES.photos.
  const appId =
      await setupAndWaitUntilReady(RootPath.DOWNLOADS, [ENTRIES.photos], []);

  await navigateWithDirectoryTree(appId, '/SMB Share');

  // Wait for the volume's file list to appear.
  const files = TestEntryInfo.getExpectedRows(BASIC_LOCAL_ENTRY_SET);
  await remoteCall.waitForFiles(appId, files, {ignoreLastModifiedTime: true});

  // Wait for the gear menu button to appear and click it.
  await remoteCall.waitAndClickElement(appId, '#gear-button');

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Check #volume-storage is shown and disabled (can't manage SMB
  // storage).
  await remoteCall.waitForElement(
      appId,
      '#gear-menu:not([hidden]) cr-menu-item' +
          '[command=\'#volume-storage\']' +
          ':not([hidden])');
};

/**
 * Tests that the "xGB available message appears in the gear menu for
 * the DocumentsProvider volume.
 */
testcase.showAvailableStorageDocProvider = async () => {
  const documentsProviderVolumeQuery =
      '[has-children="true"] [volume-type-icon="documents_provider"]';

  // Add files to the DocumentsProvider volume.
  await addEntries(
      ['documents_provider'], COMPLEX_DOCUMENTS_PROVIDER_ENTRY_SET);

  // Open Files app.
  const appId = await openNewWindow(RootPath.DOWNLOADS);

  // Wait for the DocumentsProvider volume to mount.
  await remoteCall.waitForElement(appId, documentsProviderVolumeQuery);

  // Click to open the DocumentsProvider volume.
  chrome.test.assertTrue(
      !!await remoteCall.callRemoteTestUtil(
          'fakeMouseClick', appId, [documentsProviderVolumeQuery]),
      'fakeMouseClick failed');

  // Check: the DocumentsProvider files should appear in the file list.
  const files =
      TestEntryInfo.getExpectedRows(COMPLEX_DOCUMENTS_PROVIDER_ENTRY_SET);
  await remoteCall.waitForFiles(appId, files, {ignoreLastModifiedTime: true});

  // Wait for the gear menu button to appear and click it.
  await remoteCall.waitAndClickElement(appId, '#gear-button');

  // Wait for the gear menu to appear.
  await remoteCall.waitForElement(appId, '#gear-menu:not([hidden])');

  // Check #volume-storage is shown and disabled (can't manage DocumentsProvider
  // storage).
  await remoteCall.waitForElement(
      appId,
      '#gear-menu:not([hidden]) cr-menu-item' +
          '[command=\'#volume-storage\']' +
          ':not([hidden])');
};


text:
<?php

namespace ShopBundle\Form;

use Doctrine\ORM\EntityRepository;
use Sonata\AdminBundle\Form\ChoiceList\ModelChoiceList;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use ShopBundle\Form\ImageType;
use Ivory\CKEditorBundle\Form\Type\CKEditorType;

class ProductType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name',TextType::class,array('required' => false, 'label'=>'_name'))
            ->add('slug',TextType::class,array('required' => false, 'label'=>'_slug'))
            ->add('sku',TextType::class,array('required' => false, 'label'=>'_sku'))
            ->add('isActive', CheckboxType::class,array('required' => false, 'label'=>'_isActive'))

            ->add('category', EntityType::class, array(
                'class' => 'CategoryBundle:Category',
                'choice_label' => 'name',
                'label' => '_category',
            ))

            ->add('price', IntegerType::class,array('required' => false, 'label'=>'_price',
                'attr'=>['min' => 0,00000001]
                ))
            ->add('minusPrice',IntegerType::class,array('required' => false, 'label'=>'_minusPrice',
                'attr'=>['min' => 0,00000001]
                ))
            ->add('amount',IntegerType::class,array('required' => false, 'label'=>'_amount',
                'attr'=>['min' => 1]
                ))
            ->add('metaTitle', TextareaType::class, ['label' => '_metaTitle', 'required' => false])
            ->add('metaKeywords', TextareaType::class, ['label' => '_metaKeywords', 'required' => false])
            ->add('metaDescription', TextareaType::class, ['label' => '_metaDescription', 'required' => false])

            ->add('description',  CKEditorType::class,
                array('label' => '_description', 'required' => false,'config' => array('uiColor' => '#ffffff')))

        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ShopBundle\Entity\Product'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'shopbundle_product';
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace {

class AppListShowerTestSuite : public base::TestSuite {
 public:
  AppListShowerTestSuite(int argc, char** argv) : base::TestSuite(argc, argv) {}

 protected:
  void Initialize() override {
    gfx::GLSurfaceTestSupport::InitializeOneOff();
    base::TestSuite::Initialize();
    ui::RegisterPathProvider();

    base::FilePath ui_test_pak_path;
    ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path));
    ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path);
  }

  void Shutdown() override {
    ui::ResourceBundle::CleanupSharedInstance();
    base::TestSuite::Shutdown();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(AppListShowerTestSuite);
};

}  // namespace

int main(int argc, char** argv) {
  AppListShowerTestSuite test_suite(argc, argv);

  return base::LaunchUnitTests(
      argc, argv,
      base::Bind(&AppListShowerTestSuite::Run, base::Unretained(&test_suite)));
}


text:
<?php
namespace Cucu\Phalcon\Oauth2\Storage;

use League\OAuth2\Server\Entity\RefreshTokenEntity;
use League\OAuth2\Server\Storage\RefreshTokenInterface;

use Phalcon\Db;
use Phalcon\Mvc\User\Plugin;

use Cucu\Phalcon\Oauth2\Storage\StorageTrait;
/**
 * @property \Phalcon\Db\Adapter\Pdo\Sqlite $db
 */
class RefreshToken implements RefreshTokenInterface
{
    use StorageTrait;
    protected $db;
    public function __construct($db)
    {
        if(! $this->db) {
            $this->db = $db;
        }
    }
    /**
     * Return a new instance of \League\OAuth2\Server\Entity\RefreshTokenEntity
     * @param  string $token
     * @return \League\OAuth2\Server\Entity\RefreshTokenEntity
     */
    public function get($token)
    {
        $result = $this->db->fetchAll(
            "SELECT * FROM oauth_refresh_tokens WHERE refresh_token = ? AND expire_time >= ?",
            Db::FETCH_ASSOC,
            [$token, time()]
        );

        if (count($result) === 1) {
            $token = (new RefreshTokenEntity($this->server))
                ->setId($result[0]['refresh_token'])
                ->setExpireTime($result[0]['expire_time'])
                ->setAccessTokenId($result[0]['access_token']);
            return $token;
        }
        return null;
    }
    /**
     * Create a new refresh token_name
     * @param  string $token
     * @param  integer $expireTime
     * @param  string $accessToken
     * @return \League\OAuth2\Server\Entity\RefreshTokenEntity
     */
    public function create($token, $expireTime, $accessToken)
    {
        $this->db->insert(
            'oauth_refresh_tokens',
            [$token, $accessToken, $expireTime],
            ['refresh_token', 'access_token', 'expire_time']
        );
    }
    /**
     * Delete the refresh token
     * @param  \League\OAuth2\Server\Entity\RefreshTokenEntity $token
     * @return void
     */
    public function delete(RefreshTokenEntity $token)
    {
        $this->db->delete(
            "oauth_refresh_tokens",
            "refresh_token = ?",
            [$token->getId()]
        );
    }
}


text:
"""
Functions that run on executor for measurement.

These functions are responsible for building the tvm module, uploading it to
remote devices, recording the running time costs, and checking the correctness of the output.
"""

import contextlib
import logging
import os
import shutil
import tempfile
import threading
import time
import typing
from collections import namedtuple
from random import getrandbits
import warnings

import tvm._ffi
import tvm.ir.transform
from tvm import nd
from tvm import rpc as _rpc
from tvm.autotvm.env import AutotvmGlobalScope, reset_global_scope
from tvm.contrib import ndk, stackvm, tar
from tvm.contrib.popen_pool import PopenPoolExecutor
from tvm.driver import build
from tvm.error import TVMError
from tvm.target import Target

from ..env import AutotvmGlobalScope
from ..task.space import InstantiationError
from ..utils import get_const_tuple
from .measure import Builder, MeasureErrorNo, MeasureResult, Runner

logger = logging.getLogger("autotvm")

class BuildResult(namedtuple("BuildResult", ("filename", "arg_info", "error", "time_cost"))):
    """
    Stores all the necessary inputs for a measurement.

    Parameters
    ----------
    filename : str
        The filename of generated library
    arg_info : Tuple
        The shape and dtype information of tvm tensor arguments
    error : Exception
        The error happens during compilation.
    time_cost : float
        The time cost of building
    """

class LocalBuilder(Builder):
    """Run compilation on local machine

    Parameters
    ----------
    timeout: float
        The timeout of a compilation
    n_parallel: int
        The number of tasks run in parallel. "None" will use all cpu cores
    build_kwargs: dict
        If supplied, additional kwargs passed to build_func. Overrides any build_kwargs supplied
        by the Runner.
    build_func: callable or str
        If is 'default', use default build function
        If is 'ndk', use function for android ndk
        If id 'stackvm', use function for stackvm
        If is callable, use it as custom build function, expect lib_format field.
    do_fork: bool
        If False, do not fork when building. Requires n_parallel=1.
    runtime: Optional[Runtime]
        Specify the runtime to generate artifacts for
    """

    def __init__(
        self,
        timeout=10,
        n_parallel=None,
        build_kwargs=None,
        build_func="default",
        do_fork=False,
        runtime=None,
    ):
        super(LocalBuilder, self).__init__(timeout, n_parallel, build_kwargs)

        if isinstance(build_func, str):
            if build_func == "default":
                build_func = tar.tar
            elif build_func == "ndk":
                build_func = ndk.create_shared
            elif build_func == "stackvm":
                build_func = stackvm.build
            else:
                raise ValueError("Invalid build_func" + build_func)
        self.build_func = _WrappedBuildFunc(build_func, runtime)
        if not do_fork:
            assert n_parallel in (
                None,
                1,
            ), f"if do_fork=False, need n_parallel=None or 1; got {n_parallel}"
        self.executor = PopenPoolExecutor(
            timeout=timeout, initializer=reset_global_scope, initargs=(AutotvmGlobalScope.current,)
        )
        self.tmp_dir = tempfile.mkdtemp()

    def build(self, measure_inputs):
        results = []

        shutil.rmtree(self.tmp_dir, ignore_errors=True)
        self.tmp_dir = tempfile.mkdtemp()

        for i in range(0, len(measure_inputs), self.n_parallel):
            futures = []
            for inp in measure_inputs[i : i + self.n_parallel]:
                ret = self.executor.submit(self.build_func, inp, self.tmp_dir, **self.build_kwargs)
                futures.append(ret)

            for future in futures:
                try:
                    res = future.result()
                    if res.error is not None:
                        # instantiation error
                        if isinstance(res.error, InstantiationError):
                            res = MeasureResult(
                                (res.error,),
                                MeasureErrorNo.INSTANTIATION_ERROR,
                                res.time_cost,
                                time.time(),
                            )

                        else:
                            if "InstantiationError" in str(res.error):
                                msg = str(res.error)
                                try:
                                    msg = msg.split("\n")[-2].split(": ")[1]
                                except Exception:  # pylint: disable=broad-except
                                    pass
                                res = MeasureResult(
                                    (InstantiationError(msg),),
                                    MeasureErrorNo.INSTANTIATION_ERROR,
                                    res.time_cost,
                                    time.time(),
                                )

                            else:  # tvm error
                                res = MeasureResult(
                                    (res.error,),
                                    MeasureErrorNo.COMPILE_HOST,
                                    res.time_cost,
                                    time.time(),
                                )
                except TimeoutError as ex:
                    res = MeasureResult(
                        (ex,), MeasureErrorNo.BUILD_TIMEOUT, self.timeout, time.time()
                    )
                except ChildProcessError as ex:
                    res = MeasureResult(
                        (ex,),
                        MeasureErrorNo.RUNTIME_DEVICE,
                        self.timeout,
                        time.time(),
                    )

                results.append(res)

        return results

class RPCRunner(Runner):
    """Run generated code on remove devices.
    This function will ask a RPC Tracker to get device for measurement.

    Parameters
    ----------
    timeout: float
        The timeout of a RPCRunner measurement task
    n_parallel: int
        The number of tasks run in parallel. "None" will use all cpu cores
    key: str
        The key of the device registered in the tracker
    host: str
        The host address of RPC Tracker
    port: int
        The port of RPC Tracker
    number: int
        The number of times to run the generated code for taking average.
        We call these runs as one `repeat` of measurement.
    repeat : int, optional
        The number of times to repeat the measurement.
        In total, the generated code will be run (1 + number x repeat) times,
        where the first "1" is warm up and will be discarded.
        The returned result contains `repeat` costs,
        each of which is an average of `number` costs.
    min_repeat_ms: int, optional
        The minimum duration of one `repeat` in milliseconds.
        By default, one `repeat` contains `number` runs. If this parameter is set,
        the parameters `number` will be dynamically adjusted to meet the
        minimum duration requirement of one `repeat`.
        i.e., When the run time of one `repeat` falls below this time, the `number` parameter
        will be automatically increased.
    cooldown_interval: float, optional
        The cool down interval between two measurements.
    enable_cpu_cache_flush: bool
        Whether to flush cache on CPU between repeated measurements.
        Flushing cache can make the measured latency of one operator closer to
        its actual latency during end-to-end inference.
        To make this option effective, the argument `number` should also be set to 1.
        This is only has effect on CPU task.
    module_loader : ModuleLoader
        If given, a context manager that loads the module to be timed into the remote runtime.
        If not given, default_module_loader is used.
    """

    def __init__(
        self,
        key,
        host,
        port,
        priority=1,
        timeout=10,
        n_parallel=None,
        number=4,
        repeat=3,
        min_repeat_ms=0,
        cooldown_interval=0.1,
        enable_cpu_cache_flush=False,
        module_loader=None,
    ):
        super(RPCRunner, self).__init__(timeout, n_parallel)

        self.key = key
        self.host = host
        self.port = port
        self.priority = priority
        self.timeout = timeout

        self.number = number
        self.repeat = repeat
        self.min_repeat_ms = min_repeat_ms
        self._ref_input = None

        self.enable_cpu_cache_flush = enable_cpu_cache_flush
        self.cooldown_interval = cooldown_interval
        self.module_loader = module_loader

        self.executor = PopenPoolExecutor(
            timeout=timeout * (self.n_parallel + 1),
            initializer=reset_global_scope,
            initargs=(AutotvmGlobalScope.current,),
        )

    @property
    def ref_input(self):
        """
        Fixed input for tuning special operators, e.g., sparse operators
        requiring indices as input.
        """
        return self._ref_input

    @ref_input.setter
    def ref_input(self, val):
        if val is not None:
            warnings.warn(
                "You are specifying fixed input for tuning the operator. "
                "Be sure your input always fits the operator. Some "
                "operators may conduct layout transformation during tuning, "
                "thus can lead to unexpected behaviors. ",
                RuntimeWarning,
            )
        self._ref_input = val

    def set_task(self, task):
        self.task = task

        if check_remote(task.target, self.key, self.host, self.port):
            logger.info("Get devices for measurement successfully!")
        else:
            raise RuntimeError(
                "Cannot get remote devices from the tracker. "
                "Please check the status of tracker by "
                "'python -m tvm.exec.query_rpc_tracker --port [THE PORT YOU USE]' "
                "and make sure you have free devices on the queue status."
            )

    def get_build_kwargs(self):
        kwargs = {}
        if (
            "cuda" in self.task.target.keys
            or "opencl" in self.task.target.keys
            or "rocm" in self.task.target.keys
            or "vulkan" in self.task.target.keys
        ):
            remote = request_remote(self.key, self.host, self.port)
            dev = remote.device(str(self.task.target), 0)
            max_dims = dev.max_thread_dimensions
            kwargs["check_gpu"] = {
                "max_shared_memory_per_block": dev.max_shared_memory_per_block,
                "max_threads_per_block": dev.max_threads_per_block,
                "max_thread_x": max_dims[0],
                "max_thread_y": max_dims[1],
                "max_thread_z": max_dims[2],
            }

        return kwargs

    def run(self, measure_inputs, build_results):
        results = []
        remote_kwargs = dict(
            device_key=self.key,
            host=self.host,
            port=self.port,
            priority=self.priority,
            timeout=self.timeout,
        )

        for i in range(0, len(measure_inputs), self.n_parallel):
            futures = []
            for measure_inp, build_res in zip(
                measure_inputs[i : i + self.n_parallel], build_results[i : i + self.n_parallel]
            ):
                module_loader = (
                    self.module_loader
                    if self.module_loader is not None
                    else default_module_loader()
                )
                ret = self.executor.submit(
                    run_through_rpc,
                    measure_inp,
                    build_res,
                    self.number,
                    self.repeat,
                    self.min_repeat_ms,
                    self.cooldown_interval,
                    remote_kwargs,
                    self.ref_input,
                    self.enable_cpu_cache_flush,
                    module_loader,
                )
                futures.append(ret)

            for future in futures:
                try:
                    res = future.result()
                    results.append(res)
                except Exception as ex:  # pylint: disable=broad-except
                    results.append(
                        MeasureResult(
                            (str(ex),), MeasureErrorNo.RUN_TIMEOUT, self.timeout, time.time()
                        )
                    )

        return results

class LocalRunner(RPCRunner):
    """Run generated code on local devices.

    Parameters
    ----------
    timeout: float
        The timeout of a compilation
    number: int
        The number of times to run the generated code for taking average.
        We call these runs as one `repeat` of measurement.
    repeat : int, optional
        The number of times to repeat the measurement.
        In total, the generated code will be run (1 + number x repeat) times,
        where the first one is warm up and will be discarded.
        The returned result contains `repeat` costs,
        each of which is an average of `number` costs.
    min_repeat_ms: int, optional
        The minimum duration of one `repeat` in milliseconds.
        By default, one `repeat` contains `number` runs. If this parameter is set,
        the parameters `number` will be dynamically adjusted to meet the
        minimum duration requirement of one `repeat`.
        i.e., When the run time of one `repeat` falls below this time, the `number` parameter
        will be automatically increased.
    cooldown_interval: float, optional
        The cool down interval between two measurements.
    enable_cpu_cache_flush: bool
        Whether to flush cache on CPU between repeated measurements.
        Flushing cache can make the measured latency of one operator closer to
        its actual latency during end-to-end inference.
        To make this option effective, the argument `number` should also be set to 1.
        This is only has effect on CPU task.
    Note
    ----
    This is a "fake" local mode. We start a silent rpc tracker and rpc server
    for the user. In this way we reuse timeout/isolation mechanism in RPC infrastructure.
    """

    def __init__(
        self,
        timeout=10,
        number=4,
        repeat=3,
        min_repeat_ms=0,
        cooldown_interval=0.1,
        enable_cpu_cache_flush=False,
        module_loader=None,
    ):
        super(LocalRunner, self).__init__(
            "",
            None,
            None,
            0,
            timeout=timeout,
            n_parallel=1,
            number=number,
            repeat=repeat,
            min_repeat_ms=min_repeat_ms,
            cooldown_interval=cooldown_interval,
            enable_cpu_cache_flush=enable_cpu_cache_flush,
            module_loader=module_loader,
        )
        self.tracker = None
        self.server = None

    def set_task(self, task):
        # pylint: disable=import-outside-toplevel
        from ...rpc.server import Server
        from ...rpc.tracker import Tracker

        self.task = task
        tracker = Tracker(port=9000, port_end=10000, silent=True)
        device_key = "$local$device$%d" % tracker.port
        server = Server(
            port=9000,
            port_end=10000,
            key=device_key,
            silent=True,
            tracker_addr=("127.0.0.1", tracker.port),
        )
        self.key = device_key
        self.host = "127.0.0.1"
        self.port = tracker.port

        super(LocalRunner, self).set_task(task)
        return server, tracker

def _build_func_common(measure_input, runtime=None, check_gpu=None, build_option=None):
    """Common part for building a configuration"""
    target, task, config = measure_input
    target, task.target_host = Target.check_and_update_host_consist(target, task.target_host)

    with target:
        s, args = task.instantiate(config)

        # check invalidity of template and code hash consistency
        if not config.valid():
            raise InstantiationError(config.errors)

        opts = build_option or {}
        if check_gpu:  # Add verify pass to filter out invalid configs in advance.
            opts["tir.add_lower_pass"] = [(2, gpu_verify_pass(**check_gpu))]

        # if target is vta, we need to use vta build
        if (
            hasattr(measure_input.target, "device_name")
            and measure_input.target.device_name == "vta"
        ):
            # pylint: disable=import-outside-toplevel
            import vta

            func = vta.build(s, args, target_host=task.target_host)
        else:
            with tvm.ir.transform.PassContext(config=opts):
                func = build(s, args, target_host=task.target_host, runtime=runtime)
    return func, tuple((get_const_tuple(x.shape), x.dtype) for x in args)

class _WrappedBuildFunc:
    """
    Wrap build_func to a function that can be used in measure.

    Note: this is a class instead of a closure so that it can be pickled when
    using multiprocessing.

    Parameters
    ----------
    build_func : The compilation function
        We expect fcompile to contain an attr "output_format".
    runtime : Optional[Runtime]
        The runtime to generate artifacts for

    Returns
    -------
    wrapped_build_func : callable
        The wrapped build function
    """

    def __init__(self, build_func, runtime=None):
        if not hasattr(build_func, "output_format"):
            raise AttributeError("Expect build_func to have the attribute output_format.")
        self.build_func = build_func
        self.runtime = runtime

    def __call__(self, measure_input, tmp_dir, **kwargs):
        """
        Wrapped build func.

        Parameters
        ----------
        measure_input: MeasureInput
            The input of measurement

        tmp_dir: str
            The path of temporary directory to export generated library
        """
        tic = time.time()
        try:
            filename = os.path.join(
                tmp_dir, "tmp_func_%0x.%s" % (getrandbits(64), self.build_func.output_format)
            )
            # TODO(tvm-team) consider linline _build_func_common
            func, arg_info = _build_func_common(measure_input, self.runtime, **kwargs)
            if self.build_func.output_format == ".model-library-format":
                # Late import to preserve autoTVM with USE_MICRO OFF
                try:
                    from tvm import micro  # pylint: disable=import-outside-toplevel
                except ImportError:
                    raise ImportError("Requires USE_MICRO")
                micro.export_model_library_format(func, filename)
            else:
                func.export_library(filename, self.build_func)
        except Exception as e:  # pylint: disable=broad-except
            return BuildResult(None, None, e, time.time() - tic)
        return BuildResult(filename, arg_info, None, time.time() - tic)

ModuleLoader = typing.Callable[
    [dict, dict], typing.ContextManager[typing.Tuple[tvm.rpc.RPCSession, tvm.runtime.Module]]
]

def run_through_rpc(
    measure_input,
    build_result,
    number,
    repeat,
    min_repeat_ms,
    cooldown_interval,
    remote_kwargs,
    ref_input,
    enable_cpu_cache_flush=False,
    module_loader=None,
):
    """Run a generated library through rpc

    Parameters
    ----------
    measure_input: MeasureInput
        The raw measure input
    build_result: BuildResult
        The result returned from Builder. This contains the path to the generated library.
    number: int
        The number of times to run the generated code for taking average.
        We call these runs as one `repeat` of measurement.
    repeat : int, optional
        The number of times to repeat the measurement.
        In total, the generated code will be run (1 + number x repeat) times,
        where the first one is warm up and will be discarded.
        The returned result contains `repeat` costs,
        each of which is an average of `number` costs.
    min_repeat_ms: int, optional
        The minimum duration of one `repeat` in milliseconds.
        By default, one `repeat` contains `number` runs. If this parameter is set,
        the parameters `number` will be dynamically adjusted to meet the
        minimum duration requirement of one `repeat`.
        i.e., When the run time of one `repeat` falls below this time, the `number` parameter
        will be automatically increased.
    cooldown_interval: float
        The cool down interval between two measurements
    remote_kwargs: dict
        Passed to module_loader(). Ultimately, keyword args to request_remote().
    ref_input: List of np.ndarray
        The reference input used for tuning. Empty for randomly filled input.
    enable_cpu_cache_flush: bool
        Whether to flush cache on CPU between repeated measurements.
        Flushing cache can make the measured latency of one operator closer to
        its actual latency during end-to-end inference.
        To make this option effective, the argument `number` should also be set to 1.
        This is only has effect on CPU task.
    module_loader: ModuleLoader
        A function that returns a ContextManager used to establish and teardown the remote session.
    """
    if isinstance(build_result, MeasureResult):
        return build_result

    tic = time.time()
    errno = MeasureErrorNo.NO_ERROR
    try:
        # upload built module
        with module_loader(remote_kwargs, build_result) as (remote, mod):
            dev = remote.device(str(measure_input.target), 0)

            # Limitation:
            # We can not get PackFunction directly in the remote mode as it is wrapped
            # under the std::function. We could lift the restriction later once we fold
            # the PackedFunc as an object. Currently, we pass function name to work
            # around it.
            f_prepare = "cache_flush_cpu_non_first_arg" if enable_cpu_cache_flush else ""
            time_f = mod.time_evaluator(
                mod.entry_name,
                dev,
                number=number,
                repeat=repeat,
                min_repeat_ms=min_repeat_ms,
                f_preproc=f_prepare,
            )

            if ref_input:
                args = [nd.array(x, device=dev) for x in ref_input]
            else:
                try:
                    random_fill = remote.get_function("tvm.contrib.random.random_fill")
                except AttributeError:
                    raise AttributeError(
                        "Please make sure USE_RANDOM is ON in the config.cmake "
                        "on the remote devices"
                    )
                args = [nd.empty(x[0], x[1], dev) for x in build_result.arg_info]
                if "scatter" not in measure_input.task.name:
                    # the index tensor of scatter op cannot be randomly initialized
                    for arg in args:
                        random_fill(arg)
                dev.sync()

            costs = time_f(*args).results

        if len(costs) > 2:  # remove largest and smallest value to reduce variance
            costs = list(costs)
            costs.sort()
            costs = tuple(costs[1:-1])
    except TVMError as exc:
        msg = str(exc)
        if "Stack trace returned" in msg:
            msg = msg[: msg.index("Stack trace returned")]
        if "CUDA Source" in msg:
            msg = msg[: msg.index("CUDA Source")]
        costs = (RuntimeError(msg[:1024]),)
        errno = MeasureErrorNo.RUNTIME_DEVICE
    tstamp = time.time()
    time.sleep(cooldown_interval)
    return MeasureResult(costs, errno, tstamp - tic + build_result.time_cost, tstamp)

class DefaultModuleLoader:
    """See default_module_loader(). A pickleable emulation of the original function closure."""

    def __init__(self, pre_load_function=None) -> None:
        self.pre_load_function = pre_load_function

    @contextlib.contextmanager
    def __call__(self, remote_kwargs, build_result):
        remote = request_remote(**remote_kwargs)
        if self.pre_load_function is not None:
            self.pre_load_function(remote, build_result)

        remote.upload(build_result.filename)
        try:
            yield remote, remote.load_module(os.path.split(build_result.filename)[1])

        finally:
            # clean up remote files
            remote.remove(build_result.filename)
            remote.remove(os.path.splitext(build_result.filename)[0] + ".so")
            remote.remove("")

def default_module_loader(pre_load_function=None):
    """Returns a default function that can be passed as module_loader to run_through_rpc.

    Parameters
    ----------
    pre_load_function : Optional[Function[tvm.rpc.Session, tvm.runtime.Module]]
        Invoked after a session is established and before the default code-loading RPC calls are
        issued. Allows performing pre-upload actions, e.g. resetting the remote runtime environment.

    Returns
    -------
    DefaultModuleLoader :
        A callable that can be passed as module_loader to run_through_rpc.
    """

    # This was a function with a closure before but that couldn't be pickled!
    # We need pickle to work for using python's multiprocessing on some platforms.
    return DefaultModuleLoader(pre_load_function)

def request_remote(device_key, host=None, port=None, priority=1, timeout=60):
    """Request a remote session

    Parameters
    ----------
    device_key: string
        The device key of registered device in tracker
    host: host, optional
        The host address of rpc tracker.
        If is none, will use environment variable "TVM_TRACKER_HOST"
    port: int, optional
        The port of rpc tracker.
        If is none, will use environment variable "TVM_TRACKER_PORT"
    priority: int, optional
        The priority of this request, larger is more prior
    timeout: float, optional
        The timeout of this session (units: second)

    Returns
    ------
    session: RPCSession
    """
    # connect to the tracker
    host = host or os.environ["TVM_TRACKER_HOST"]
    port = port or int(os.environ["TVM_TRACKER_PORT"])

    tracker = _rpc.connect_tracker(host, port)
    remote = tracker.request(device_key, priority=priority, session_timeout=timeout)
    return remote

def check_remote(target, device_key, host=None, port=None, priority=100, timeout=10):
    """
    Check the availability of a remote device

    Parameters
    ----------
    target: Target
        The wanted compilation target
    device_key: string
        device key of registered device in tracker
    host: host, optional
        The host address of rpc tracker.
        If is none, will use environment variable "TVM_TRACKER_HOST"
    port: int, optional
        The port address of rpc tracker.
        If is none, will use environment variable "TVM_TRACKER_PORT"
    priority: int, optional
        The priority of this request, larger is more prior
    timeout: float, optional
        The timeout of this check (units: seconds).

    Returns
    -------
    available: bool
        True if can find available device
    """

    def _check():
        remote = request_remote(device_key, host, port, priority)
        dev = remote.device(str(target))
        while not dev.exist:  # wait until we get an available device
            pass

    t = threading.Thread(
        target=_check,
    )
    t.start()
    t.join(timeout)
    return not t.is_alive()

def set_cuda_target_arch(arch):
    """THIS API IS DEPRECATED.

    set target architecture of nvcc compiler

    Parameters
    ----------
    arch: str or list
        The argument of nvcc -arch. (e.g. "sm_51", "sm_62")
        it can also be a count of gencode arguments pass to nvcc command line,
        e.g., ["-gencode", "arch=compute_52,code=sm_52", "-gencode", "arch=compute_70,code=sm_70"]
    """
    raise ValueError(
        "The API 'autotvm.measure.set_cuda_target_arch' is deprecated."
        "Try specifying it by adding '-arch=sm_xx' to your target, such as 'cuda -arch=sm_86'."
        "See https://github.com/apache/tvm/pull/9544 for the upgrade guide."
    )

def gpu_verify_pass(**kwargs):
    """Verify the validity of a gpu kernel.
    This pass will check memory usage and number of threads per block.
    """

    def verify_pass(f, *_):
        valid = tvm.tir.analysis.verify_gpu_code(f, kwargs)
        if not valid:
            raise InstantiationError("Skipped because of invalid gpu kernel")
        return f

    return tvm.tir.transform.prim_func_pass(verify_pass, opt_level=0)


text:
require 'spec_helper'
require 'torkify/log/parser'

module Torkify::Log
  describe LineMatcher do
    shared_examples "a ruby error" do
      let(:matcher) { LineMatcher.new line }

      context "calling ruby_error?" do
        subject { matcher.ruby_error? }

        it { should be_true }
      end
    end

    shared_examples "an error description" do
      let(:matcher) { LineMatcher.new line }

      context "calling error_description?" do
        subject { matcher.error_description? }

        it { should be_true }
      end
    end

    shared_examples "a tork load line" do
      let(:matcher) { LineMatcher.new line }

      context "calling tork_load_line?" do
        subject { matcher.tork_load_line? }

        it { should be_true }
      end
    end

    shared_examples "a tork error line" do
      let(:matcher) { LineMatcher.new line }

      context "calling tork_error_line?" do
        subject { matcher.tork_error_line? }

        it { should be_true }
      end
    end

    shared_examples "the end of errors" do
      let(:matcher) { LineMatcher.new line }

      context "calling end_of_errors?" do
        subject { matcher.end_of_errors? }

        it { should be_true }
      end
    end

    shared_examples "a test error or failure" do
      let(:matcher) { LineMatcher.new line }

      context "calling test_error_or_failure?" do
        subject { matcher.test_error_or_failure? }

        it { should be_true }
      end
    end

    shared_examples "a finished line" do
      let(:matcher) { LineMatcher.new line }

      context "calling finished_line?" do
        subject { matcher.finished_line? }

        it { should be_true }
      end
    end

    shared_examples "a test summary" do
      let(:matcher) { LineMatcher.new line }

      context "calling test_summary?" do
        subject { matcher.test_summary? }

        it { should be_true }
      end
    end

    context "the starting line of a ruby fatal error" do
      let(:line) do <<LIN
test/unit/address_test.rb:3:in `<top (required)>': uninitialized constant Tes (NameError)
LIN
      end

      it_behaves_like "a ruby error"

      context "calling ruby_error" do
        let(:matches) { LineMatcher.new(line).ruby_error }

        context "the whole match" do
          subject { matches[0] }
          it { should == "test/unit/address_test.rb:3:in" }
        end
        context "the file" do
          subject { matches[1] }
          it { should == "test/unit/address_test.rb" }
        end
        context "the line number" do
          subject { matches[2] }
          it { should == "3" }
        end
      end
    end

    context "the starting line of another ruby fatal error" do
      let(:line) do <<LIN
/home/jon/.rvm/gems/ruby-1.9.3-p286/gems/tork-19.3.0/lib/tork/master.rb:62:in `load': spec/line_matcher_spec.rb:79: syntax error, unexpected keyword_end, expecting '}' (SyntaxError)
LIN
      end

      it_behaves_like "a ruby error"
    end

    context "the starting line of an rspec test failure" do
      let(:line) do <<LIN
  1) torklog::linematcher with the starting line of a ruby fatal error calling test_error_or_failure?"
LIN
      end

      it_behaves_like "a test error or failure"
    end

    context "a line of a test::unit test failure" do
      let(:line) { "  15) Failure: " }

      it_behaves_like "a test error or failure"
    end

    context "an rpsec test summary line" do
      let(:line) { "6 examples, 0 failures" }

      it_behaves_like "a test summary"
      it_behaves_like "the end of errors"
    end

    context "a test::unit test summary line" do
      let(:line) do <<LIN
1 tests, 11 assertions, 3 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
LIN
      end

      it_behaves_like "a test summary"
      it_behaves_like "the end of errors"
    end

    context "a test::unit finished line" do
      let(:line) { "Finished in 1.0396772 seconds." }

      it_behaves_like "a finished line"
      it_behaves_like "the end of errors"
    end

    context "the final line of an rspec error" do
      let(:line) do <<LIN
     # spec/integration_spec.rb:20:in `block (3 levels) in <module:TorkLog>'
LIN
      end

      it_behaves_like "an error description"

      context "calling error_description" do
        let(:matches) { LineMatcher.new(line).error_description }

        context "the whole match" do
          subject { matches[0] }
          it { should == "     # spec/integration_spec.rb:20:in" }
        end
        context "the file" do
          subject { matches[1] }
          it { should == "spec/integration_spec.rb" }
        end
        context "the line number" do
          subject { matches[2] }
          it { should == "20" }
        end
      end
    end

    context "the final line of an test::unit error" do
      let(:line) do <<LIN
    test/integration/user_flows_test.rb:8:in `block (2 levels) in <class:UserFlowsTest>'
LIN
      end

      it_behaves_like "an error description"

      context "calling error_description" do
        let(:matches) { LineMatcher.new(line).error_description }

        context "the whole match" do
          subject { matches[0] }
          it { should == "    test/integration/user_flows_test.rb:8:in" }
        end
        context "the file" do
          subject { matches[1] }
          it { should == "test/integration/user_flows_test.rb" }
        end
        context "the line number" do
          subject { matches[2] }
          it { should == "8" }
        end
      end
    end

    context "a tork load line" do
      let(:line) { "Loaded suite tork-worker[1] test/unit/address_test" }

      it_behaves_like "a tork load line"

      context "calling tork_load_line" do
        let(:matches) { LineMatcher.new(line).tork_load_line }

        context "the whole match" do
          subject { matches[0] }
          it { should == "Loaded suite tork-worker[1] test/unit/address_test" }
        end
        context "the file" do
          subject { matches[1] }
          it { should == "test/unit/address_test" }
        end
      end
    end

    context "a tork error line" do
      let(:line) { "/home/jon/.rvm/gems/ruby-1.9.3-p286/gems/tork-19.3.0/lib/tork/master.rb:62:in `load': spec/integration_spec.rb:6: syntax error, unexpected $end, expecting keyword_end (SyntaxError)" }

      it_behaves_like "a tork error line"

      context "calling tork_error_line" do
        let(:matches) { LineMatcher.new(line).tork_error_line }

        context "the whole match" do
          subject { matches[0] }
          it { should == "/home/jon/.rvm/gems/ruby-1.9.3-p286/gems/tork-19.3.0/lib/tork/master.rb:62:in `load': " }
        end
      end
    end
  end
end


text:
const gulp = require('gulp');
const uglify = require('gulp-uglify-es').default;
const rename = require("gulp-rename");

gulp.task("uglify", function () {
    return gulp.src(["app/static/*.js", "!app/static/*.min.js"])
        .pipe(uglify())
        .pipe(rename({
            suffix: ".min"
        }))
        .pipe(gulp.dest("app/static/"));
});

gulp.task('default', ['minify'], function() {
    console.log("Finished");
});