text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Material Admin Documentation</title>
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="css/style.css">

Material Admin Documentation

            Demo
            Purchase

About Material Admin

Project Structure

NodeJs and NPM

Installation

GruntJs

Change Log

Upgrading from 1.5.1

About Material Admin

Material Admin is a Google Material Design inspired powerful-lightweight fully responsive retina display compatible admin template based on latest Bootstrap 3. Material Admin comes with both jQuery and AngularJs versions.

Unless like other admin templates, all the plugin used in Material Admin are completely customized to match the Material Design.

Project structure

Toggle between tabs for both jQuery and AngularJs project structures

jQuery

AngularJs

- css
  -- app.1.min.css
  -- app.2.min.css

- fonts
- img
- js
  -- flot-charts
  -- charts.js
  -- demo.js
  -- functions.js

- less
  -- inc
  -- app.less

- media
- node_modules
- vendors
  -- bower_components

  gruntfile.js
  package.json
  index.html
  ...

- css
  -- app.1.min.css
  -- app.2.min.css

- data
- fonts
- img
- js
  -- controller
  -- modules
  -- app.js
  -- config.js
  -- services.js
  -- template.js

- less
  -- inc
  -- app.less

- media
- node_modules
- templates
- vendors
  -- bower_components

- views

  gruntfile.js
  package.json
  index.html
  ...

About CSS files

All LESS files including third party's are compiled in to a single CSS file and, splitted in to 2 minified pieces in order to gain support for IE 9. In IE 9, a sheet may contain up to only 4095 selectors and anything above will be ignored.

Make sure to include both app.min.1.css and app.min.2.css in your project files in proper sequence.

NodeJs and NPM

Material Admin comes with GruntJs for automated tasks and a complete set of third party dependencies. Source files of these dependencies are not included in your downloaded directory and in order to install them, you'll need to have NodeJs and NPM installed in your computer. Make sure to install this duo before your proceed anything with your new project.

NodeJs

Installing NPM

Installation

Make sure to install both NodeJs and NPM in your computer as mentioned in previous section, before you proceed anything in this section.

Extract the file downloaded using any file archive utility software.

Copy all the files and folders from template directory to your project directory.

                                Install all the NPM dependencies by firing the following command in your main project directory where you can find package.json

npm install

That's it. Now you can start previewing Material Admin.

Useful Links

                        Bower: Getting Started

                        How to manage your frontend dependencies with Bower

GruntJs

GruntJs is a task-based command line build tool for JavaScript projects. It helps making most of our manual tasks to automate such as minifying, compiling, splitting etc. In Material Admin, GruntJs is been used for:

Compiling LESS to CSS.

Splitting main CSS file to sub instances.

Minification of CSS and JS files

Template Caching (AngularJs)

All the above tasks are added in gruntfile.js which is available in the main project folder. gruntfile just creates a basic grunt.js that you can fill in with tasks.

Installing GruntJs

GruntJs is available as a NPM package and already included in our main NPM dependency list in package.json

Doing a simple:

npm install

                        as mentioned in 'NodeJs and NPM', will install all the dependencies including GruntJs.

Before you make any changes...

before you make any changes in less or template (Angularjs) directory files, make sure to run:

grunt watch

grunt watch is a file watcher which will execute certain tasks when any given file changes. All less files and template files in angularjs variant should be watched in order to make changes in the output files (css and template.js).

Useful Links

                        GruntJs: Getting Started

                        Meet Grunt: The Build Tool for JavaScript

Change Log

Newly added

Malihu Content Scroller plugin (Replacing Nicescroll)

Page Loader

Pre Loaders (preloaders.html)

3 level sub-menus in mainmenu

Custom headers

Description and Address in Typography (typography)

Basic Documentation

Updated

Bootstrap library

AngularJs library (AngularJs)

Top Search

Image icons to Font icons in top menu

New color scheme for Alerts (alerts.html)

Fixed

Color Picker display (AngularJs - form-components.html))

Href link new window in Summernote HTML Editor (jQuery - form-components.html)

Tooltip Position (components.html)

Dropdown Flipin animation in Safari browser (components.html)

Arrow key accessibility in Typeahead plugin (form-components.html)

Arrow key accessibility in Chosen plugin (form-components.html)

Removed

Nicescroll plugin

Upgrade Notes

Those who upgrading from version 1.5.1 to this release, please follow the changes below.

Replacing Custom Scrollbar

                            In this release, previously used NiceScroll custom scrollbar plugin has been replaced with
                            Malihu Content Scroller.

                                Copy Malihu Content Scroller plugin from newly downloaded Material Admin package to your project vendors/bower_components/malihu-custom-scrollbar-plugin.

                                Alternatively, you can install it from Bower.

bower install malihu-custom-scrollbar-plugin --save

                                Link CSS file

    <link href="vendors/bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.min.css" rel="stylesheet">

                                Link JS file and remove old Nicescroll reference.

    <script src="vendors/bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min.js"></script>

                                Initiate the plugin.

jQuery

AngularJs

Replace code in js/functions.js under comment 'Scrollbar' with

function scrollBar(selector, theme, mousewheelaxis) {
    $(selector).mCustomScrollbar({
        theme: theme,
        scrollInertia: 100,
        axis:'yx',
        mouseWheel: {
            enable: true,
            axis: mousewheelaxis,
            preventDefault: true
        }
    });
}

if (!$('html').hasClass('ismobile')) {
    //On Custom Class
    if ($('.c-overflow')[0]) {
        scrollBar('.c-overflow', 'minimal-dark', 'y');
    }
}

Replace code in js/services.js under comment 'Nice Scroll - Custom Scroll bars' with

.service('scrollService', function() {
    var ss = {};
    ss.malihuScroll = function scrollBar(selector, theme, mousewheelaxis) {
        $(selector).mCustomScrollbar({
            theme: theme,
            scrollInertia: 100,
            axis:'yx',
            mouseWheel: {
                enable: true,
                axis: mousewheelaxis,
                preventDefault: true
            }
        });
    }

    return ss;
})

Replace code in js/modules/ui.js under comment 'NICE SCROLL' with

.directive('cOverflow', ['scrollService', function(scrollService){
    return {
        restrict: 'C',
        link: function(scope, element) {

            if (!$('html').hasClass('ismobile')) {
                scrollService.malihuScroll(element, 'minimal-dark', 'y');
            }
        }
    }
}])

Markup Changes

Header - New release comes with support for custom header colors. An extra attribute is required in ordre to activate this feature.

                                Code before

<header id="header">

                            Code now

<header id="header" class="clearfix" data-current-skin="blue">

Header Menu - Image icons to Font Icons.

                                Code before

<li class="dropdown">
    <a data-toggle="dropdown" class="tm-message" href=""><i class="tmn-counts">6</i></a>
    ...

                                Code now

<li class="dropdown">
    <a data-toggle="dropdown" href="">
        <i class="tm-icon zmdi zmdi-email"></i>
        <i class="tmn-counts">6</i>
    </a>
    ...

Header Search

                                Code before

<div id="top-search-wrap">
    <input type="text">
    <i id="top-search-close">×</i>
</div>

                            Code now

<div id="top-search-wrap">
    <div class="tsw-inner">>
        <i id="top-search-close" class="zmdi zmdi-arrow-left"></i>
        <input type="text">
    </div>
</div>

Sidebars (Menu and Chat)

                                Code before

<aside id="sidebar"> <!-- or id="chat" for chat sidebar -->
    <div class="sidebar-inner c-overflow">
        ...

                            Code now

<aside id="sidebar" class="sidebar c-overflow"> <!-- or id="chat" for chat sidebar -->
    ...

Sidebar Profile Menu

                                Code before

<div class="profile-menu">
    <a href="">
        <div class="profile-pic">
            <img src="img/profile-pics/1.jpg" alt="">
        </div>

        <div class="profile-info">
            Malinda Hollaway

            <i class="zmdi zmdi-arrow-drop-down"></i> <!-- this -->
        </div>
    </a>
    ...

                                Code now

<div class="profile-menu">
    <a href="">
        <div class="profile-pic">
            <img src="img/profile-pics/1.jpg" alt="">
        </div>

        <div class="profile-info">
            Malinda Hollaway

            <i class="zmdi zmdi-caret-down"></i> <!-- this -->
        </div>
    </a>
    ...

Floating form label (in form-elements.html and widgets.html)

                                Code before

<div class="form-group fg-float">
    <div class="fg-line">
        <input type="text" class="input-sm form-control fg-input">
    </div>
    <label class="fg-label">Input Small</label>
</div>

                                Code now

<div class="form-group fg-float">
    <div class="fg-line">
        <input type="text" class="input-sm form-control fg-input">
        <label class="fg-label">Input Small</label>
    </div>
</div>

Chosen library reference (in form-components.html) -  Now it's part of bower_components

                                Code before

<!-- css -->
<link href="vendors/chosen_v1.4.2/chosen.min.css" rel="stylesheet">

<!-- js -->
<script src="vendors/chosen_v1.4.2/chosen.jquery.min.js"></script>

                            Code now

<!-- css -->
<link href="vendors/bower_components/chosen/chosen.min.css" rel="stylesheet">

<!-- js -->
<script src="vendors/bower_components/chosen/chosen.jquery.min.js"></script>

Page loading animation - Add the codes below in all pages before closing body tag.

<div class="page-loader">
    <div class="preloader pls-blue">
        <svg class="pl-circular" viewBox="25 25 50 50">
            <circle class="plc-path" cx="50" cy="50" r="20" />
        </svg>

        <p>Please wait...</p>
    </div>
</div>


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

package org.chromium.chrome.browser.customtabs.features.toolbar;

import static org.chromium.chrome.browser.dependency_injection.ChromeCommonQualifiers.APP_CONTEXT;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.browser.customtabs.CustomTabsIntent;

import org.chromium.base.Log;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.cc.input.BrowserControlsState;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.browser_controls.BrowserControlsVisibilityManager;
import org.chromium.chrome.browser.browserservices.intents.BrowserServicesIntentDataProvider;
import org.chromium.chrome.browser.browserservices.intents.CustomButtonParams;
import org.chromium.chrome.browser.compositor.layouts.LayoutManagerImpl;
import org.chromium.chrome.browser.customtabs.CloseButtonVisibilityManager;
import org.chromium.chrome.browser.customtabs.CustomTabCompositorContentInitializer;
import org.chromium.chrome.browser.customtabs.CustomTabsConnection;
import org.chromium.chrome.browser.customtabs.content.CustomTabActivityNavigationController;
import org.chromium.chrome.browser.customtabs.content.CustomTabActivityTabController;
import org.chromium.chrome.browser.customtabs.content.CustomTabActivityTabProvider;
import org.chromium.chrome.browser.dependency_injection.ActivityScope;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.toolbar.ToolbarManager;
import org.chromium.components.browser_ui.share.ShareHelper;
import org.chromium.ui.util.TokenHolder;
import org.chromium.url.GURL;

import javax.inject.Inject;
import javax.inject.Named;

import dagger.Lazy;

/**
 * Works with the toolbar in a Custom Tab. Encapsulates interactions with Chrome's toolbar-related
 * classes such as {@link ToolbarManager} and {@link BrowserControlsVisibilityManager}.
 *
 * TODO(pshmakov):
 * 1. Reduce the coupling between Custom Tab toolbar and Chrome's common code. In particular,
 * ToolbarLayout has Custom Tab specific methods that throw unless we're in a Custom Tab - we need a
 * better design.
 * 2. Make toolbar lazy. E.g. in Trusted Web Activities we always start without toolbar - delay
 * executing any initialization code and creating {@link ToolbarManager} until the toolbar needs
 * to appear.
 * 3. Refactor to MVC.
 */
@ActivityScope
public class CustomTabToolbarCoordinator {
    private final BrowserServicesIntentDataProvider mIntentDataProvider;
    private final CustomTabActivityTabProvider mTabProvider;
    private final CustomTabsConnection mConnection;
    private final Activity mActivity;
    private final Context mAppContext;
    private final CustomTabActivityTabController mTabController;
    private final Lazy<BrowserControlsVisibilityManager> mBrowserControlsVisibilityManager;
    private final CustomTabActivityNavigationController mNavigationController;
    private final CloseButtonVisibilityManager mCloseButtonVisibilityManager;
    private final CustomTabBrowserControlsVisibilityDelegate mVisibilityDelegate;
    private final CustomTabToolbarColorController mToolbarColorController;

    @Nullable
    private ToolbarManager mToolbarManager;

    private int mControlsHidingToken = TokenHolder.INVALID_TOKEN;
    private boolean mInitializedToolbarWithNative;
    private PendingIntent.OnFinished mCustomButtonClickOnFinished;

    private static final String TAG = "CustomTabToolbarCoor";

    @Inject
    public CustomTabToolbarCoordinator(BrowserServicesIntentDataProvider intentDataProvider,
            CustomTabActivityTabProvider tabProvider, CustomTabsConnection connection,
            Activity activity, @Named(APP_CONTEXT) Context appContext,
            CustomTabActivityTabController tabController,
            Lazy<BrowserControlsVisibilityManager> controlsVisiblityManager,
            CustomTabActivityNavigationController navigationController,
            CloseButtonVisibilityManager closeButtonVisibilityManager,
            CustomTabBrowserControlsVisibilityDelegate visibilityDelegate,
            CustomTabCompositorContentInitializer compositorContentInitializer,
            CustomTabToolbarColorController toolbarColorController) {
        mIntentDataProvider = intentDataProvider;
        mTabProvider = tabProvider;
        mConnection = connection;
        mActivity = activity;
        mAppContext = appContext;
        mTabController = tabController;
        mBrowserControlsVisibilityManager = controlsVisiblityManager;
        mNavigationController = navigationController;
        mCloseButtonVisibilityManager = closeButtonVisibilityManager;
        mVisibilityDelegate = visibilityDelegate;
        mToolbarColorController = toolbarColorController;

        compositorContentInitializer.addCallback(this::onCompositorContentInitialized);
    }

    /**
     * Notifies the navigation controller that the ToolbarManager has been created and is ready for
     * use. ToolbarManager isn't passed directly to the constructor because it's not guaranteed to
     * be initialized yet.
     */
    public void onToolbarInitialized(ToolbarManager manager) {
        assert manager != null : "Toolbar manager not initialized";
        mToolbarManager = manager;
        mToolbarColorController.onToolbarInitialized(manager);
        mCloseButtonVisibilityManager.onToolbarInitialized(manager);

        manager.setShowTitle(
                mIntentDataProvider.getTitleVisibilityState() == CustomTabsIntent.SHOW_PAGE_TITLE);
        if (mConnection.shouldHideDomainForSession(mIntentDataProvider.getSession())) {
            manager.setUrlBarHidden(true);
        }
        if (mIntentDataProvider.isMediaViewer()) {
            manager.setToolbarShadowVisibility(View.GONE);
        }
        showCustomButtonsOnToolbar();
    }

    /**
     * Configures the custom button on toolbar. Does nothing if invalid data is provided by clients.
     */
    private void showCustomButtonsOnToolbar() {
        for (CustomButtonParams params : mIntentDataProvider.getCustomButtonsOnToolbar()) {
            View.OnClickListener onClickListener = v -> onCustomButtonClick(params);
            mToolbarManager.addCustomActionButton(
                    params.getIcon(mActivity), params.getDescription(), onClickListener);
        }
    }

    private void onCustomButtonClick(CustomButtonParams params) {
        Tab tab = mTabProvider.getTab();
        if (tab == null) return;

        sendButtonPendingIntentWithUrlAndTitle(params, tab.getOriginalUrl(), tab.getTitle());

        RecordUserAction.record("CustomTabsCustomActionButtonClick");
        Resources resources = mActivity.getResources();
        if (mIntentDataProvider.shouldEnableEmbeddedMediaExperience()
                && TextUtils.equals(params.getDescription(), resources.getString(R.string.share))) {
            ShareHelper.recordShareSource(ShareHelper.ShareSourceAndroid.ANDROID_SHARE_SHEET);
            RecordUserAction.record("CustomTabsCustomActionButtonClick.DownloadsUI.Share");
        }
    }

    /**
     * Sends the pending intent for the custom button on the toolbar with the given {@code params},
     *         with the given {@code url} as data.
     * @param params The parameters for the custom button.
     * @param url The URL to attach as additional data to the {@link PendingIntent}.
     * @param title The title to attach as additional data to the {@link PendingIntent}.
     */
    private void sendButtonPendingIntentWithUrlAndTitle(
            CustomButtonParams params, GURL url, String title) {
        Intent addedIntent = new Intent();
        addedIntent.setData(Uri.parse(url.getSpec()));
        addedIntent.putExtra(Intent.EXTRA_SUBJECT, title);
        try {
            params.getPendingIntent().send(
                    mAppContext, 0, addedIntent, mCustomButtonClickOnFinished, null);
        } catch (PendingIntent.CanceledException e) {
            Log.e(TAG, "CanceledException while sending pending intent in custom tab");
        }
    }

    private void onCompositorContentInitialized(LayoutManagerImpl layoutDriver) {
        mToolbarManager.initializeWithNative(
                layoutDriver, null, null, null, v -> onCloseButtonClick(), null);
        mInitializedToolbarWithNative = true;
    }

    private void onCloseButtonClick() {
        RecordUserAction.record("CustomTabs.CloseButtonClicked");
        if (mIntentDataProvider.shouldEnableEmbeddedMediaExperience()) {
            RecordUserAction.record("CustomTabs.CloseButtonClicked.DownloadsUI");
        }

        mNavigationController.navigateOnClose();
    }

    public void setBrowserControlsState(@BrowserControlsState int controlsState) {
        mVisibilityDelegate.setControlsState(controlsState);
        if (controlsState == BrowserControlsState.HIDDEN) {
            mControlsHidingToken =
                    mBrowserControlsVisibilityManager.get().hideAndroidControlsAndClearOldToken(
                            mControlsHidingToken);
        } else {
            mBrowserControlsVisibilityManager.get().releaseAndroidControlsHidingToken(
                    mControlsHidingToken);
        }
    }

    /**
     * Shows toolbar temporarily, for a few seconds.
     */
    public void showToolbarTemporarily() {
        mBrowserControlsVisibilityManager.get()
                .getBrowserVisibilityDelegate()
                .showControlsTransient();
    }

    /**
     * Updates a custom button with a new icon and description. Provided {@link CustomButtonParams}
     * must have the updated data.
     * Returns whether has succeeded.
     */
    public boolean updateCustomButton(CustomButtonParams params) {
        if (!params.doesIconFitToolbar(mActivity)) {
            return false;
        }
        int index = mIntentDataProvider.getCustomToolbarButtonIndexForId(params.getId());
        if (index == -1) {
            assert false;
            return false;
        }
        if (mToolbarManager == null) {
            return false;
        }

        mToolbarManager.updateCustomActionButton(
                index, params.getIcon(mActivity), params.getDescription());
        return true;
    }

    /**
     * Returns whether the toolbar has been fully initialized
     * ({@link ToolbarManager#initializeWithNative}).
     */
    public boolean toolbarIsInitialized() {
        return mInitializedToolbarWithNative;
    }

    /**
     * Set the callback object for the {@link PendingIntent} which is sent by the custom buttons.
     */
    @VisibleForTesting
    public void setCustomButtonPendingIntentOnFinishedForTesting(
            PendingIntent.OnFinished onFinished) {
        mCustomButtonClickOnFinished = onFinished;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { Button, Classes, Dialog, Icon, IconName, IDialogProps, Intent } from '@blueprintjs/core';
import * as React from 'react';

import './table-action-dialog.scss';

export interface SideButtonMetaData {
  icon: IconName;
  text: string;
  active?: boolean;
  onClick?: () => void;
}

interface TableActionDialogProps extends IDialogProps {
  sideButtonMetadata: SideButtonMetaData[];
  onClose: () => void;
  bottomButtons?: React.ReactNode;
}

export class TableActionDialog extends React.Component<TableActionDialogProps, {}> {
  constructor(props: TableActionDialogProps) {
    super(props);
    this.state = {};
  }

  render() {
    const { sideButtonMetadata, isOpen, onClose, title, bottomButtons } = this.props;

    return <Dialog
      className="table-action-dialog"
      isOpen={isOpen}
      onClose={onClose}
      title={title}
    >

          {
            sideButtonMetadata.map((d: SideButtonMetaData) => (
              <Button
                className="tab-button"
                icon={<Icon icon={d.icon} iconSize={20}/>}
                key={d.text}
                text={d.text}
                intent={d.active ? Intent.PRIMARY : Intent.NONE}
                minimal={!d.active}
                onClick={d.onClick}
              />
            ))
          }

          {this.props.children}

          {bottomButtons}

          <Button
            text="Close"
            intent={Intent.PRIMARY}
            onClick={onClose}
          />

    </Dialog>;
  }
}


text:
import { Foundation } from './foundation.core';

import { Nest } from '../../foundation.util.nest';

Foundation.Nest = Nest;

export { Foundation, Nest };


text:
class Player:
    """
    An object representation of a CTF player.
    """

    def __init__(self, user_id):
        """
        user_id : The slack ID of a user
        """
        self.user_id = user_id


text:
layout: project
title: "Istanbul Documentation Project"
description: The IDP aims to create a digital platform for the virtual presentation of Istanbul's Roman, Byzantine, Ottoman and early Republican sites and monuments.
link: "http://www.learn.columbia.edu/istanbul/"
img: istanbul.png
author: Alex Gil
people:
- Holger Klein
teams:
- Media Center for Art History
---

Istanbul is a city with a fascinating history that stretches over three millennia. Having served as the capital of two successive empires, namely the Late Roman or Byzantine Empire (330–1453) and the Ottoman Empire (1453–1922), it is today a rich palimpsest of cultures and artistic traditions, in which architectural monuments of its Roman, Byzantine, and Ottoman past serve as sites of historical and cultural memory woven into the ever-changing fabric of a 21st-century metropolis.

The Istanbul Documentation Project, developed by Professor Holger A. Klein of Columbia University's Department of Art History and Archaeology in collaboration with the Media Center for Art History, aims to create a digital platform for the virtual presentation of Istanbul's Roman, Byzantine, Ottoman and early Republican sites and monuments and thus provides a rich resource for scholars, students, and the general public to study the deep history of the city in preparation for site visits and as a tool for individual study, research, and teaching in the classroom.

Columbia University is inviting proposals from institutions and individual scholars, who are interested to participate in joining us in our venture. For further information, contact Professor Holger A. Klein at hak56@columbia.edu.


text:
<?php

namespace Drupal\Tests\block\Unit\Plugin\migrate\process;

use Drupal\block\Plugin\migrate\process\BlockVisibility;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\migrate\Plugin\MigrateProcessInterface;
use Drupal\Tests\migrate\Unit\process\MigrateProcessTestCase;

/**
 * Tests the block_visibility process plugin.
 *
 * @coversDefaultClass \Drupal\block\Plugin\migrate\process\BlockVisibility
 * @group block
 */
class BlockVisibilityTest extends MigrateProcessTestCase {

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->moduleHandler = $this->prophesize(ModuleHandlerInterface::class);
    $migration_plugin = $this->prophesize(MigrateProcessInterface::class);
    $this->plugin = new BlockVisibility([], 'block_visibility_pages', [], $this->moduleHandler->reveal(), $migration_plugin->reveal());
  }

  /**
   * @covers ::transform
   */
  public function testTransformNoData() {
    $transformed_value = $this->plugin->transform([0, '', []], $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertEmpty($transformed_value);
  }

  /**
   * @covers ::transform
   */
  public function testTransformSinglePageWithFront() {
    $visibility = $this->plugin->transform([0, '<front>', []], $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame('request_path', $visibility['request_path']['id']);
    $this->assertTrue($visibility['request_path']['negate']);
    $this->assertSame('<front>', $visibility['request_path']['pages']);
  }

  /**
   * @covers ::transform
   */
  public function testTransformMultiplePagesWithFront() {
    $visibility = $this->plugin->transform([1, "foo\n/bar\rbaz\r\n<front>", []], $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame('request_path', $visibility['request_path']['id']);
    $this->assertFalse($visibility['request_path']['negate']);
    $this->assertSame("/foo\n/bar\n/baz\n<front>", $visibility['request_path']['pages']);
  }

  /**
   * @covers ::transform
   */
  public function testTransformPhpEnabled() {
    $this->moduleHandler->moduleExists('php')->willReturn(TRUE);
    $visibility = $this->plugin->transform([2, '<?php', []], $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertSame('php', $visibility['php']['id']);
    $this->assertFalse($visibility['php']['negate']);
    $this->assertSame('<?php', $visibility['php']['php']);
  }

  /**
   * @covers ::transform
   */
  public function testTransformPhpDisabled() {
    $this->moduleHandler->moduleExists('php')->willReturn(FALSE);
    $transformed_value = $this->plugin->transform([2, '<?php', []], $this->migrateExecutable, $this->row, 'destinationproperty');
    $this->assertEmpty($transformed_value);
  }

}


text:
@implementation DevNewsLoader

+ (void)load
{
#if TARGET_OS_IPHONE
    [[NSNotificationCenter defaultCenter] addObserver:[self class] selector:@selector(applicationDidBecomeActive:) name:@"UIApplicationDidFinishLaunchingNotification" object:nil];
#elif !TARGET_OS_IPHONE
    [[NSNotificationCenter defaultCenter] addObserver:[self class] selector:@selector(applicationDidBecomeActive:) name:@"NSApplicationDidFinishLaunchingNotification" object:nil];
#endif
}

+ (void)applicationDidBecomeActive:(NSNotification *)notification
{
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *path = [bundle pathForResource:@"DevNews" ofType:@"plist"];
    NSDictionary *configs = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *apiKey;
    NSString *listID;

#if TARGET_OS_IPHONE
#if TARGET_IPHONE_SIMULATOR
    NSDictionary *configurations = [configs valueForKey:@"Simulator"];

    // API Key
    if ([configurations objectForKey:@"API Key"]) {
        apiKey = [configurations valueForKey:@"API Key"];
    }

    // List ID
    if ([configurations objectForKey:@"List ID"]) {
        listID = [configurations valueForKey:@"List ID"];
    }
#else
    NSDictionary *configurations = [configs valueForKey:@"Device"];

    // API Key
    if ([configurations objectForKey:@"API Key"]) {
        apiKey = [configurations valueForKey:@"API Key"];
    }

    // List ID
    if ([configurations objectForKey:@"List ID"]) {
        listID = [configurations valueForKey:@"List ID"];
    }
#endif
#elif !TARGET_OS_IPHONE
    NSDictionary *configurations = [configs valueForKey:@"Mac"];

    // API Key
    if ([configurations objectForKey:@"API Key"]) {
        apiKey = [configurations valueForKey:@"API Key"];
    }

    // List ID
    if ([configurations objectForKey:@"List ID"]) {
        listID = [configurations valueForKey:@"List ID"];
    }
#endif

    if (apiKey) {
        [DevNews devNewsWithAPIKey:apiKey listID:listID];
        NSLog(@"DevNews is configured with the MailChimp API key %@ and list ID %@", apiKey, listID);
    } else {
        NSLog(@"Please specify the MailChimp API key in DevNews.plist first");
    }
}

@end


text:
package top.cardone.usercenter.service.impl;

import org.springframework.transaction.annotation.Transactional;
import top.cardone.data.service.impl.PageServiceImpl;
import top.cardone.usercenter.dao.UserAddressDao;

import java.util.Map;

/**
 * 用户与地址服务
 *
 * @author yao hai tao
 */
@Transactional(readOnly = true)
public class UserAddressServiceImpl extends PageServiceImpl<UserAddressDao> implements top.cardone.usercenter.service.UserAddressService {
    @Override
    public Map<String, Object> findOneByUserAddressId(Map<String, Object> findOne) {
        return this.dao.findOneBySqlFileName("page.find", findOne);
    }
}


text:
'use strict';

/**
 * Module dependencies
 */
 var acl = require('acl');

// Using the memory backend
acl = new acl(new acl.memoryBackend());

/**
 * Invoke Tickets Permissions
 */
 exports.invokeRolesPolicies = function() {
 	acl.allow([{
 		roles: ['admin', 'user'],
 		allows: [{
 			resources: '/api/support/tickets',
 			permissions: '*'
 		}, {
 			resources: '/api/support/tickets/create',
 			permission: '*'
 		}, {
 			resources: '/api/support/tickets/:ticketId',
 			permissions: '*'
 		}]
 	}]);
 };

 /**
  * Check if Tickets Policy Allows
  */
exports.isAllowed = function (req, res, next) {
	var roles = (req.user) ? req.user.roles : ['guest'];

	// Check for user roles
	acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
		if (err) {
			// An authorization error occurred.
			return res.status(500).send('Unexpected authorization error');
		} else {
			if (isAllowed) {
				// Access allowed. Invoke middleware
				return next();
			} else {
				return res.status(403).json({
					message: 'User is not authorized'
				});
			}
		}
	});
};


text:
#ifndef ALIVZERORAWSTREAM_H
#define ALIVZERORAWSTREAM_H

///////////////////////////////////////////////////////////////////////////////
///
/// This is a class for reading the VZERO DDL raw data
/// The format of the raw data corresponds to the one
/// implemented in AliVZEROBuffer class.
///
/// PLEASE NOTE that Int_t channel is here the FEE channel from 0 to 63 in the
/// order defined by Yannick Zoccarato which is not the same order as the order
/// defined in aliroot by the naming and numbering conventions.
/// Therefore one has to go from FEE_Channel to AliRoot_Channel using
/// GetOfflineChannel(Int_t channel)  when going from Online to Offline !!!
///
///////////////////////////////////////////////////////////////////////////////

#include <TObject.h>
#include <TMath.h>

class AliRawReader;
class AliVZEROTriggerData;

class AliVZERORawStream: public TObject {
  public :
    AliVZERORawStream(AliRawReader* rawReader);
    virtual ~AliVZERORawStream();

    virtual void      Reset();
    virtual Bool_t    Next();

// Getters of various scalers and Minimum Bias flags :

   ULong64_t          GetBBScalers(Int_t channel) const
      { return        fBBScalers[channel]; }
   ULong64_t          GetBGScalers(Int_t channel) const
      { return        fBGScalers[channel]; }
   UInt_t             GetTriggerScalers(Int_t num_scaler) const
      { return        fScalers[num_scaler]; }
   UInt_t             GetBunchNumbersMB(Int_t num_bunch) const
      { return        fBunchNumbers[num_bunch]; }
   UShort_t           GetChargeMB(Int_t channel, Int_t num_bunch) const
      { return        fChargeMB[channel][num_bunch]; }
   Bool_t             GetIntMBFlag(Int_t channel, Int_t num_bunch) const
      { return        fIsIntMB[channel][num_bunch]; }
   Bool_t             GetBBMBFlag(Int_t channel, Int_t num_bunch) const
      { return        fIsBBMB[channel][num_bunch]; }
   Bool_t             GetBGMBFlag(Int_t channel, Int_t num_bunch) const
      { return        fIsBGMB[channel][num_bunch]; }

// Getters of ADC signals, ADC pedestals, time information and corresponding flags :

    Short_t           GetADC(Int_t channel) const
      { return TMath::MaxElement(kNEvOfInt, fADC[channel]); }    // maximum value instead of central clock
//    { return fADC[channel][kNEvOfInt/2]; }

    Short_t           GetPedestal(Int_t channel, Int_t event) const
      { return fADC[channel][event]; }
    Bool_t            GetIntegratorFlag(Int_t channel, Int_t event) const
      { return fIsInt[channel][event]; }
    Bool_t            GetBBFlag(Int_t channel, Int_t event) const
      { return fIsBB[channel][event]; }
    Bool_t            GetBGFlag(Int_t channel, Int_t event) const
      { return fIsBG[channel][event]; }
    Short_t           GetTime(Int_t channel) const
      { return fTime[channel]; }
    Short_t           GetWidth(Int_t channel) const
      { return fWidth[channel]; }

    UShort_t          GetTriggerInputs() const
      { return fTrigger; }
    UShort_t          GetTriggerInputsMask() const
      { return fTriggerMask; }

    void              CalculateChargeForCentrTriggers(AliVZEROTriggerData *triggerData,
						      UShort_t &chargeA, UShort_t &chargeC) const;
    void              CalculateBBandBGFlags(AliVZEROTriggerData *triggerData,
					    UChar_t &nBBA, UChar_t &nBBC,
					    UChar_t &nBGA, UChar_t &nBGC) const;
    void              FillTriggerBits(AliVZEROTriggerData *triggerData);

// Getter of Offline Channel number as used in aliroot (defined by aliroot
// numbering convention) from FEE channel (electronic channel number given
// by the V0 electronics readout) - See comment above -

    Int_t              GetOfflineChannel(Int_t channel)  const
      { Int_t  fOfflineChannel[64] = {39, 38, 37, 36, 35, 34, 33, 32,
                                      47, 46, 45, 44, 43, 42, 41, 40,
			              55, 54, 53, 52, 51, 50, 49, 48,
			              63, 62, 61, 60, 59, 58, 57, 56,
			               7,  6,  5,  4,  3,  2,  1,  0,
			              15, 14, 13, 12, 11, 10,  9,  8,
			              23, 22, 21, 20, 19, 18, 17, 16,
			              31, 30, 29, 28, 27, 26, 25, 24};
               return fOfflineChannel[channel]; }

    enum EVZERORawDataParams {
      kNChannels = 64, // number of electronic channels in V0 (FEE numbering)
      kNEvOfInt  = 21, // number of events of interest
      kNScalers  = 16, // number of scalers
      kNBunches  = 10  // number of bunches used in Minimum Bias information
    };

    enum EVZERORawStreamError {
      kRawDataSizeErr = 1
    };

  private:

    AliVZERORawStream(const AliVZERORawStream& stream);
    AliVZERORawStream& operator = (const AliVZERORawStream& stream);

    UInt_t GetNextWord();
    UShort_t GetNextShort();

    ULong64_t     fBBScalers[kNChannels];        // 'Beam-Beam' scalers for all channels
    ULong64_t     fBGScalers[kNChannels];        // 'Beam-Gas' scalers for all channels
    UInt_t        fScalers[kNScalers];           // Trigger scalers
    UInt_t        fBunchNumbers[kNBunches];      // Bunch numbers for the previous 10 MB events
    UShort_t      fChargeMB[kNChannels][kNBunches]; // ADC counts for all channels for the previous 10 MB events
    Bool_t        fIsIntMB[kNChannels][kNBunches];  // 'Integrator' flag for all channels for the previous 10 MB events
    Bool_t        fIsBBMB[kNChannels][kNBunches];   // 'Beam-Beam' flag for all channels for the previous 10 MB events
    Bool_t        fIsBGMB[kNChannels][kNBunches];   // 'Beam-Gas' for all channels for the previous 10 MB events

    Short_t       fADC[kNChannels][kNEvOfInt];   // ADC counts for all channels and all events of interest
    Bool_t        fIsInt[kNChannels][kNEvOfInt]; // 'Integrator' flag for all channels
    Bool_t        fIsBB[kNChannels][kNEvOfInt];  // 'Beam-Beam' flag for all channels
    Bool_t        fIsBG[kNChannels][kNEvOfInt];  // 'Beam-Gas' flag for all channels
    Short_t       fTime[kNChannels];             // leading time for all channels - from HPTDC - in HPTDC units
    Short_t       fWidth[kNChannels];            // pulse width for all channels - from HPTDC - in HPTDC units

    UShort_t      fTrigger;        // VZERO trigger inputs
    UShort_t      fTriggerMask;    // VZERO trigger inputs mask

    Int_t         fPosition;       // current position in the raw-data payload

    AliRawReader* fRawReader;      // object for reading the raw data

    UChar_t*      fData;           // pointer to raw data payload

    ClassDef(AliVZERORawStream, 0) // class for reading VZERO DDL raw data
};

#endif


text:
package org.opensingular.form.wicket.component;

import net.vidageek.mirror.dsl.Mirror;
import org.apache.wicket.Page;
import org.apache.wicket.ThreadContext;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IFormSubmitter;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.protocol.http.WicketFilter;
import org.apache.wicket.protocol.http.mock.MockServletContext;
import org.apache.wicket.request.IExceptionMapper;
import org.apache.wicket.request.IRequestMapper;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.cycle.RequestCycleContext;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.mock.web.MockFilterConfig;

import javax.servlet.ServletException;
import java.util.Locale;

public class SingularFormWicketTest {

    @Before
    public void mockWicketContext() throws ServletException {
        ThreadContext t = ThreadContext.get(true);

        WebApplication webApplication = new WebApplication() {
            @Override
            public Class<? extends Page> getHomePage() {
                return Page.class;
            }

        };

        MockFilterConfig filterConfig = new MockFilterConfig(new MockServletContext(webApplication, null), "nada");
        WicketFilter filter = new WicketFilter(webApplication);
        filter.init(filterConfig);

        webApplication.setWicketFilter(filter);

        Request request = Mockito.mock(Request.class);
        Mockito.when(request.getLocale()).thenReturn(Locale.ENGLISH);

        t.setSession(new WebSession(request));
        t.setRequestCycle(new RequestCycle(new RequestCycleContext(request, Mockito.mock(Response.class), Mockito.mock(IRequestMapper.class), Mockito.mock(IExceptionMapper.class))));
        t.setApplication(webApplication);

        webApplication.initApplication();
    }

    @Test
    public void invokePrivateMethodTest() throws Exception {
        SingularFormWicket f1 = Mockito.spy(new SingularFormWicket("1"){});

        Form f2 = new Form<>("12");
        f1.add(f2);

        IFormSubmitter formSubmitter = Mockito.mock(AjaxFormSubmitBehavior.AjaxFormSubmitter.class);
        Mockito.when(formSubmitter.getForm()).thenReturn(f2);

        new Mirror().on(f1).invoke().method("markFormsSubmitted").withArgs(formSubmitter);
        new Mirror().on(f2).invoke().method("markFormsSubmitted").withArgs(formSubmitter);

        f1.process(formSubmitter);
    }
}


text:
r"""Code to extract a tensorflow checkpoint from a bundle file.

To run this code on your local machine:
$ python magenta/scripts/unpack_bundle.py \
--bundle_path 'path' --checkpoint_path 'path'
"""

from magenta.models.shared import sequence_generator_bundle
import tensorflow.compat.v1 as tf

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('bundle_path', '',
                           'Path to .mag file containing the bundle')
tf.app.flags.DEFINE_string('checkpoint_path', '/tmp/model.ckpt',
                           'Path where the extracted checkpoint should'
                           'be saved')

def main(_):
  bundle_file = FLAGS.bundle_path
  checkpoint_file = FLAGS.checkpoint_path
  metagraph_filename = checkpoint_file + '.meta'

  bundle = sequence_generator_bundle.read_bundle_file(bundle_file)

  with tf.gfile.Open(checkpoint_file, 'wb') as f:
    f.write(bundle.checkpoint_file[0])

  with tf.gfile.Open(metagraph_filename, 'wb') as f:
    f.write(bundle.metagraph_file)

if __name__ == '__main__':
  tf.disable_v2_behavior()
  tf.app.run()


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

#include "ash/capture_mode/capture_mode_camera_preview_view.h"

#include "ash/accessibility/scoped_a11y_override_window_setter.h"
#include "ash/capture_mode/capture_mode_constants.h"
#include "ash/capture_mode/capture_mode_controller.h"
#include "ash/capture_mode/capture_mode_session.h"
#include "ash/capture_mode/capture_mode_util.h"
#include "ash/resources/vector_icons/vector_icons.h"
#include "ash/shell.h"
#include "ash/strings/grit/ash_strings.h"
#include "ash/style/ash_color_provider.h"
#include "base/bind.h"
#include "base/check.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/compositor/layer.h"
#include "ui/events/event.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/paint_vector_icon.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/animation/animation_builder.h"
#include "ui/views/background.h"
#include "ui/views/controls/highlight_path_generator.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/widget/widget.h"

namespace ash {

namespace {

// The duration for the resize button fading in process.
constexpr base::TimeDelta kResizeButtonFadeInDuration = base::Milliseconds(150);

// The duration for the reize button fading out process.
constexpr base::TimeDelta kResizeButtonFadeOutDuration = base::Milliseconds(50);

gfx::PointF GetEventScreenLocation(const ui::LocatedEvent& event) {
  return event.target()->GetScreenLocationF(event);
}

const gfx::VectorIcon& GetIconOfResizeButton(
    const bool is_camera_preview_collapsed) {
  return is_camera_preview_collapsed ? kCaptureModeCameraPreviewExpandIcon
                                     : kCaptureModeCameraPreviewCollapseIcon;
}

bool IsArrowKeyEvent(const ui::KeyEvent* event) {
  const ui::KeyboardCode key_code = event->key_code();
  return key_code == ui::VKEY_DOWN || key_code == ui::VKEY_RIGHT ||
         key_code == ui::VKEY_LEFT || key_code == ui::VKEY_UP;
}

}  // namespace

// -----------------------------------------------------------------------------
// CameraPreviewResizeButton:

CameraPreviewResizeButton::CameraPreviewResizeButton(
    CameraPreviewView* camera_preview_view,
    views::Button::PressedCallback callback,
    const gfx::VectorIcon& icon)
    : CaptureModeButton(std::move(callback), icon),
      camera_preview_view_(camera_preview_view) {}

CameraPreviewResizeButton::~CameraPreviewResizeButton() = default;

void CameraPreviewResizeButton::PseudoFocus() {
  DCHECK(camera_preview_view_->is_collapsible());

  CaptureModeSessionFocusCycler::HighlightableView::PseudoFocus();
  camera_preview_view_->RefreshResizeButtonVisibility();
}

void CameraPreviewResizeButton::PseudoBlur() {
  CaptureModeSessionFocusCycler::HighlightableView::PseudoBlur();
  camera_preview_view_->ScheduleRefreshResizeButtonVisibility();
}

BEGIN_METADATA(CameraPreviewResizeButton, CaptureModeButton)
END_METADATA

// -----------------------------------------------------------------------------
// CameraPreviewView:

CameraPreviewView::CameraPreviewView(
    CaptureModeCameraController* camera_controller,
    const CameraId& camera_id,
    mojo::Remote<video_capture::mojom::VideoSource> camera_video_source,
    const media::VideoCaptureFormat& capture_format,
    bool should_flip_frames_horizontally)
    : camera_controller_(camera_controller),
      camera_id_(camera_id),
      camera_video_renderer_(std::move(camera_video_source),
                             capture_format,
                             should_flip_frames_horizontally),
      camera_video_host_view_(
          AddChildView(std::make_unique<views::NativeViewHost>())),
      resize_button_(AddChildView(std::make_unique<CameraPreviewResizeButton>(
          this,
          base::BindRepeating(&CameraPreviewView::OnResizeButtonPressed,
                              base::Unretained(this)),
          GetIconOfResizeButton(
              camera_controller_->is_camera_preview_collapsed())))),
      scoped_a11y_overrider_(
          std::make_unique<ScopedA11yOverrideWindowSetter>()) {
  // Add an empty border to the camera preview. This is done to keep some gap
  // between the focus ring and the contents of the camera preview, as focus
  // ring will extend a little beyond the border.
  SetBorder(views::CreateEmptyBorder(capture_mode::kCameraPreviewBorderSize));

  resize_button_->SetPaintToLayer();
  resize_button_->layer()->SetFillsBoundsOpaquely(false);
  resize_button_->SetBackground(views::CreateRoundedRectBackground(
      AshColorProvider::Get()->GetBaseLayerColor(
          AshColorProvider::BaseLayerType::kTransparent80),
      resize_button_->GetPreferredSize().height() / 2.f));

  accessibility_observation_.Observe(Shell::Get()->accessibility_controller());
  RefreshResizeButtonVisibility();
  UpdateResizeButtonTooltip();
}

CameraPreviewView::~CameraPreviewView() {
  auto* controller = CaptureModeController::Get();
  if (controller->IsActive() && !controller->is_recording_in_progress())
    controller->capture_mode_session()->OnCameraPreviewDestroyed();
}

void CameraPreviewView::SetIsCollapsible(bool value) {
  if (value != is_collapsible_) {
    is_collapsible_ = value;
    RefreshResizeButtonVisibility();
  }
}

bool CameraPreviewView::MaybeHandleKeyEvent(const ui::KeyEvent* event) {
  // Handle control+arrow keys to snap the camera preview to different corners
  // when it has focus.
  if (has_focus() && event->IsControlDown() && IsArrowKeyEvent(event)) {
    const CameraPreviewSnapPosition current_snap_position =
        camera_controller_->camera_preview_snap_position();
    CameraPreviewSnapPosition new_snap_position = current_snap_position;
    const ui::KeyboardCode key_code = event->key_code();
    if (key_code == ui::VKEY_LEFT || key_code == ui::VKEY_RIGHT) {
      new_snap_position =
          capture_mode_util::GetCameraNextHorizontalSnapPosition(
              current_snap_position, /*going_left=*/key_code == ui::VKEY_LEFT);
    } else {
      DCHECK(key_code == ui::VKEY_UP || key_code == ui::VKEY_DOWN);
      new_snap_position = capture_mode_util::GetCameraNextVerticalSnapPosition(
          current_snap_position, /*going_up=*/key_code == ui::VKEY_UP);
    }

    // Still call `SetCameraPreviewSnapPosition` even if the snap position does
    // not change. As we still want to trigger a11y alert in this case.
    camera_controller_->SetCameraPreviewSnapPosition(new_snap_position,
                                                     /*animate=*/true);
    return new_snap_position != current_snap_position;
  }

  auto* controller = CaptureModeController::Get();
  if (controller->IsActive() || !controller->is_recording_in_progress())
    return false;

  // Handle the key events on camera preview when it has focus (either the
  // preview view or the resize button) in video recording.
  const bool camera_preview_has_focus =
      has_focus() || resize_button_->has_focus();
  bool should_handle_event = false;
  switch (event->key_code()) {
    case ui::VKEY_TAB:
      if (camera_preview_has_focus) {
        if (resize_button_->has_focus()) {
          DCHECK(is_collapsible_);
          resize_button_->PseudoBlur();
          PseudoFocus();
        } else if (is_collapsible_) {
          PseudoBlur();
          resize_button_->PseudoFocus();
        }
        should_handle_event = true;
      }
      break;
    case ui::VKEY_SPACE:
      if (resize_button_->has_focus()) {
        resize_button_->ClickView();
        should_handle_event = true;
      }
      break;
    case ui::VKEY_ESCAPE:
      if (camera_preview_has_focus) {
        BlurA11yFocus();
        should_handle_event = true;
      }
      break;
    default:
      break;
  }
  return should_handle_event;
}

void CameraPreviewView::RefreshResizeButtonVisibility() {
  const float target_opacity = CalculateResizeButtonTargetOpacity();
  if (target_opacity == resize_button_->layer()->GetTargetOpacity())
    return;

  resize_button_hide_timer_.Stop();
  if (target_opacity == 1.f) {
    FadeInResizeButton();
    ScheduleRefreshResizeButtonVisibility();
  } else {
    FadeOutResizeButton();
  }
}

void CameraPreviewView::UpdateA11yOverrideWindow() {
  if (has_focus() || resize_button_->has_focus()) {
    scoped_a11y_overrider_->MaybeUpdateA11yOverrideWindow(
        GetWidget()->GetNativeWindow());
  } else {
    scoped_a11y_overrider_->MaybeUpdateA11yOverrideWindow(nullptr);
  }
}

void CameraPreviewView::MaybeBlurFocus(const ui::MouseEvent& event) {
  auto* target = static_cast<aura::Window*>(event.target());
  if (!GetWidget()->GetNativeWindow()->Contains(target))
    BlurA11yFocus();
}

void CameraPreviewView::AddedToWidget() {
  camera_video_host_view_->Attach(camera_video_renderer_.host_window());
  // This must be called after the renderer's `host_window()` has been attached
  // to the `NativeViewHost`, and before we call `Initialize()`, since
  // `Initialize()` will create a layer tree frame sink for the `host_window()`
  // and we're not allowed to change the event targeting policy after that.
  DisableEventHandlingInCameraVideoHostHierarchy();

  camera_video_renderer_.Initialize();
}

bool CameraPreviewView::OnMousePressed(const ui::MouseEvent& event) {
  camera_controller_->StartDraggingPreview(GetEventScreenLocation(event));
  return true;
}

bool CameraPreviewView::OnMouseDragged(const ui::MouseEvent& event) {
  camera_controller_->ContinueDraggingPreview(GetEventScreenLocation(event));
  return true;
}

void CameraPreviewView::OnMouseReleased(const ui::MouseEvent& event) {
  camera_controller_->EndDraggingPreview(GetEventScreenLocation(event),
                                         /*is_touch=*/false);
}

void CameraPreviewView::OnGestureEvent(ui::GestureEvent* event) {
  const gfx::PointF screen_location = GetEventScreenLocation(*event);

  switch (event->type()) {
    case ui::ET_GESTURE_SCROLL_BEGIN:
      camera_controller_->StartDraggingPreview(screen_location);
      break;
    case ui::ET_GESTURE_SCROLL_UPDATE:
      DCHECK(camera_controller_->is_drag_in_progress());
      camera_controller_->ContinueDraggingPreview(screen_location);
      break;
    case ui::ET_SCROLL_FLING_START:
      // TODO(conniekxu): Handle fling event.
      break;
    case ui::ET_GESTURE_SCROLL_END:
      DCHECK(camera_controller_->is_drag_in_progress());
      camera_controller_->EndDraggingPreview(screen_location,
                                             /*is_touch=*/true);
      break;
    case ui::ET_GESTURE_END:
      if (camera_controller_->is_drag_in_progress()) {
        camera_controller_->EndDraggingPreview(screen_location,
                                               /*is_touch=*/true);
      }
      break;
    case ui::ET_GESTURE_TAP:
      has_been_tapped_ = true;
      RefreshResizeButtonVisibility();
      has_been_tapped_ = false;
      break;
    default:
      break;
  }

  event->StopPropagation();
  event->SetHandled();
}

void CameraPreviewView::OnMouseEntered(const ui::MouseEvent& event) {
  RefreshResizeButtonVisibility();
}

void CameraPreviewView::OnMouseExited(const ui::MouseEvent& event) {
  ScheduleRefreshResizeButtonVisibility();
}

void CameraPreviewView::Layout() {
  const gfx::Size resize_button_size = resize_button_->GetPreferredSize();
  const gfx::Rect bounds(
      (width() - resize_button_size.width()) / 2.f,
      height() - resize_button_size.height() -
          capture_mode::kSpaceBetweenResizeButtonAndCameraPreview -
          capture_mode::kCameraPreviewBorderSize,
      resize_button_size.width(), resize_button_size.height());
  resize_button_->SetBoundsRect(bounds);

  camera_video_host_view_->SetBoundsRect(GetContentsBounds());

  // The size must have changed, and we need to update the rounded corners. Note
  // that the assumption is that this view must have a square size, so when
  // rounded corners are applied, it looks like a perfect circle.
  // The rounded corners is applied on the window hosting the camera frames.
  // That window's layer is a solid-color layer, so applying rounded corners on
  // it won't make it produce a render surface. This is better than applying it
  // on the preview widget's layer (which is a texture layer) and would cause a
  // a render surface. This also avoids the rendering artifacts seen in
  // https://crbug.com/1312059.
  DCHECK_EQ(width(), height());
  auto* layer = camera_video_renderer_.host_window()->layer();
  layer->SetRoundedCornerRadius(gfx::RoundedCornersF(height() / 2.f));
  layer->SetIsFastRoundedCorner(true);

  // Refocus the camera preview to relayout the focus ring on it.
  if (has_focus())
    PseudoFocus();
}

void CameraPreviewView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
  views::View::GetAccessibleNodeData(node_data);
  node_data->role = ax::mojom::Role::kVideo;
  node_data->SetName(
      l10n_util::GetStringUTF16(IDS_ASH_SCREEN_CAPTURE_CAMERA_PREVIEW_FOCUSED));
}

views::View* CameraPreviewView::GetView() {
  return this;
}

std::unique_ptr<views::HighlightPathGenerator>
CameraPreviewView::CreatePathGenerator() {
  return std::make_unique<views::CircleHighlightPathGenerator>(
      gfx::Insets(views::FocusRing::kDefaultHaloThickness / 2));
}

void CameraPreviewView::OnAccessibilityStatusChanged() {
  RefreshResizeButtonVisibility();
}

void CameraPreviewView::OnAccessibilityControllerShutdown() {
  accessibility_observation_.Reset();
}

void CameraPreviewView::OnResizeButtonPressed() {
  camera_controller_->ToggleCameraPreviewSize();
  UpdateResizeButton();
}

void CameraPreviewView::UpdateResizeButton() {
  resize_button_->SetImage(
      views::Button::STATE_NORMAL,
      gfx::CreateVectorIcon(
          GetIconOfResizeButton(
              camera_controller_->is_camera_preview_collapsed()),
          AshColorProvider::Get()->GetContentLayerColor(
              AshColorProvider::ContentLayerType::kIconColorPrimary)));
  UpdateResizeButtonTooltip();
}

void CameraPreviewView::UpdateResizeButtonTooltip() {
  resize_button_->SetTooltipText(l10n_util::GetStringUTF16(
      camera_controller_->is_camera_preview_collapsed()
          ? IDS_ASH_SCREEN_CAPTURE_TOOLTIP_EXPAND_SELFIE_CAMERA
          : IDS_ASH_SCREEN_CAPTURE_TOOLTIP_COLLAPSE_SELFIE_CAMERA));
}

void CameraPreviewView::DisableEventHandlingInCameraVideoHostHierarchy() {
  camera_video_host_view_->SetCanProcessEventsWithinSubtree(false);
  camera_video_host_view_->SetFocusBehavior(FocusBehavior::NEVER);
  auto* const host_window = camera_video_renderer_.host_window();
  auto* const widget_window = GetWidget()->GetNativeWindow();
  DCHECK(host_window);
  DCHECK(host_window->parent());
  DCHECK(widget_window);

  for (auto* window = host_window; window && window != widget_window;
       window = window->parent()) {
    window->SetEventTargetingPolicy(aura::EventTargetingPolicy::kNone);
  }
}

void CameraPreviewView::FadeInResizeButton() {
  resize_button_->SetVisible(true);

  views::AnimationBuilder()
      .SetPreemptionStrategy(
          ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
      .Once()
      .SetDuration(kResizeButtonFadeInDuration)
      .SetOpacity(resize_button_->layer(), 1.0f);
}

void CameraPreviewView::FadeOutResizeButton() {
  views::AnimationBuilder()
      .OnEnded(base::BindOnce(
          [](base::WeakPtr<CameraPreviewView> camera_preview_view) {
            if (camera_preview_view)
              camera_preview_view->resize_button()->SetVisible(false);
          },
          weak_ptr_factory_.GetWeakPtr()))
      .SetPreemptionStrategy(
          ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET)
      .Once()
      .SetDuration(kResizeButtonFadeOutDuration)
      .SetOpacity(resize_button_->layer(), 0.0f);
}

void CameraPreviewView::ScheduleRefreshResizeButtonVisibility() {
  resize_button_hide_timer_.Start(
      FROM_HERE, capture_mode::kResizeButtonShowDuration, this,
      &CameraPreviewView::RefreshResizeButtonVisibility);
}

float CameraPreviewView::CalculateResizeButtonTargetOpacity() {
  if (!is_collapsible_ || camera_controller_->is_drag_in_progress())
    return 0.f;

  if (Shell::Get()->accessibility_controller()->IsSwitchAccessRunning() ||
      IsMouseHovered() || resize_button_->IsMouseHovered() ||
      resize_button_->has_focus() || has_been_tapped_) {
    return 1.f;
  }

  return 0.f;
}

void CameraPreviewView::BlurA11yFocus() {
  PseudoBlur();
  resize_button_->PseudoBlur();
  UpdateA11yOverrideWindow();
}

BEGIN_METADATA(CameraPreviewView, views::View)
END_METADATA

}  // namespace ash


text:
package ru.stqa.pft.addressbook.tests;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import java.util.stream.Collectors;

import static java.lang.System.getProperty;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Created by Sergei on 06.05.2016.
 */
public class ContactPhoneTests extends TestBase {
    private final Properties properties;

    public ContactPhoneTests() {
        properties = new Properties();
    }

    @BeforeMethod
    public void areThereClients() throws IOException {
        String target = getProperty("target", "local");
        properties.load(new FileReader(new File(String.format("src/test/resources/%s.properties", target))));
        if (app.contact().all().size() == 0) {
            app.contact().initClientGeneration();
            app.contact().fillClientForm(new ContactData()
                    .withFirstName(properties.getProperty("web.FirstName"))
                    .withMiddleName(properties.getProperty("web.MiddleName"))
                    .withLastName(properties.getProperty("web.LastName"))
                    .withNickName(properties.getProperty("web.NickName"))
                    .withCompany(properties.getProperty("web.Company"))
                    .withAddress(properties.getProperty("web.Address"))
                    .withHomePhone(properties.getProperty("web.HomePhone"))
                    .withMobilePhone(properties.getProperty("web.MobilePhone"))
                    .withWorkPhone(properties.getProperty("web.WorkPhone"))
                    .withFax(properties.getProperty("web.Fax"))
                    .withDate(properties.getProperty("web.Date"))
                    .withGroup(properties.getProperty("web.Group"))
                    .withEmail(properties.getProperty("web.Email"))
                    .withEmail2(properties.getProperty("web.Email2"))
                    .withEmail3(properties.getProperty("web.Email3")), true);
            app.contact().submitClientCreation();
        }
    }
    @Test
    public void testContactPhones() {
        app.goTo().homePage();
        ContactData contact = app.contact().all().iterator().next();
        ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact);
        assertThat(contact.getAllPhones(), equalTo(mergePhones(contactInfoFromEditForm)));

    }

    private String mergePhones(ContactData contact) {
        return Arrays.asList(contact.getHomePhone(), contact.getMobilePhone(), contact.getWorkPhone())
                .stream().filter((s) -> !s.equals(""))
                .map(ContactPhoneTests::cleaned)
                .collect(Collectors.joining("\n"));
    }

    private static String cleaned(String phone) {
        return phone.replaceAll("\\s", "").replaceAll("[-()]", "");
    }
}


text:
@implementation UIColor (Extension)

+ (UIColor *) getColor:(NSString *)hexColor{
    unsigned int red, green, blue;
    NSRange range;
    range.length =2;
    range.location =0;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&red];
    range.location =2;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&green];
    range.location =4;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]]scanHexInt:&blue];

    return [UIColor colorWithRed:(float)(red/255.0f)green:(float)(green/255.0f)blue:(float)(blue/255.0f)alpha:1.0f];
}

@end


text:
namespace _7days2mod_core.Models
{
    public class AppSettings
    {
        public string GitHubAppName { get; set; }
        public string GitHubClientId { get; set; }
        public string GitHubClientSecret { get; set; }
    }
}


text:
/**
  The goal of this tutorial is to implement in Tiramisu a code that is
  equivalent to the following

  for (int i = 0; i < 10; i++)
    for (int j = 0; j < 20; j++)
      output[i, j] = input[i, j] + i + 4;
*/

#include <tiramisu/tiramisu.h>

#define NN 10
#define MM 20

using namespace tiramisu;

int main(int argc, char **argv)
{
    // Set default tiramisu options.
    tiramisu::init();

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------

    // Declare the function tut_08.
    function tut_08("tut_08");

    // Declare two constants N and M. These constants will be used as loop bounds.
    // The parameters of the constant constructor are as follows:
    //    - The name of the constant is "N".
    //    - The value of the constant is expr((int32_t) NN).
    //    - The constant is of type int32.
    //    - The constant is declared in the beginning of the function tut_08 (i.e.,
    //      its scope is the whole function).
    //    - The next two arguments (NULL and 0) are unused here.
    //    - The last argument is the function in which this constant is declared.
    // For more details please refer to the documentation of the constant constructor.
    constant N_const("N", expr((int32_t) NN), p_int32, true, NULL, 0, &tut_08);
    constant M_const("M", expr((int32_t) MM), p_int32, true, NULL, 0, &tut_08);

    // Declare iterator variables.
    var i("i"), j("j");

    // Declare a wrapper around the input.
    // In Tiramisu, if a function reads an input buffer (or writes to it), that buffer
    // cannot be accessed directly, but should first be wrapped in a dummy computation.
    // This is mainly because computations in Tiramisu do not access memory directly,
    // since the algorithm is supposed to be expressed independently of how data is stored.
    // Therefor all algorithms (computations) access other computations.  The actual data
    // layout is only specified later in Layer III.
    // A wrapper is usually declared with an empty expression and is not supposed to be scheduled
    // (check the documentation of the computation constructor for more details).
    computation in("[N, M]->{in[i,j]: 0<=i<N and 0<=j<M}", expr(), false, p_uint8, &tut_08);

    // Declare expression and output computation.
    // To declare a computation, you need to provide:
    // (1) an ISL set representing the iteration space of the computation.
    // Tiramisu uses the ISL syntax to represent sets and maps.  The ISL syntax
    // is described in http://barvinok.gforge.inria.fr/barvinok.pdf (Section
    // 1.2.1 for sets and iteration domains, and 1.2.2 for maps and access
    // relations),
    // (2) a tiramisu expression: this is the expression that will be computed
    // by the computation.
    // (3) the type of the computation which is an unsigned char in this case (p_uint8).
    // (4) a boolean that indicates whether this computation should be
    // scheduled or not (more about this in the next tutorials).
    // (5) the function in which the computation will be declared.
    //
    // The best way to learn about the constructor of computations is to
    // check the documentation of the computation class in
    // https://tiramisu-compiler.github.io/doc
    expr e = in(i, j) + cast(p_uint8, i) + (uint8_t)4;
    computation output("[N, M]->{output[i,j]: 0<=i<N and 0<=j<M}", e, true, p_uint8, &tut_08);

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------

    // Set the schedule of the computation.
    var i0("i0"), i1("i1"), j0("j0"), j1("j1");

    // Tile the i, j loop around output by a 2x2 tile. The names of iterators
    // in the resulting loop are i0, j0, i1, j1.
    output.tile(i, j, 2, 2, i0, j0, i1, j1);

    // Parallelize the outermost loop i0 (OpenMP style parallelism).
    output.parallelize(i0);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------

    // Declare input and output buffers.
    buffer b_input("b_input", {expr(NN), expr(MM)}, p_uint8, a_input, &tut_08);
    buffer b_output("b_output", {expr(NN), expr(MM)}, p_uint8, a_output, &tut_08);

    // Map the computations to a buffer.
    // The following call indicates that each computation input[i,j]
    // is stored in the buffer element b_input[i,j] (one-to-one mapping).
    // This is the most common mapping to memory.
    in.set_access("{in[i,j]->b_input[i,j]}");
    output.set_access("{output[i,j]->b_output[i,j]}");

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------

    // Set the arguments to tut_08
    tut_08.codegen({&b_input, &b_output}, "build/generated_fct_developers_tutorial_08.o");

    // Some debugging
    tut_08.dump_halide_stmt();

    return 0;
}

/**
 * Current limitations:
 * - Note that the type of the invariants N and M are "int32_t". This is
 *   important because these invariants are used later as loop bounds and the
 *   type of the bounds and the iterators should be the same for correct code
 *   generation. This implies that the invariants should be of type "int32_t".
 */


text:
package org.deeplearning4j.nn.layers.convolution.subsampling;

import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacpp.Pointer;
import org.deeplearning4j.nn.conf.ConvolutionMode;
import org.deeplearning4j.nn.conf.layers.PoolingType;
import org.deeplearning4j.nn.gradient.DefaultGradient;
import org.deeplearning4j.nn.gradient.Gradient;
import org.deeplearning4j.nn.graph.ComputationGraph;
import org.deeplearning4j.nn.layers.BaseCudnnHelper;
import org.deeplearning4j.util.ConvolutionUtils;
import org.nd4j.jita.allocator.Allocator;
import org.nd4j.jita.allocator.impl.AtomicAllocator;
import org.nd4j.jita.conf.CudaEnvironment;
import org.nd4j.linalg.api.memory.MemoryWorkspace;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.executioner.GridExecutioner;
import org.nd4j.linalg.api.shape.Shape;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.jcublas.context.CudaContext;
import org.nd4j.linalg.primitives.Pair;

import static org.bytedeco.javacpp.cuda.CUstream_st;
import static org.bytedeco.javacpp.cudnn.*;

/**
 * cuDNN-based helper for the subsampling layer.
 *
 * @author saudet
 */
@Slf4j
public class CudnnSubsamplingHelper extends BaseCudnnHelper implements SubsamplingHelper {

    private static class CudnnSubsamplingContext extends CudnnContext {

        private static class Deallocator extends CudnnSubsamplingContext implements Pointer.Deallocator {
            Deallocator(CudnnSubsamplingContext c) {
                super(c);
            }

            @Override
            public void deallocate() {
                destroyHandles();
            }
        }

        private cudnnTensorStruct srcTensorDesc = new cudnnTensorStruct(), dstTensorDesc = new cudnnTensorStruct(),
                        deltaTensorDesc = new cudnnTensorStruct();
        private cudnnPoolingStruct poolingDesc = new cudnnPoolingStruct();

        public CudnnSubsamplingContext() {
            createHandles();
            deallocator(new Deallocator(this));
        }

        public CudnnSubsamplingContext(CudnnSubsamplingContext c) {
            super(c);
            srcTensorDesc = new cudnnTensorStruct(c.srcTensorDesc);
            dstTensorDesc = new cudnnTensorStruct(c.dstTensorDesc);
            deltaTensorDesc = new cudnnTensorStruct(c.deltaTensorDesc);
            poolingDesc = new cudnnPoolingStruct(c.poolingDesc);
        }

        @Override
        protected void createHandles() {
            super.createHandles();
            checkCudnn(cudnnCreateTensorDescriptor(srcTensorDesc));
            checkCudnn(cudnnCreateTensorDescriptor(dstTensorDesc));
            checkCudnn(cudnnCreateTensorDescriptor(deltaTensorDesc));
            checkCudnn(cudnnCreatePoolingDescriptor(poolingDesc));
        }

        @Override
        protected void destroyHandles() {
            checkCudnn(cudnnDestroyPoolingDescriptor(poolingDesc));
            checkCudnn(cudnnDestroyTensorDescriptor(srcTensorDesc));
            checkCudnn(cudnnDestroyTensorDescriptor(dstTensorDesc));
            checkCudnn(cudnnDestroyTensorDescriptor(deltaTensorDesc));
            super.destroyHandles();
        }
    }

    private CudnnSubsamplingContext cudnnContext = new CudnnSubsamplingContext();
    private INDArray reduced = null;

    @Override
    public Pair<Gradient, INDArray> backpropGradient(INDArray input, INDArray epsilon, int[] kernel, int[] strides,
                    int[] pad, PoolingType poolingType, ConvolutionMode convolutionMode, int[] dilation) {
        if(dilation[0] != 1 || dilation[1] != 1){
            //CuDNN doesn't support dilated subsampling
            return null;
        }

        int miniBatch = input.size(0);
        int depth = input.size(1);
        int inH = input.size(2);
        int inW = input.size(3);

        int[] outSize;
        if (convolutionMode == ConvolutionMode.Same) {
            outSize = ConvolutionUtils.getOutputSize(input, kernel, strides, null, convolutionMode, dilation); //Also performs validation
            pad = ConvolutionUtils.getSameModeTopLeftPadding(outSize, new int[] {input.size(2), input.size(3)}, kernel,
                            strides, dilation);
        } else {
            outSize = ConvolutionUtils.getOutputSize(input, kernel, strides, pad, convolutionMode, dilation); //Also performs validation
        }

        int outH = outSize[0];
        int outW = outSize[1];

        //subsampling doesn't have weights and thus gradients are not calculated for this layer
        //only scale and reshape epsilon
        Gradient retGradient = new DefaultGradient();

        //Epsilons in shape: [miniBatch, depth, outH, outW]
        //Epsilons out shape: [miniBatch, depth, inH, inW]

        int poolingMode;
        switch (poolingType) {
            case AVG:
                poolingMode = CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING;
                break;
            case MAX:
                poolingMode = CUDNN_POOLING_MAX;
                break;
            case NONE:
                return new Pair<>(retGradient, epsilon);
            default:
                return null;
        }

        if (!Shape.strideDescendingCAscendingF(epsilon)) {
            // apparently not supported by cuDNN
            epsilon = epsilon.dup();
        }

        int[] srcStride = input.stride();
        int[] deltaStride = epsilon.stride();

        if (Nd4j.getExecutioner() instanceof GridExecutioner)
            ((GridExecutioner) Nd4j.getExecutioner()).flushQueue();

        checkCudnn(cudnnSetTensor4dDescriptorEx(cudnnContext.srcTensorDesc, dataType, miniBatch, depth, inH, inW,
                        srcStride[0], srcStride[1], srcStride[2], srcStride[3]));
        checkCudnn(cudnnSetTensor4dDescriptorEx(cudnnContext.deltaTensorDesc, dataType, miniBatch, depth, outH, outW,
                        deltaStride[0], deltaStride[1], deltaStride[2], deltaStride[3]));
        checkCudnn(cudnnSetPooling2dDescriptor(cudnnContext.poolingDesc, poolingMode, CUDNN_PROPAGATE_NAN, kernel[0],
                        kernel[1], pad[0], pad[1], strides[0], strides[1]));

        INDArray outEpsilon;
        if (Nd4j.getWorkspaceManager().checkIfWorkspaceExists(ComputationGraph.workspaceExternal)) {
            try (MemoryWorkspace workspace = Nd4j.getWorkspaceManager()
                            .getWorkspaceForCurrentThread(ComputationGraph.workspaceExternal).notifyScopeBorrowed()) {
                outEpsilon = Nd4j.create(new int[] {miniBatch, depth, inH, inW}, 'c');
            }
        } else
            outEpsilon = Nd4j.create(new int[] {miniBatch, depth, inH, inW}, 'c');

        int[] dstStride = outEpsilon.stride();
        checkCudnn(cudnnSetTensor4dDescriptorEx(cudnnContext.dstTensorDesc, dataType, miniBatch, depth, inH, inW,
                        dstStride[0], dstStride[1], dstStride[2], dstStride[3]));

        Allocator allocator = AtomicAllocator.getInstance();
        CudaContext context = allocator.getFlowController().prepareAction(input, epsilon, reduced, outEpsilon);
        Pointer srcData = allocator.getPointer(input, context);
        Pointer epsData = allocator.getPointer(epsilon, context);
        Pointer zData = allocator.getPointer(reduced, context);
        Pointer dstData = allocator.getPointer(outEpsilon, context);

        checkCudnn(cudnnSetStream(cudnnContext, new CUstream_st(context.getOldStream())));
        checkCudnn(cudnnPoolingBackward(cudnnContext, cudnnContext.poolingDesc, alpha, cudnnContext.deltaTensorDesc,
                        zData, cudnnContext.deltaTensorDesc, epsData, cudnnContext.srcTensorDesc, srcData, beta,
                        cudnnContext.dstTensorDesc, dstData));

        allocator.registerAction(context, outEpsilon, input, epsilon, reduced);

        if (CudaEnvironment.getInstance().getConfiguration().isDebug())
            context.syncOldStream();

        return new Pair<>(retGradient, outEpsilon);
    }

    @Override
    public INDArray activate(INDArray input, boolean training, int[] kernel, int[] strides, int[] pad,
                    PoolingType poolingType, ConvolutionMode convolutionMode, int[] dilation) {
        if(dilation[0] != 1 || dilation[1] != 1){
            //CuDNN doesn't support dilated subsampling
            return null;
        }

        int miniBatch = input.size(0);
        int inDepth = input.size(1);
        int inH = input.size(2);
        int inW = input.size(3);

        int[] outSize;
        if (convolutionMode == ConvolutionMode.Same) {
            outSize = ConvolutionUtils.getOutputSize(input, kernel, strides, null, convolutionMode, dilation); //Also performs validation
            pad = ConvolutionUtils.getSameModeTopLeftPadding(outSize, new int[] {input.size(2), input.size(3)}, kernel,
                            strides, dilation);
        } else {
            outSize = ConvolutionUtils.getOutputSize(input, kernel, strides, pad, convolutionMode, dilation); //Also performs validation
        }

        int outH = outSize[0];
        int outW = outSize[1];

        int poolingMode;
        switch (poolingType) {
            case AVG:
                poolingMode = CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING;
                break;
            case MAX:
                poolingMode = CUDNN_POOLING_MAX;
                break;
            case NONE:
                return input;
            default:
                return null;
        }

        if (Nd4j.getExecutioner() instanceof GridExecutioner)
            ((GridExecutioner) Nd4j.getExecutioner()).flushQueue();

        int[] srcStride = input.stride();
        checkCudnn(cudnnSetPooling2dDescriptor(cudnnContext.poolingDesc, poolingMode, CUDNN_PROPAGATE_NAN, kernel[0],
                        kernel[1], pad[0], pad[1], strides[0], strides[1]));
        checkCudnn(cudnnSetTensor4dDescriptorEx(cudnnContext.srcTensorDesc, dataType, miniBatch, inDepth, inH, inW,
                        srcStride[0], srcStride[1], srcStride[2], srcStride[3]));

        if (Nd4j.getWorkspaceManager().checkIfWorkspaceExists(ComputationGraph.workspaceExternal)) {
            try (MemoryWorkspace workspace = Nd4j.getWorkspaceManager()
                            .getWorkspaceForCurrentThread(ComputationGraph.workspaceExternal).notifyScopeBorrowed()) {
                reduced = Nd4j.createUninitialized(new int[] {miniBatch, inDepth, outH, outW}, 'c');
            }
        } else
            reduced = Nd4j.createUninitialized(new int[] {miniBatch, inDepth, outH, outW}, 'c');

        int[] dstStride = reduced.stride();
        checkCudnn(cudnnSetTensor4dDescriptorEx(cudnnContext.dstTensorDesc, dataType, miniBatch, inDepth, outH, outW,
                        dstStride[0], dstStride[1], dstStride[2], dstStride[3]));

        Allocator allocator = AtomicAllocator.getInstance();
        CudaContext context = allocator.getFlowController().prepareAction(input, reduced);
        Pointer srcData = allocator.getPointer(input, context);
        Pointer dstData = allocator.getPointer(reduced, context);

        checkCudnn(cudnnSetStream(cudnnContext, new CUstream_st(context.getOldStream())));
        checkCudnn(cudnnPoolingForward(cudnnContext, cudnnContext.poolingDesc, alpha, cudnnContext.srcTensorDesc,
                        srcData, beta, cudnnContext.dstTensorDesc, dstData));

        allocator.registerAction(context, reduced, input);

        if (CudaEnvironment.getInstance().getConfiguration().isDebug())
            context.syncOldStream();

        return reduced;
    }

}