text:
package org.kie.workbench.common.forms.migration.tool.pipelines.basic;

import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

import org.assertj.core.api.Assertions;
import org.assertj.core.api.Condition;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.forms.fields.shared.fieldTypes.basic.textBox.definition.TextBoxFieldDefinition;
import org.kie.workbench.common.forms.migration.legacy.model.Field;
import org.kie.workbench.common.forms.migration.legacy.model.Form;
import org.kie.workbench.common.forms.migration.tool.FormMigrationSummary;
import org.kie.workbench.common.forms.migration.tool.Resource;
import org.kie.workbench.common.forms.migration.tool.pipelines.MigrationContext;
import org.kie.workbench.common.forms.migration.tool.util.FormsMigrationConstants;
import org.kie.workbench.common.forms.model.FieldDefinition;
import org.kie.workbench.common.forms.model.FormDefinition;
import org.kie.workbench.common.migration.cli.RealSystemAccess;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.uberfire.backend.vfs.Path;
import org.uberfire.ext.layout.editor.api.editor.LayoutColumn;
import org.uberfire.ext.layout.editor.api.editor.LayoutComponent;
import org.uberfire.ext.layout.editor.api.editor.LayoutRow;
import org.uberfire.ext.layout.editor.api.editor.LayoutTemplate;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class FormDefinitionGeneratorWithUnsupportedFieldsTest extends AbstractFormDefinitionGeneratorTest {

    private static final String USER_WITH_UNSUPPORTED_FIELDS = "user_unsupported_fields.form";

    @Mock
    private Path userFormPath;

    private Form userForm;

    @Override
    protected void doInit() throws Exception {
        List<FormMigrationSummary> summaries = new ArrayList<>();

        initForm(form -> userForm = form, DATAOBJECTS_RESOURCES, USER_WITH_UNSUPPORTED_FIELDS, userFormPath);
        summaries.add(new FormMigrationSummary(new Resource<>(userForm, userFormPath)));

        context = new MigrationContext(workspaceProject, weldContainer, formsMigrationServicesCDIWrapper, new RealSystemAccess(), summaries, migrationServicesCDIWrapper);
    }

    @Test
    public void testMigration() {
        generator.execute(context);

        Assertions.assertThat(context.getSummaries())
                .isNotEmpty()
                .hasSize(1);

        Assertions.assertThat(context.getExtraSummaries())
                .isEmpty();

        // 1 legacyforms + 1 migrated forms
        verify(migrationServicesCDIWrapper, times(2)).write(any(Path.class), anyString(), anyString());

        FormMigrationSummary summary = context.getSummaries().iterator().next();

        Form originalForm = summary.getOriginalForm().get();

        FormDefinition newForm = summary.getNewForm().get();

        assertNotNull(newForm);

        Assertions.assertThat(newForm.getFields())
                .isNotEmpty()
                .hasSize(1);

        LayoutTemplate newLayout = newForm.getLayoutTemplate();

        assertNotNull(newLayout);

        Assertions.assertThat(newLayout.getRows())
                .isNotEmpty()
                .hasSize(2);

        // Checking first field (login), althought the original field type isn't supported it can be migrated to a textbox
        Field originalLogin = originalForm.getField(USER_LOGIN);
        FieldDefinition newLogin = newForm.getFieldByName(USER_LOGIN);

        assertNotNull(newLogin);

        checkFieldDefinition(newLogin, USER_LOGIN, "login", "login", TextBoxFieldDefinition.class, newForm, originalLogin);

        LayoutRow loginRow = newLayout.getRows().get(0);

        assertNotNull(loginRow);

        Assertions.assertThat(loginRow.getLayoutColumns())
                .isNotEmpty()
                .hasSize(1);

        LayoutColumn loginColumn = loginRow.getLayoutColumns().get(0);

        assertNotNull(loginColumn);
        assertEquals("12", loginColumn.getSpan());

        Assertions.assertThat(loginColumn.getLayoutComponents())
                .isNotEmpty()
                .hasSize(1);

        checkLayoutFormField(loginColumn.getLayoutComponents().get(0), newLogin, newForm);

        // Checking second field (password), the original field type isn't supported and it cannot be migrated to any
        // other form control. There shouldn't be any FieldDefinition for it but it should be an HTML component on
        // the layout warning about the error
        assertNull(newForm.getFieldByName(USER_PASSWORD));

        LayoutRow passwordRow = newLayout.getRows().get(1);

        assertNotNull(passwordRow);

        Assertions.assertThat(passwordRow.getLayoutColumns())
                .isNotEmpty()
                .hasSize(1);

        LayoutColumn passwordColumn = passwordRow.getLayoutColumns().get(0);

        assertNotNull(passwordColumn);
        assertEquals("12", passwordColumn.getSpan());

        Assertions.assertThat(passwordColumn.getLayoutComponents())
                .isNotEmpty()
                .hasSize(1);

        LayoutComponent passwordComponent = passwordColumn.getLayoutComponents().get(0);

        Assertions.assertThat(passwordComponent)
                .isNotNull()
                .hasFieldOrPropertyWithValue("dragTypeName", FormsMigrationConstants.HTML_COMPONENT);

        Field originalPassword = originalForm.getField(USER_PASSWORD);

        Formatter formatter = new Formatter();
        formatter.format(FormsMigrationConstants.UNSUPORTED_FIELD_HTML_TEMPLATE, originalPassword.getFieldName(), originalPassword.getFieldType().getCode());

        final String expectedHtmlMessage = formatter.toString();

        Assertions.assertThat(passwordComponent.getProperties())
                .hasEntrySatisfying(FormsMigrationConstants.HTML_CODE_PARAMETER, new Condition<>(htmlMessage -> htmlMessage.equals(expectedHtmlMessage), "Invalid error HTML message"));

        formatter.close();
    }
}


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [@snowplow/browser-tracker](./browser-tracker.md) > [ActivityTrackingConfigurationCallback](./browser-tracker.activitytrackingconfigurationcallback.md) > [callback](./browser-tracker.activitytrackingconfigurationcallback.callback.md)

## ActivityTrackingConfigurationCallback.callback property

The callback to fire based on heart beat

<b>Signature:</b>

```typescript
callback: ActivityCallback;
```

redpajama_set_name: RedPajamaGithub


text:
$('#single-testimonial-item').owlCarousel({
        items : 1,
        navigation : true,
        pagination: false,
        slideSpeed : 300,
        paginationSpeed : 400,
        singleItem:true
    });

    $('#single-testimonial-item').find('.owl-prev').html('');
    $('#single-testimonial-item').find('.owl-next').html('');

      $('#image-carousel').owlCarousel({
        navigation : false,
        pagination: true,
        items : 4,
        itemsDesktop : [1199,3],
        itemsDesktopSmall : [979,3]
      });

      $('#posts-carousel').owlCarousel({
        navigation : true,
        pagination: true,
        items : 4,
        itemsDesktop : [1199,3],
        itemsDesktopSmall : [979,3]
      });

      $('#posts-carousel').find('.owl-prev').html('');
      $('#posts-carousel').find('.owl-next').html('');

      $('#posts-carousel-3col').owlCarousel({
        navigation : true,
        pagination: false,
        items : 3,
        itemsDesktop : [1199,3],
        itemsDesktopSmall : [979,3]
      });

      $('#posts-carousel-3col').find('.owl-prev').html('');
      $('#posts-carousel-3col').find('.owl-next').html('');

      $('#image-slider').owlCarousel({
          navigation : true, // Show next and prev buttons
          slideSpeed : 300,
          paginationSpeed : 400,
          singleItem:true
      });
      $('#image-slider').find('.owl-prev').html('');
      $('#image-slider').find('.owl-next').html('');


text:
from django.contrib import admin
from .models import Player

admin.site.register(Player)


text:
import numpy as np
from dipy.data import get_sphere, get_3shell_gtab, get_isbi2013_2shell_gtab
from dipy.reconst.shore import ShoreModel
from dipy.reconst.shm import QballModel, sh_to_sf
from dipy.direction.peaks import gfa, peak_directions
from numpy.testing import (assert_equal,
                           assert_almost_equal,
                           run_module_suite,
                           assert_array_equal,
                           assert_raises)
from dipy.sims.voxel import SticksAndBall
from dipy.core.subdivide_octahedron import create_unit_sphere
from dipy.core.sphere_stats import angular_similarity
from dipy.reconst.tests.test_dsi import sticks_and_ball_dummies

def test_shore_odf():
    gtab = get_isbi2013_2shell_gtab()

    # load symmetric 724 sphere
    sphere = get_sphere('symmetric724')

    # load icosahedron sphere
    sphere2 = create_unit_sphere(5)
    data, golden_directions = SticksAndBall(gtab, d=0.0015,
                                            S0=100, angles=[(0, 0), (90, 0)],
                                            fractions=[50, 50], snr=None)
    asm = ShoreModel(gtab, radial_order=6,
                     zeta=700, lambdaN=1e-8, lambdaL=1e-8)
    # symmetric724
    asmfit = asm.fit(data)
    odf = asmfit.odf(sphere)
    odf_sh = asmfit.odf_sh()
    odf_from_sh = sh_to_sf(odf_sh, sphere, 6, basis_type=None)
    assert_almost_equal(odf, odf_from_sh, 10)

    directions, _, _ = peak_directions(odf, sphere, .35, 25)
    assert_equal(len(directions), 2)
    assert_almost_equal(
        angular_similarity(directions, golden_directions), 2, 1)

    # 5 subdivisions
    odf = asmfit.odf(sphere2)
    directions, _, _ = peak_directions(odf, sphere2, .35, 25)
    assert_equal(len(directions), 2)
    assert_almost_equal(
        angular_similarity(directions, golden_directions), 2, 1)

    sb_dummies = sticks_and_ball_dummies(gtab)
    for sbd in sb_dummies:
        data, golden_directions = sb_dummies[sbd]
        asmfit = asm.fit(data)
        odf = asmfit.odf(sphere2)
        directions, _ , _ = peak_directions(odf, sphere2, .35, 25)
        if len(directions) <= 3:
            assert_equal(len(directions), len(golden_directions))
        if len(directions) > 3:
            assert_equal(gfa(odf) < 0.1, True)

def test_multivox_shore():
    gtab = get_3shell_gtab()

    data = np.random.random([20, 30, 1, gtab.gradients.shape[0]])
    radial_order = 4
    zeta = 700
    asm = ShoreModel(gtab, radial_order=radial_order,
                     zeta=zeta, lambdaN=1e-8, lambdaL=1e-8)
    asmfit = asm.fit(data)
    c_shore = asmfit.shore_coeff
    assert_equal(c_shore.shape[0:3], data.shape[0:3])
    assert_equal(np.alltrue(np.isreal(c_shore)), True)

if __name__ == '__main__':
    run_module_suite()


text:
/**
 * MenuSection
 */

import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import uniqueId from 'lodash/uniqueId';
import css from './MenuSection.css';
import Headline from '../Headline';

const MenuSection = ({ className, children, id, label, labelTag, ...rest }) => {
  const sectionId = id || uniqueId('menu-section-');
  return (
    <section
      id={sectionId}
      className={classNames(css.menuSection, className)}
      aria-labelledby={`${sectionId}-label`}
      {...rest}
      data-test-menu-section
    >
      { label && (
        <Headline
          id={`${sectionId}-label`}
          size="small"
          margin="none"
          tag={labelTag}
          className={css.menuSection__label}
          faded
          data-test-menu-section-label
        >
          {label}
        </Headline>
      )}
      {children}
    </section>
  );
};

MenuSection.propTypes = {
  children: PropTypes.node,
  className: PropTypes.string,
  id: PropTypes.string,
  label: PropTypes.node,
  labelTag: PropTypes.oneOf(['div', 'h2', 'h3', 'h4', 'h5', 'h6'])
};

MenuSection.defaultProps = {
  labelTag: 'div',
};

export default MenuSection;


text:
package appevents_test

import (
	"net/http"
	"net/http/httptest"

	"time"

	. "code.cloudfoundry.org/cli/cf/api/appevents"
	"code.cloudfoundry.org/cli/cf/api/strategy"
	"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
	"code.cloudfoundry.org/cli/cf/models"
	"code.cloudfoundry.org/cli/cf/net"
	"code.cloudfoundry.org/cli/cf/terminal/terminalfakes"
	"code.cloudfoundry.org/cli/cf/trace/tracefakes"
	testconfig "code.cloudfoundry.org/cli/utils/testhelpers/configuration"
	testnet "code.cloudfoundry.org/cli/utils/testhelpers/net"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("App Events Repo", func() {
	var (
		server  *httptest.Server
		handler *testnet.TestHandler
		config  coreconfig.ReadWriter
		repo    Repository
	)

	BeforeEach(func() {
		config = testconfig.NewRepository()
		config.SetAccessToken("BEARER my_access_token")
		config.SetAPIVersion("2.2.0")
	})

	JustBeforeEach(func() {
		strategy := strategy.NewEndpointStrategy(config.APIVersion())
		gateway := net.NewCloudControllerGateway(config, time.Now, new(terminalfakes.FakeUI), new(tracefakes.FakePrinter), "")
		repo = NewCloudControllerAppEventsRepository(config, gateway, strategy)
	})

	AfterEach(func() {
		server.Close()
	})

	setupTestServer := func(requests ...testnet.TestRequest) {
		server, handler = testnet.NewServer(requests)
		config.SetAPIEndpoint(server.URL)
	}

	Describe("list recent events", func() {
		It("returns the most recent events", func() {
			setupTestServer(eventsRequest)

			list, err := repo.RecentEvents("my-app-guid", 2)
			Expect(err).ToNot(HaveOccurred())
			timestamp, err := time.Parse(eventTimestampFormat, "2014-01-21T00:20:11+00:00")
			Expect(err).ToNot(HaveOccurred())

			Expect(list).To(ConsistOf([]models.EventFields{
				{
					GUID:        "event-1-guid",
					Name:        "audit.app.update",
					Timestamp:   timestamp,
					Description: "instances: 1, memory: 256, command: PRIVATE DATA HIDDEN, environment_json: PRIVATE DATA HIDDEN",
					Actor:       "cf-1-client",
					ActorName:   "somebody@pivotallabs.com",
				},
				{
					GUID:        "event-2-guid",
					Name:        "audit.app.update",
					Timestamp:   timestamp,
					Description: "instances: 1, memory: 256, command: PRIVATE DATA HIDDEN, environment_json: PRIVATE DATA HIDDEN",
					Actor:       "cf-2-client",
					ActorName:   "nobody@pivotallabs.com",
				},
			}))
		})
	})
})

const eventTimestampFormat = "2006-01-02T15:04:05-07:00"

var eventsRequest = testnet.TestRequest{
	Method: "GET",
	Path:   "/v2/events?q=actee%3Amy-app-guid&order-direction=desc&results-per-page=2",
	Response: testnet.TestResponse{
		Status: http.StatusOK,
		Body: `{
		  "total_results": 1,
		  "total_pages": 1,
		  "prev_url": null,
		  "next_url": "/v2/events?q=actee%3Amy-app-guid&page=2",
		  "resources": [
			{
			  "metadata": {
				"guid": "event-1-guid"
			  },
			  "entity": {
				"type": "audit.app.update",
				"timestamp": "2014-01-21T00:20:11+00:00",
				"actor": "cf-1-client",
				"actor_name": "somebody@pivotallabs.com",
				"metadata": {
				  "request": {
					"command": "PRIVATE DATA HIDDEN",
					"instances": 1,
					"memory": 256,
					"name": "dora",
					"environment_json": "PRIVATE DATA HIDDEN"
				  }
				}
			  }
			},
			{
			  "metadata": {
				"guid": "event-2-guid"
			  },
			  "entity": {
				"type": "audit.app.update",
				"actor": "cf-2-client",
				"actor_name": "nobody@pivotallabs.com",
				"timestamp": "2014-01-21T00:20:11+00:00",
				"metadata": {
				  "request": {
					"command": "PRIVATE DATA HIDDEN",
					"instances": 1,
					"memory": 256,
					"name": "dora",
					"environment_json": "PRIVATE DATA HIDDEN"
				  }
				}
			  }
			}
		  ]
		}`}}


text:
package com.amazonaws.services.ec2.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * LaunchTemplateHibernationOptionsRequest StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class LaunchTemplateHibernationOptionsRequestStaxUnmarshaller implements Unmarshaller<LaunchTemplateHibernationOptionsRequest, StaxUnmarshallerContext> {

    public LaunchTemplateHibernationOptionsRequest unmarshall(StaxUnmarshallerContext context) throws Exception {
        LaunchTemplateHibernationOptionsRequest launchTemplateHibernationOptionsRequest = new LaunchTemplateHibernationOptionsRequest();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return launchTemplateHibernationOptionsRequest;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("Configured", targetDepth)) {
                    launchTemplateHibernationOptionsRequest.setConfigured(BooleanStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return launchTemplateHibernationOptionsRequest;
                }
            }
        }
    }

    private static LaunchTemplateHibernationOptionsRequestStaxUnmarshaller instance;

    public static LaunchTemplateHibernationOptionsRequestStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new LaunchTemplateHibernationOptionsRequestStaxUnmarshaller();
        return instance;
    }
}


text:
package net.rafaeltoledo.gamestore.ui.feature.home;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import net.rafaeltoledo.gamestore.R;
import net.rafaeltoledo.gamestore.ui.model.Banner;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

public class BannerAdapter extends PagerAdapter {

    private final List<Banner> banners;

    BannerAdapter(List<Banner> banners) {
        this.banners = banners;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup collection, int position) {
        LayoutInflater inflater = LayoutInflater.from(collection.getContext());
        ImageView banner = (ImageView) inflater.inflate(R.layout.item_banner, collection, false);
        Glide.with(collection.getContext()).load(banners.get(position).getImage()).into(banner);
        collection.addView(banner);
        return banner;
    }

    @Override
    public int getCount() {
        return banners.size();
    }

    @Override
    public void destroyItem(@NonNull ViewGroup collection, int position, @NonNull Object view) {
        collection.removeView((View) view);
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }
}


text:
/* skin/bg */

html {
    background: url(../img/linedpaper.png);
}


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ProductManager.ViewData.Entity;

namespace ProductManager.ViewModel.ProductManagers
{
    public class DeleteFileViewWindowViewModel : NotifyPropertyChanged
    {
        private ChildWindow childWindow;

        public ProjectFilesEntity ProjectFileEntity { get; set; }

        public String Title { get; set; }

        public ICommand OnOK { get; private set; }
        public ICommand OnCancel { get; private set; }

        public DeleteFileViewWindowViewModel(ChildWindow aChildWindow, ProjectFilesEntity aProjectFileEntity)
        {
            childWindow = aChildWindow;
            ProjectFileEntity = aProjectFileEntity;
            Title = "已删除文件:" + ProjectFileEntity.FileName;

            OnOK = new DelegateCommand(OnOKCommand);
            OnCancel = new DelegateCommand(OnCancelCommand);
        }

        private void OnOKCommand()
        {
            childWindow.DialogResult = true;
        }

        private void OnCancelCommand()
        {
            childWindow.DialogResult = false;
        }
    }
}


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\User;
use AppBundle\Entity\Role;
use AppBundle\Form\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class UserController extends Controller
{
    /**
     * @Route("/login", name="login")
     */
    public function loginAction(Request $request)
    {
        $authenticationUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', array(
            'last_username' => $lastUsername,
            'error'         => $error,
        ));
    }
//    /**
//     * @Route("/login_check", name="check")
//     */
//    public function loginCheckAction(Request $request)
//    {
//
////        dump("test");die;
//    }

    /**
     * @Route("/register", name="register")
     */
    public function registerAction(Request $request)
    {

        $em = $this->getDoctrine()->getManager();
        // 1) build the form
        $roles = $em->getRepository('AppBundle:Role')->findAll();
        if($roles == NULL){
            $this->get('user_service')->generateGroups($em);
        }

        $user = new User($em);
        $form = $this->createForm(UserType::class, $user);

        // 2) handle the submit (will only happen on POST)
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            // 3) Encode the password (you could also do this via Doctrine listener)
            $password = $this->get('security.password_encoder')
                ->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);
            // 4) save the User!
            $em->persist($user);
            $em->flush();

            return $this->redirectToRoute('homepage');
        }

        return $this->render(
            'security/register.html.twig',
            array('form' => $form->createView())
        );
    }

    /**
     * @Route("/godpalace", name="become_a_god")
     */
    public function godAction(Request $request){

        $em = $this->getDoctrine()->getManager();
        $log_user = $this->getUser()->getId();
//        dump($log_user->getId());die;
        $user = $em->getRepository('AppBundle:User')->find($log_user);
//        dump($user);
        $role = $em->getRepository('AppBundle:Role')->findAll();
//        dump($role[0]);die;
        $user->addRole($role[0]);
//        dump($user);die;
        $em->persist($user);
        $em->flush();
        $token = $this->get('security.token_storage')->getToken()->setAuthenticated(false);
        return $this->redirectToRoute('homepage');

    }

    /**
     * @Route("/logout", name="logout")
     */
    public function logoutAction() {
        throw new \RuntimeException('You must activate the logout in your security firewall configuration.');
    }
}


text:
declare type InternalComponentOptions = {
  _isComponent: true;
  parent: Component;
  _parentVnode: VNode;
  _parentElm: ?Node;
  _refElm: ?Node;
  render?: Function;
  staticRenderFns?: Array<Function>
};

type InjectKey = string | Symbol;

declare type ComponentOptions = {
  componentId?: string;

  // data
  data: Object | Function | void;
  props?: { [key: string]: PropOptions };
  propsData?: ?Object;
  computed?: {
    [key: string]: Function | {
      get?: Function;
      set?: Function;
      cache?: boolean
    }
  };
  methods?: { [key: string]: Function };
  watch?: { [key: string]: Function | string };

  // DOM
  el?: string | Element;
  template?: string;
  render: (h: () => VNode) => VNode;
  renderError?: (h: () => VNode, err: Error) => VNode;
  staticRenderFns?: Array<() => VNode>;

  // lifecycle
  beforeCreate?: Function;
  created?: Function;
  beforeMount?: Function;
  mounted?: Function;
  beforeUpdate?: Function;
  updated?: Function;
  activated?: Function;
  deactivated?: Function;
  beforeDestroy?: Function;
  destroyed?: Function;
  errorCaptured?: () => boolean | void;

  // assets
  directives?: { [key: string]: Object };
  components?: { [key: string]: Class<Component> };
  transitions?: { [key: string]: Object };
  filters?: { [key: string]: Function };

  // context
  provide?: { [key: string | Symbol]: any } | () => { [key: string | Symbol]: any };
  inject?: { [key: string]: InjectKey | { from?: InjectKey, default?: any }} | Array<string>;

  // component v-model customization
  model?: {
    prop?: string;
    event?: string;
  };

  // misc
  parent?: Component;
  mixins?: Array<Object>;
  name?: string;
  extends?: Class<Component> | Object;
  delimiters?: [string, string];
  comments?: boolean;
  inheritAttrs?: boolean;

  // private
  _isComponent?: true;
  _propKeys?: Array<string>;
  _parentVnode?: VNode;
  _parentListeners?: ?Object;
  _renderChildren?: ?Array<VNode>;
  _componentTag: ?string;
  _scopeId: ?string;
  _base: Class<Component>;
  _parentElm: ?Node;
  _refElm: ?Node;
};

declare type PropOptions = {
  type: Function | Array<Function> | null;
  default: any;
  required: ?boolean;
  validator: ?Function;
}


text:
const
    // General
    API_URL = "Web/API.php",
    API_METHOD_GET = 0,
    API_METHOD_POST = 1;

// Write API methods below

function API_SendRequest(Method, Interface, Action, Data, Callback) {
    if (Method === API_METHOD_GET)
        $.get(API_URL, {
            "Interface": Interface,
            "Action": Action,
            "Data": Data
        }, Callback, "json");
    else if (Method === API_METHOD_POST)
        $.post(API_URL, {
            "Interface": Interface,
            "Action": Action,
            "Data": Data
        }, Callback, "json");
}


text:
require 'sinatra/base'
require 'slim'

class AndrewThorp < Sinatra::Base
  set :root,            'app'
  set :public_folder,   Proc.new { File.join(root, 'public') }
  set :views,           Proc.new { File.join(root, 'views') }

  get '/' do
    slim :index
  end

  get '/pgp' do
    slim :pgp
  end

  run! if app_file == $0
end


text:
package io.grpc.internal.testing;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import javax.security.auth.x500.X500Principal;

/**
 * Internal utility functions useful for writing tests.
 */
public class TestUtils {
  public static final String TEST_SERVER_HOST = "foo.test.google.fr";

  /**
   * Creates a new {@link InetSocketAddress} that overrides the host with {@link #TEST_SERVER_HOST}.
   */
  public static InetSocketAddress testServerAddress(String host, int port) {
    try {
      InetAddress inetAddress = InetAddress.getByName(host);
      inetAddress = InetAddress.getByAddress(TEST_SERVER_HOST, inetAddress.getAddress());
      return new InetSocketAddress(inetAddress, port);
    } catch (UnknownHostException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Creates a new {@link InetSocketAddress} on localhost that overrides the host with
   * {@link #TEST_SERVER_HOST}.
   */
  public static InetSocketAddress testServerAddress(int port) {
    try {
      InetAddress inetAddress = InetAddress.getByName("localhost");
      inetAddress = InetAddress.getByAddress(TEST_SERVER_HOST, inetAddress.getAddress());
      return new InetSocketAddress(inetAddress, port);
    } catch (UnknownHostException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Returns the ciphers preferred to use during tests. They may be chosen because they are widely
   * available or because they are fast. There is no requirement that they provide confidentiality
   * or integrity.
   */
  public static List<String> preferredTestCiphers() {
    String[] ciphers;
    try {
      ciphers = SSLContext.getDefault().getDefaultSSLParameters().getCipherSuites();
    } catch (NoSuchAlgorithmException ex) {
      throw new RuntimeException(ex);
    }
    List<String> ciphersMinusGcm = new ArrayList<>();
    for (String cipher : ciphers) {
      // The GCM implementation in Java is _very_ slow (~1 MB/s)
      if (cipher.contains("_GCM_")) {
        continue;
      }
      ciphersMinusGcm.add(cipher);
    }
    return Collections.unmodifiableList(ciphersMinusGcm);
  }

  /**
   * Saves a file from the classpath resources in src/main/resources/certs as a file on the
   * filesystem.
   *
   * @param name  name of a file in src/main/resources/certs.
   */
  public static File loadCert(String name) throws IOException {
    InputStream
        in = new BufferedInputStream(TestUtils.class.getResourceAsStream("/certs/" + name));
    File tmpFile = File.createTempFile(name, "");
    tmpFile.deleteOnExit();

    OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile));
    try {
      int b;
      while ((b = in.read()) != -1) {
        os.write(b);
      }
      os.flush();
    } finally {
      in.close();
      os.close();
    }

    return tmpFile;
  }

  /**
   * Loads an X.509 certificate from the classpath resources in src/main/resources/certs.
   *
   * @param fileName  name of a file in src/main/resources/certs.
   */
  public static X509Certificate loadX509Cert(String fileName)
      throws CertificateException, IOException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream in = TestUtils.class.getResourceAsStream("/certs/" + fileName);
    try {
      return (X509Certificate) cf.generateCertificate(in);
    } finally {
      in.close();
    }
  }

  private static boolean conscryptInstallAttempted;

  /**
   * Add Conscrypt to the list of security providers, if it is available. If it appears to be
   * available but fails to load, this method will throw an exception. Since the list of security
   * providers is static, this method does nothing if the provider is not available or succeeded
   * previously.
   */
  public static void installConscryptIfAvailable() {
    if (conscryptInstallAttempted) {
      return;
    }
    Class<?> conscrypt;
    try {
      conscrypt = Class.forName("org.conscrypt.Conscrypt");
    } catch (ClassNotFoundException ex) {
      conscryptInstallAttempted = true;
      return;
    }
    Method newProvider;
    try {
      newProvider = conscrypt.getMethod("newProvider");
    } catch (NoSuchMethodException ex) {
      throw new RuntimeException("Could not find newProvider method on Conscrypt", ex);
    }
    Provider provider;
    try {
      provider = (Provider) newProvider.invoke(null);
    } catch (IllegalAccessException ex) {
      throw new RuntimeException("Could not invoke Conscrypt.newProvider", ex);
    } catch (InvocationTargetException ex) {
      throw new RuntimeException("Could not invoke Conscrypt.newProvider", ex);
    }
    Security.addProvider(provider);
    conscryptInstallAttempted = true;
  }

  /**
   * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
   */
  public static SSLSocketFactory newSslSocketFactoryForCa(Provider provider,
                                                          File certChainFile) throws Exception {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(
        new BufferedInputStream(new FileInputStream(certChainFile)));
    X500Principal principal = cert.getSubjectX500Principal();
    ks.setCertificateEntry(principal.getName("RFC2253"), cert);

    // Set up trust manager factory to use our key store.
    TrustManagerFactory trustManagerFactory =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(ks);
    SSLContext context = SSLContext.getInstance("TLS", provider);
    context.init(null, trustManagerFactory.getTrustManagers(), null);
    return context.getSocketFactory();
  }

  /**
   * Sleeps for at least the specified time. When in need of a guaranteed sleep time, use this in
   * preference to {@code Thread.sleep} which might not sleep for the required time.
   */
  public static void sleepAtLeast(long millis) throws InterruptedException {
    long delay = TimeUnit.MILLISECONDS.toNanos(millis);
    long end = System.nanoTime() + delay;
    while (delay > 0) {
      TimeUnit.NANOSECONDS.sleep(delay);
      delay = end - System.nanoTime();
    }
  }

  private TestUtils() {}
}


text:
/**
 * Append anchor elements to all heading elements that live inside the
 * `<main>` element, apply unique `id` attribute values to each heading and
 * use that same value for each anchor `href` value.
 */

var appendAnchorsToHeadings = function appendAnchorsToHeadings() {

    // The `<main>` element where all the headings live
    var main = $(".js-main");

    // Grab all the headings minus the `h1` inside the `<main>` element
    var allHeadingsMinusLevelOne = main.querySelectorAll(
        "h2.heading, h3.heading, h4.heading, h5.heading, h6.heading"
    );

    // The inner HTML of the anchor
    var anchorHTML =
        "Anchor to this heading<svg aria-hidden='true'><use xmlns:xlink='http://www.w3.org/1999/xlink' xlink:href='#link-icon'></use></svg>";

    // Loop through all headings applying the anchor and heading `id`s
    for (var i = 0, max = allHeadingsMinusLevelOne.length; i < max; i++) {

        var theHeading = max;
        var theHeadingID = "heading-" + theHeading;

        // Apply an `id` to the heading
        allHeadingsMinusLevelOne[theHeading].setAttribute("id", theHeadingID);

        // Build the anchor
        var anchor = document.createElement("a");
        anchor.setAttribute("href", "#" + theHeadingID);
        anchor.classList.add("heading__anchor");
        anchor.innerHTML = anchorHTML;

        // Append an anchor to the heading
        allHeadingsMinusLevelOne[theHeading].appendChild(anchor);
    };
}


text:
<form class="form-horizontal dc-pictures">

        {{$ctrl.config.label}}

                    <comment-bubble control="$ctrl.control"
                                    field="$ctrl.fieldName"
                                    model="picture"
                                    picture="picture"
                                    parent-context-guid="$ctrl.contextGuid"
                                    config-type="$ctrl.config.type"
                                    get-picture-url="$ctrl.getPictureUrl"></comment-bubble>

                    <dc-multitext control="$ctrl.control"
                                  config="$ctrl.config"
                                  model="picture.caption"
                                  picture="picture"
                                  field-name="$ctrl.fieldName"
                                  parent-context-guid="$ctrl.contextGuid">
                    </dc-multitext>

Drop an image file here

or if you prefer...

                    <button class="btn btn-std" id="browseButton" data-ngf-select="$ctrl.uploadFile($file)">Browse...</button>

                    <button class="btn btn-std" ngf-select="$ctrl.uploadFile($file)">Browse...</button>

{{$ctrl.upload.file.name}} {{$ctrl.upload.file.size | bytes }}

                    <uib-progressbar value="$ctrl.upload.progress" max="100.0"></uib-progressbar>

</form>

     Add Picture


text:
#ifndef POLYGRAPH__PROBE_PROBECLT_H
#define POLYGRAPH__PROBE_PROBECLT_H

#include "xstd/AlarmClock.h"
#include "probe/ProbeAgent.h"

class ProbeCltXact;

class ProbeClt: public ProbeAgent, public AlarmUser {
	public:
		ProbeClt(const NetAddr &aLclHost, const NetAddr &aRmtHost);

		virtual void exec();

		void noteXactDone(ProbeCltXact *x);

		virtual void noteWriteReady(int fd);
		virtual void wakeUp(const Alarm &a);

	protected:
		void startConnect();
		void tryAgainLater();
};

#endif


text:
export default function toObject(emberObject) {
  return Object.keys(emberObject).reduce((obj, key) => {
    obj[key] = emberObject[key];
    return obj;
  }, {});
}


text:
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
    <title>Test</title>
    <script src="../../web-component-tester/browser.js"></script>
  </head>
  <body>
    <script>
      WCT.loadSuites([
        'token.html'
      ]);
    </script>
  </body>
</html>


text:
package com.wh.finaldemos.demos.otherlibs.guava;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.wh.finaldemos.R;

public class GuavaDemoActivity extends AppCompatActivity {

    private int mCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guava_demo);

        String a = null;
        //Preconditions.checkNotNull(a, "a should not null");

        Strings.isNullOrEmpty(a);

        mCount = 10;

        Log.e("wh_debug", MoreObjects.toStringHelper(this).add("me", "4104").add("mCount", mCount).toString());

    }
}


text:
module RBattlenet
  module Wow
    class Item < RBattlenet::Endpoints::Base
      def self.path(id)
        RBattlenet.uri("data/wow/item/#{id}?namespace=static-")
      end
    end
  end
end


text:
$(document).ready(function() {
    // make right selection in mainPanel
    $("#new-benefiter").removeClass("hide").addClass("purple-background");
    $("#import-file").removeClass("hide");
    $("#register-benefiter").find("div i").removeClass('glyphicon-chevron-right').addClass('glyphicon-chevron-down');
});


text:
from copy import copy
from dataclasses import dataclass
from decimal import Decimal
from typing import (
    TYPE_CHECKING,
    Any,
    Callable,
    DefaultDict,
    Iterable,
    List,
    Optional,
    Set,
    Tuple,
    Union,
)

from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse
from django.utils.functional import SimpleLazyObject
from django_countries.fields import Country
from graphene import Mutation
from graphql import GraphQLError, ResolveInfo
from graphql.execution import ExecutionResult
from prices import Money, TaxedMoney
from promise.promise import Promise

from ..core.models import EventDelivery
from ..payment.interface import (
    CustomerSource,
    GatewayResponse,
    InitializedPaymentResponse,
    PaymentData,
    PaymentGateway,
    TransactionActionData,
)
from .models import PluginConfiguration

if TYPE_CHECKING:
    # flake8: noqa
    from ..account.models import Address, Group, User
    from ..app.models import App
    from ..attribute.models import Attribute, AttributeValue
    from ..channel.models import Channel
    from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
    from ..checkout.models import Checkout
    from ..core.middleware import Requestor
    from ..core.notify_events import NotifyEventType
    from ..core.taxes import TaxData, TaxType
    from ..discount import DiscountInfo, Voucher
    from ..discount.models import Sale
    from ..giftcard.models import GiftCard
    from ..invoice.models import Invoice
    from ..menu.models import Menu, MenuItem
    from ..order.models import Fulfillment, Order, OrderLine
    from ..page.models import Page, PageType
    from ..payment.models import TransactionItem
    from ..product.models import (
        Category,
        Collection,
        Product,
        ProductType,
        ProductVariant,
    )
    from ..shipping.interface import ShippingMethodData
    from ..shipping.models import ShippingMethod, ShippingZone
    from ..warehouse.models import Warehouse

PluginConfigurationType = List[dict]
NoneType = type(None)
RequestorOrLazyObject = Union[SimpleLazyObject, "Requestor"]

class ConfigurationTypeField:
    STRING = "String"
    MULTILINE = "Multiline"
    BOOLEAN = "Boolean"
    SECRET = "Secret"
    SECRET_MULTILINE = "SecretMultiline"
    PASSWORD = "Password"
    OUTPUT = "OUTPUT"
    CHOICES = [
        (STRING, "Field is a String"),
        (MULTILINE, "Field is a Multiline"),
        (BOOLEAN, "Field is a Boolean"),
        (SECRET, "Field is a Secret"),
        (PASSWORD, "Field is a Password"),
        (SECRET_MULTILINE, "Field is a Secret multiline"),
        (OUTPUT, "Field is a read only"),
    ]

@dataclass
class ExternalAccessTokens:
    token: Optional[str] = None
    refresh_token: Optional[str] = None
    csrf_token: Optional[str] = None
    user: Optional["User"] = None

@dataclass
class ExcludedShippingMethod:
    id: str
    reason: Optional[str]

class BasePlugin:
    """Abstract class for storing all methods available for any plugin.

    All methods take previous_value parameter.
    previous_value contains a value calculated by the previous plugin in the queue.
    If the plugin is first, it will use default value calculated by the manager.
    """

    PLUGIN_NAME = ""
    PLUGIN_ID = ""
    PLUGIN_DESCRIPTION = ""
    CONFIG_STRUCTURE = None
    CONFIGURATION_PER_CHANNEL = True
    DEFAULT_CONFIGURATION = []
    DEFAULT_ACTIVE = False
    HIDDEN = False

    @classmethod
    def check_plugin_id(cls, plugin_id: str) -> bool:
        """Check if given plugin_id matches with the PLUGIN_ID of this plugin."""
        return cls.PLUGIN_ID == plugin_id

    def __init__(
        self,
        *,
        configuration: PluginConfigurationType,
        active: bool,
        channel: Optional["Channel"] = None,
        requestor_getter: Optional[Callable[[], "Requestor"]] = None,
        db_config: Optional["PluginConfiguration"] = None
    ):
        self.configuration = self.get_plugin_configuration(configuration)
        self.active = active
        self.channel = channel
        self.requestor: Optional[RequestorOrLazyObject] = (
            SimpleLazyObject(requestor_getter) if requestor_getter else requestor_getter
        )
        self.db_config = db_config

    def __str__(self):
        return self.PLUGIN_NAME

    #  Trigger when address is created.
    #
    #  Overwrite this method if you need to trigger specific logic after an address is
    #  created.
    address_created: Callable[["Address", None], None]

    #  Trigger when address is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after an address is
    #  deleted.
    address_deleted: Callable[["Address", None], None]

    #  Trigger when address is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after an address is
    #  updated.
    address_updated: Callable[["Address", None], None]

    #  Trigger when app is installed.
    #
    #  Overwrite this method if you need to trigger specific logic after an app is
    #  installed.
    app_installed: Callable[["App", None], None]

    #  Trigger when app is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after an app is
    #  deleted.
    app_deleted: Callable[["App", None], None]

    #  Trigger when app is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after an app is
    #  updated.
    app_updated: Callable[["App", None], None]

    #  Trigger when channel status is changed.
    #
    #  Overwrite this method if you need to trigger specific logic after an app
    #  status is changed.
    app_status_changed: Callable[["App", None], None]

    #  Apply taxes to the product price based on the customer country.
    #
    #  Overwrite this method if you want to show products with taxes.
    apply_taxes_to_product: Callable[
        ["Product", Money, Country, TaxedMoney], TaxedMoney
    ]

    #  Assign tax code dedicated to plugin.
    assign_tax_code_to_object_meta: Callable[
        [Union["Product", "ProductType"], Union[str, NoneType], Any], Any
    ]

    #  Trigger when attribute is created.
    #
    #  Overwrite this method if you need to trigger specific logic after an attribute is
    #  installed.
    attribute_created: Callable[["Attribute", None], None]

    #  Trigger when attribute is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after an attribute is
    #  deleted.
    attribute_deleted: Callable[["Attribute", None], None]

    #  Trigger when attribute is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after an attribute is
    #  updated.
    attribute_updated: Callable[["Attribute", None], None]

    #  Trigger when attribute value is created.
    #
    #  Overwrite this method if you need to trigger specific logic after an attribute
    #  value is installed.
    attribute_value_created: Callable[["AttributeValue", None], None]

    #  Trigger when attribute value is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after an attribute
    #  value is deleted.
    attribute_value_deleted: Callable[["AttributeValue", None], None]

    #  Trigger when attribute value is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after an attribute
    #  value is updated.
    attribute_value_updated: Callable[["AttributeValue", None], None]

    #  Authenticate user which should be assigned to the request.
    #
    #  Overwrite this method if the plugin handles authentication flow.
    authenticate_user: Callable[
        [WSGIRequest, Optional["User"]], Union["User", NoneType]
    ]

    authorize_payment: Callable[["PaymentData", Any], GatewayResponse]

    #  Update order lines taxes.
    #
    #  Overwrite this method if you need to apply specific logic for applying taxes on
    #  order lines. Return Iterable["OrderLine"].
    update_taxes_for_order_lines: Callable[
        ["Order", List["OrderLine"], List["OrderLine"]], List["OrderLine"]
    ]

    #  Calculate checkout line total.
    #
    #  Overwrite this method if you need to apply specific logic for the calculation
    #  of a checkout line total. Return TaxedMoney.
    calculate_checkout_line_total: Callable[
        [
            "CheckoutInfo",
            List["CheckoutLineInfo"],
            "CheckoutLineInfo",
            Union["Address", NoneType],
            Iterable["DiscountInfo"],
            TaxedMoney,
        ],
        TaxedMoney,
    ]

    #  Calculate checkout line unit price.
    calculate_checkout_line_unit_price: Callable[
        [
            "CheckoutInfo",
            List["CheckoutLineInfo"],
            "CheckoutLineInfo",
            Union["Address", NoneType],
            Iterable["DiscountInfo"],
            Any,
        ],
        TaxedMoney,
    ]

    #  Calculate the shipping costs for checkout.
    #
    #  Overwrite this method if you need to apply specific logic for the calculation
    #  of shipping costs. Return TaxedMoney.
    calculate_checkout_shipping: Callable[
        [
            "CheckoutInfo",
            List["CheckoutLineInfo"],
            Union["Address", NoneType],
            List["DiscountInfo"],
            TaxedMoney,
        ],
        TaxedMoney,
    ]

    #  Calculate the total for checkout.
    #
    #  Overwrite this method if you need to apply specific logic for the calculation
    #  of a checkout total. Return TaxedMoney.
    calculate_checkout_total: Callable[
        [
            "CheckoutInfo",
            List["CheckoutLineInfo"],
            Union["Address", NoneType],
            List["DiscountInfo"],
            TaxedMoney,
        ],
        TaxedMoney,
    ]

    #  Calculate order line total.
    #
    #  Overwrite this method if you need to apply specific logic for the calculation
    #  of a order line total. Return TaxedMoney.
    calculate_order_line_total: Callable[
        ["Order", "OrderLine", "ProductVariant", "Product", TaxedMoney], TaxedMoney
    ]

    #  Calculate order line unit price.
    #
    #  Update order line unit price in the order in case of changes in draft order.
    #  Return TaxedMoney.
    #  Overwrite this method if you need to apply specific logic for the calculation
    #  of an order line unit price.
    calculate_order_line_unit: Callable[
        ["Order", "OrderLine", "ProductVariant", "Product", TaxedMoney], TaxedMoney
    ]

    #  Calculate the shipping costs for the order.
    #
    #  Update shipping costs in the order in case of changes in shipping address or
    #  changes in draft order. Return TaxedMoney.
    calculate_order_shipping: Callable[["Order", TaxedMoney], TaxedMoney]

    #  Calculate order total.
    #
    #  Overwrite this method if you need to apply specific logic for the calculation
    #  of a order total. Return TaxedMoney.
    calculate_order_total: Callable[
        ["Order", List["OrderLine"], TaxedMoney], TaxedMoney
    ]

    capture_payment: Callable[["PaymentData", Any], GatewayResponse]

    #  Trigger when category is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a category is
    #  created.
    category_created: Callable[["Category", None], None]

    #  Trigger when category is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a category is
    #  deleted.
    category_deleted: Callable[["Category", None], None]

    #  Trigger when category is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a category is
    #  updated.
    category_updated: Callable[["Category", None], None]

    #  Trigger when channel is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a channel is
    #  created.
    channel_created: Callable[["Channel", None], None]

    #  Trigger when channel is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a channel is
    #  deleted.
    channel_deleted: Callable[["Channel", None], None]

    #  Trigger when channel is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a channel is
    #  updated.
    channel_updated: Callable[["Channel", None], None]

    #  Trigger when channel status is changed.
    #
    #  Overwrite this method if you need to trigger specific logic after a channel
    #  status is changed.
    channel_status_changed: Callable[["Channel", None], None]

    change_user_address: Callable[
        ["Address", Union[str, NoneType], Union["User", NoneType], "Address"], "Address"
    ]

    #  Retrieves the balance remaining on a shopper's gift card
    check_payment_balance: Callable[[dict, str], dict]

    #  Trigger when checkout is created.
    #
    #  Overwrite this method if you need to trigger specific logic when a checkout is
    #  created.
    checkout_created: Callable[["Checkout", Any], Any]

    #  Trigger when checkout is updated.
    #
    #  Overwrite this method if you need to trigger specific logic when a checkout is
    #  updated.
    checkout_updated: Callable[["Checkout", Any], Any]

    #  Trigger when checkout metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic when a checkout
    #  metadata is updated.
    checkout_metadata_updated: Callable[["Checkout", Any], Any]

    #  Trigger when collection is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a collection is
    #  created.
    collection_created: Callable[["Collection", Any], Any]

    #  Trigger when collection is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a collection is
    #  deleted.
    collection_deleted: Callable[["Collection", Any], Any]

    #  Trigger when collection is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a collection is
    #  updated.
    collection_updated: Callable[["Collection", Any], Any]

    #  Trigger when collection metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a collection
    #  metadata is updated.
    collection_metadata_updated: Callable[["Collection", Any], Any]

    confirm_payment: Callable[["PaymentData", Any], GatewayResponse]

    #  Trigger when user is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a user is
    #  created.
    customer_created: Callable[["User", Any], Any]

    #  Trigger when user is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a user is
    #  deleted.
    customer_deleted: Callable[["User", Any], Any]

    #  Trigger when user is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a user is
    #  updated.
    customer_updated: Callable[["User", Any], Any]

    #  Trigger when user metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a user
    #  metadata is updated.
    customer_metadata_updated: Callable[["User", Any], Any]

    #  Handle authentication request.
    #
    #  Overwrite this method if the plugin handles authentication flow.
    external_authentication_url: Callable[[dict, WSGIRequest, dict], dict]

    #  Handle logout request.
    #
    #  Overwrite this method if the plugin handles logout flow.
    external_logout: Callable[[dict, WSGIRequest, dict], Any]

    #  Handle authentication request responsible for obtaining access tokens.
    #
    #  Overwrite this method if the plugin handles authentication flow.
    external_obtain_access_tokens: Callable[
        [dict, WSGIRequest, ExternalAccessTokens], ExternalAccessTokens
    ]

    #  Handle authentication refresh request.
    #
    #  Overwrite this method if the plugin handles authentication flow and supports
    #  refreshing the access.
    external_refresh: Callable[
        [dict, WSGIRequest, ExternalAccessTokens], ExternalAccessTokens
    ]

    #  Verify the provided authentication data.
    #
    #  Overwrite this method if the plugin should validate the authentication data.
    external_verify: Callable[
        [dict, WSGIRequest, Tuple[Union["User", NoneType], dict]],
        Tuple[Union["User", NoneType], dict],
    ]

    #  Triggered when ShopFetchTaxRates mutation is called.
    fetch_taxes_data: Callable[[Any], Any]

    #  Trigger when fulfillment is created.
    #
    #  Overwrite this method if you need to trigger specific logic when a fulfillment is
    #  created.
    fulfillment_created: Callable[["Fulfillment", Any], Any]

    #  Trigger when fulfillment is cancelled.
    #
    #  Overwrite this method if you need to trigger specific logic when a fulfillment is
    #  cancelled.
    fulfillment_canceled: Callable[["Fulfillment", Any], Any]

    #  Trigger when fulfillment is approved.
    #
    #  Overwrite this method if you need to trigger specific logic when a fulfillment is
    #  approved.
    fulfillment_approved: Callable[["Fulfillment", Any], Any]

    #  Trigger when fulfillment metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic when a fulfillment
    #  metadata is updated.
    fulfillment_metadata_updated: Callable[["Fulfillment", Any], Any]

    get_checkout_line_tax_rate: Callable[
        [
            "CheckoutInfo",
            List["CheckoutLineInfo"],
            "CheckoutLineInfo",
            Union["Address", NoneType],
            Iterable["DiscountInfo"],
            Decimal,
        ],
        Decimal,
    ]

    get_checkout_shipping_tax_rate: Callable[
        [
            "CheckoutInfo",
            Iterable["CheckoutLineInfo"],
            Union["Address", NoneType],
            Iterable["DiscountInfo"],
            Any,
        ],
        Any,
    ]

    get_taxes_for_checkout: Callable[
        ["CheckoutInfo", Iterable["CheckoutLineInfo"], Any],
        Optional["TaxData"],
    ]

    get_taxes_for_order: Callable[["Order", Any], Optional["TaxData"]]

    get_client_token: Callable[[Any, Any], Any]

    get_order_line_tax_rate: Callable[
        ["Order", "Product", "ProductVariant", Union["Address", NoneType], Decimal],
        Decimal,
    ]

    get_order_shipping_tax_rate: Callable[["Order", Any], Any]
    get_payment_config: Callable[[Any], Any]

    get_shipping_methods_for_checkout: Callable[
        ["Checkout", Any], List["ShippingMethodData"]
    ]

    get_supported_currencies: Callable[[Any], Any]

    #  Return tax code from object meta.
    get_tax_code_from_object_meta: Callable[
        [Union["Product", "ProductType"], "TaxType"], "TaxType"
    ]

    #  Return tax rate percentage value for a given tax rate type in a country.
    #
    #  It is used only by the old storefront.
    get_tax_rate_percentage_value: Callable[
        [Union["Product", "ProductType"], Country, Any], Decimal
    ]

    #  Return list of all tax categories.
    #
    #  The returned list will be used to provide staff users with the possibility to
    #  assign tax categories to a product. It can be used by tax plugins to properly
    #  calculate taxes for products.
    #  Overwrite this method in case your plugin provides a list of tax categories.
    get_tax_rate_type_choices: Callable[[List["TaxType"]], List["TaxType"]]

    #  Trigger when gift card is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a gift card is
    #  created.
    gift_card_created: Callable[["GiftCard", None], None]

    #  Trigger when gift card is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a gift card is
    #  deleted.
    gift_card_deleted: Callable[["GiftCard", None], None]

    #  Trigger when gift card is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a gift card is
    #  updated.
    gift_card_updated: Callable[["GiftCard", None], None]

    #  Trigger when gift card metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a gift card
    #  metadata is updated.
    gift_card_metadata_updated: Callable[["GiftCard", None], None]

    #  Trigger when gift card status is changed.
    #
    #  Overwrite this method if you need to trigger specific logic after a gift card
    #  status is changed.
    gift_card_status_changed: Callable[["GiftCard", None], None]

    initialize_payment: Callable[[dict], InitializedPaymentResponse]

    #  Trigger before invoice is deleted.
    #
    #  Perform any extra logic before the invoice gets deleted.
    #  Note there is no need to run invoice.delete() as it will happen in mutation.
    invoice_delete: Callable[["Invoice", Any], Any]

    #  Trigger when invoice creation starts.
    #  May return Invoice object.
    #  Overwrite to create invoice with proper data, call invoice.update_invoice.
    invoice_request: Callable[
        ["Order", "Invoice", Union[str, NoneType], Any], Optional["Invoice"]
    ]

    #  Trigger after invoice is sent.
    invoice_sent: Callable[["Invoice", str, Any], Any]

    list_payment_sources: Callable[[str, Any], List["CustomerSource"]]

    #  Trigger when menu is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a menu is
    #  created.
    menu_created: Callable[["Menu", None], None]

    #  Trigger when menu is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a menu is
    #  deleted.
    menu_deleted: Callable[["Menu", None], None]

    #  Trigger when menu is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a menu is
    #  updated.
    menu_updated: Callable[["Menu", None], None]

    #  Trigger when menu item is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a menu item is
    #  created.
    menu_item_created: Callable[["MenuItem", None], None]

    #  Trigger when menu item is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a menu item is
    #  deleted.
    menu_item_deleted: Callable[["MenuItem", None], None]

    #  Trigger when menu item is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a menu item is
    #  updated.
    menu_item_updated: Callable[["MenuItem", None], None]

    #  Handle notification request.
    #
    #  Overwrite this method if the plugin is responsible for sending notifications.
    notify: Callable[["NotifyEventType", dict, Any], Any]

    #  Trigger when order is cancelled.
    #
    #  Overwrite this method if you need to trigger specific logic when an order is
    #  canceled.
    order_cancelled: Callable[["Order", Any], Any]

    #  Trigger when order is confirmed by staff.
    #
    #  Overwrite this method if you need to trigger specific logic after an order is
    #  confirmed.
    order_confirmed: Callable[["Order", Any], Any]

    #  Trigger when order is created.
    #
    #  Overwrite this method if you need to trigger specific logic after an order is
    #  created.
    order_created: Callable[["Order", Any], Any]

    #  Trigger when order is fulfilled.
    #
    #  Overwrite this method if you need to trigger specific logic when an order is
    #  fulfilled.
    order_fulfilled: Callable[["Order", Any], Any]

    #  Trigger when order is fully paid.
    #
    #  Overwrite this method if you need to trigger specific logic when an order is
    #  fully paid.
    order_fully_paid: Callable[["Order", Any], Any]

    #  Trigger when order is updated.
    #
    #  Overwrite this method if you need to trigger specific logic when an order is
    #  changed.
    order_updated: Callable[["Order", Any], Any]

    #  Trigger when order metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic when an order
    #  metadata is changed.
    order_metadata_updated: Callable[["Order", Any], Any]

    #  Trigger when page is created.
    #
    #  Overwrite this method if you need to trigger specific logic when a page is
    #  created.
    page_created: Callable[["Page", Any], Any]

    #  Trigger when page is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic when a page is
    #  deleted.
    page_deleted: Callable[["Page", Any], Any]

    #  Trigger when page is updated.
    #
    #  Overwrite this method if you need to trigger specific logic when a page is
    #  updated.
    page_updated: Callable[["Page", Any], Any]

    #  Trigger when page type is created.
    #
    #  Overwrite this method if you need to trigger specific logic when a page type is
    #  created.
    page_type_created: Callable[["PageType", Any], Any]

    #  Trigger when page type is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic when a page type is
    #  deleted.
    page_type_deleted: Callable[["PageType", Any], Any]

    #  Trigger when page type is updated.
    #
    #  Overwrite this method if you need to trigger specific logic when a page type is
    #  updated.
    page_type_updated: Callable[["PageType", Any], Any]

    #  Trigger when permission group is created.
    #
    #  Overwrite this method if you need to trigger specific logic when a permission
    #  group is created.
    permission_group_created: Callable[["Group", Any], Any]

    #  Trigger when permission group type is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic when a permission
    #  group is deleted.
    permission_group_deleted: Callable[["Group", Any], Any]

    #  Trigger when permission group is updated.
    #
    #  Overwrite this method if you need to trigger specific logic when a permission
    #  group is updated.
    permission_group_updated: Callable[["Group", Any], Any]

    #  Trigger directly before order creation.
    #
    #  Overwrite this method if you need to trigger specific logic before an order is
    #  created.
    preprocess_order_creation: Callable[
        [
            "CheckoutInfo",
            List["DiscountInfo"],
            Union[Iterable["CheckoutLineInfo"], NoneType],
            Any,
        ],
        Any,
    ]

    process_payment: Callable[["PaymentData", Any], Any]

    transaction_action_request: Callable[["TransactionActionData", None], None]

    #  Trigger when transaction item metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic when a transaction
    #  item metadata is updated.
    transaction_item_metadata_updated: Callable[["TransactionItem", Any], Any]

    #  Trigger when product is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a product is
    #  created.
    product_created: Callable[["Product", Any], Any]

    #  Trigger when product is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a product is
    #  deleted.
    product_deleted: Callable[["Product", List[int], Any], Any]

    #  Trigger when product is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a product is
    #  updated.
    product_updated: Callable[["Product", Any], Any]

    #  Trigger when product metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a product
    #  metadata is updated.
    product_metadata_updated: Callable[["Product", Any], Any]

    #  Trigger when product variant is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a product
    #  variant is created.
    product_variant_created: Callable[["ProductVariant", Any], Any]

    #  Trigger when product variant is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a product
    #  variant is deleted.
    product_variant_deleted: Callable[["ProductVariant", Any], Any]

    #  Trigger when product variant is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a product
    #  variant is updated.
    product_variant_updated: Callable[["ProductVariant", Any], Any]

    #  Trigger when product variant metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a product
    #  variant metadata is updated.
    product_variant_metadata_updated: Callable[["ProductVariant", Any], Any]

    refund_payment: Callable[["PaymentData", Any], GatewayResponse]

    #  Trigger when sale is created.
    #
    # Overwrite this method if you need to trigger specific logic after sale is created.
    sale_created: Callable[["Sale", DefaultDict[str, Set[str]], Any], Any]

    #  Trigger when sale is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after sale is deleted.
    sale_deleted: Callable[["Sale", DefaultDict[str, Set[str]], Any], Any]

    #  Trigger when sale is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after sale is updated.
    sale_updated: Callable[
        ["Sale", DefaultDict[str, Set[str]], DefaultDict[str, Set[str]], Any], Any
    ]

    #  Trigger when shipping price is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a shipping
    #  price is created.
    shipping_price_created: Callable[["ShippingMethod", None], None]

    #  Trigger when shipping price is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a shipping
    #  price is deleted.
    shipping_price_deleted: Callable[["ShippingMethod", None], None]

    #  Trigger when shipping price is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a shipping
    #  price is updated.
    shipping_price_updated: Callable[["ShippingMethod", None], None]

    #  Trigger when shipping zone is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a shipping zone
    #  is created.
    shipping_zone_created: Callable[["ShippingZone", None], None]

    #  Trigger when shipping zone is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a shipping zone
    #  is deleted.
    shipping_zone_deleted: Callable[["ShippingZone", None], None]

    #  Trigger when shipping zone is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a shipping zone
    #  is updated.
    shipping_zone_updated: Callable[["ShippingZone", None], None]

    #  Trigger when shipping zone metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a shipping zone
    #  metadata is updated.
    shipping_zone_metadata_updated: Callable[["ShippingZone", None], None]

    #  Define if storefront should add info about taxes to the price.
    #
    #  It is used only by the old storefront. The returned value determines if
    #  storefront should append info to the price about "including/excluding X% VAT".
    show_taxes_on_storefront: Callable[[bool], bool]

    #  Trigger when staff user is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a staff user is
    #  created.
    staff_created: Callable[["User", Any], Any]

    #  Trigger when staff user is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a staff user is
    #  updated.
    staff_updated: Callable[["User", Any], Any]

    #  Trigger when staff user is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a staff user is
    #  deleted.
    staff_deleted: Callable[["User", Any], Any]

    #  Trigger when tracking number is updated.
    tracking_number_updated: Callable[["Fulfillment", Any], Any]

    void_payment: Callable[["PaymentData", Any], GatewayResponse]

    #  Trigger when warehouse is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a warehouse is
    #  created.
    warehouse_created: Callable[["Warehouse", None], None]

    #  Trigger when warehouse is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a warehouse is
    #  deleted.
    warehouse_deleted: Callable[["Warehouse", None], None]

    #  Trigger when warehouse is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a warehouse is
    #  updated.
    warehouse_updated: Callable[["Warehouse", None], None]

    #  Trigger when warehouse metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a warehouse
    #  metadata is updated.
    warehouse_metadata_updated: Callable[["Warehouse", None], None]

    #  Trigger when voucher is created.
    #
    #  Overwrite this method if you need to trigger specific logic after a voucher is
    #  created.
    voucher_created: Callable[["Voucher", None], None]

    #  Trigger when voucher is deleted.
    #
    #  Overwrite this method if you need to trigger specific logic after a voucher is
    #  deleted.
    voucher_deleted: Callable[["Voucher", None], None]

    #  Trigger when voucher is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a voucher is
    #  updated.
    voucher_updated: Callable[["Voucher", None], None]

    #  Trigger when voucher metadata is updated.
    #
    #  Overwrite this method if you need to trigger specific logic after a voucher
    #  metadata is updated.
    voucher_metadata_updated: Callable[["Voucher", None], None]

    #  Handle received http request.
    #
    #  Overwrite this method if the plugin expects the incoming requests.
    webhook: Callable[[WSGIRequest, str, Any], HttpResponse]

    # Triggers retry mechanism for event delivery
    event_delivery_retry: Callable[["EventDelivery", Any], EventDelivery]

    # Invoked before each mutation is executed
    #
    # This allows to trigger specific logic before the mutation is executed
    # but only once the permissions are checked.
    #
    # Returns one of:
    #     - null if the execution shall continue
    #     - an execution result
    #     - graphql.GraphQLError
    perform_mutation: Callable[
        [
            Optional[Union[ExecutionResult, GraphQLError]],  # previous value
            Mutation,  # mutation class
            Any,  # mutation root
            ResolveInfo,  # resolve info
            dict,  # mutation data
        ],
        Optional[Union[ExecutionResult, GraphQLError]],
    ]

    def token_is_required_as_payment_input(self, previous_value):
        return previous_value

    def get_payment_gateways(
        self, currency: Optional[str], checkout: Optional["Checkout"], previous_value
    ) -> List["PaymentGateway"]:
        payment_config = (
            self.get_payment_config(previous_value)  # type: ignore
            if hasattr(self, "get_payment_config")
            else []
        )
        currencies = (
            self.get_supported_currencies(previous_value=[])  # type: ignore
            if hasattr(self, "get_supported_currencies")
            else []
        )
        if currency and currency not in currencies:
            return []
        gateway = PaymentGateway(
            id=self.PLUGIN_ID,
            name=self.PLUGIN_NAME,
            config=payment_config,
            currencies=currencies,
        )
        return [gateway]

    @classmethod
    def _update_config_items(
        cls, configuration_to_update: List[dict], current_config: List[dict]
    ):
        config_structure: dict = (
            cls.CONFIG_STRUCTURE if cls.CONFIG_STRUCTURE is not None else {}
        )
        for config_item in current_config:
            for config_item_to_update in configuration_to_update:
                config_item_name = config_item_to_update.get("name")
                if config_item["name"] == config_item_name:
                    new_value = config_item_to_update.get("value")
                    item_type = config_structure.get(config_item_name, {}).get("type")
                    if (
                        item_type == ConfigurationTypeField.BOOLEAN
                        and new_value
                        and not isinstance(new_value, bool)
                    ):
                        new_value = new_value.lower() == "true"
                    if item_type == ConfigurationTypeField.OUTPUT:
                        # OUTPUT field is read only. No need to update it
                        continue
                    config_item.update([("value", new_value)])

        # Get new keys that don't exist in current_config and extend it.
        current_config_keys = set(c_field["name"] for c_field in current_config)
        configuration_to_update_dict = {
            c_field["name"]: c_field["value"] for c_field in configuration_to_update
        }
        missing_keys = set(configuration_to_update_dict.keys()) - current_config_keys
        for missing_key in missing_keys:
            if not config_structure.get(missing_key):
                continue
            current_config.append(
                {
                    "name": missing_key,
                    "value": configuration_to_update_dict[missing_key],
                }
            )

    @classmethod
    def validate_plugin_configuration(
        cls, plugin_configuration: "PluginConfiguration", **kwargs
    ):
        """Validate if provided configuration is correct.

        Raise django.core.exceptions.ValidationError otherwise.
        """
        return

    @classmethod
    def pre_save_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):
        """Trigger before plugin configuration will be saved.

        Overwrite this method if you need to trigger specific logic before saving a
        plugin configuration.
        """

    @classmethod
    def save_plugin_configuration(
        cls, plugin_configuration: "PluginConfiguration", cleaned_data
    ):
        current_config = plugin_configuration.configuration
        configuration_to_update = cleaned_data.get("configuration")
        if configuration_to_update:
            cls._update_config_items(configuration_to_update, current_config)

        if "active" in cleaned_data:
            plugin_configuration.active = cleaned_data["active"]

        cls.validate_plugin_configuration(plugin_configuration)
        cls.pre_save_plugin_configuration(plugin_configuration)
        plugin_configuration.save()

        if plugin_configuration.configuration:
            # Let's add a translated descriptions and labels
            cls._append_config_structure(plugin_configuration.configuration)
        return plugin_configuration

    @classmethod
    def _append_config_structure(cls, configuration: PluginConfigurationType):
        """Append configuration structure to config from the database.

        Database stores "key: value" pairs, the definition of fields should be declared
        inside of the plugin. Based on this, the plugin will generate a structure of
        configuration with current values and provide access to it via API.
        """
        config_structure = getattr(cls, "CONFIG_STRUCTURE") or {}
        fields_without_structure = []
        for configuration_field in configuration:

            structure_to_add = config_structure.get(configuration_field.get("name"))
            if structure_to_add:
                configuration_field.update(structure_to_add)
            else:
                fields_without_structure.append(configuration_field)

        if fields_without_structure:
            [
                configuration.remove(field)  # type: ignore
                for field in fields_without_structure
            ]

    @classmethod
    def _update_configuration_structure(cls, configuration: PluginConfigurationType):
        updated_configuration = []
        config_structure = getattr(cls, "CONFIG_STRUCTURE") or {}
        desired_config_keys = set(config_structure.keys())
        for config_field in configuration:
            if config_field["name"] not in desired_config_keys:
                continue
            updated_configuration.append(copy(config_field))

        configured_keys = set(d["name"] for d in updated_configuration)
        missing_keys = desired_config_keys - configured_keys

        if not missing_keys:
            return updated_configuration

        default_config = cls.DEFAULT_CONFIGURATION
        if not default_config:
            return updated_configuration

        update_values = [copy(k) for k in default_config if k["name"] in missing_keys]
        if update_values:
            updated_configuration.extend(update_values)
        return updated_configuration

    @classmethod
    def get_default_active(cls):
        return cls.DEFAULT_ACTIVE

    def get_plugin_configuration(
        self, configuration: PluginConfigurationType
    ) -> PluginConfigurationType:
        if not configuration:
            configuration = []
        configuration = self._update_configuration_structure(configuration)
        if configuration:
            # Let's add a translated descriptions and labels
            self._append_config_structure(configuration)
        return configuration

    def resolve_plugin_configuration(
        self, request
    ) -> Union[PluginConfigurationType, Promise[PluginConfigurationType]]:
        # Override this function to customize resolving plugin configuration in API.
        return self.configuration

    def is_event_active(self, event: str, channel=Optional[str]):
        return hasattr(self, event)


text:
#include <iostream>
#include <vector>
#include "train.h"
#include"depot.h"
#include <algorithm>

Depot::Depot(int _depotNumber, int _trainsCapacity, int _carriagesCapacity)
:m_number(_depotNumber), m_trainsCapacity(_trainsCapacity), m_carriagesCapacity(_carriagesCapacity){
	incorrectCapacity(m_carriagesCapacity);
	incorrectCapacity(m_trainsCapacity);
	incorrectNumber(_depotNumber);
}

Depot::~Depot()
{
	for (Train *_pTrain : m_Trains)
	{
		delete _pTrain;
	}
	for (Carriage *_pCarriage : m_Carriages)
	{
		delete _pCarriage;
	}
}

int Depot::getNumber()
{
	return m_number;
}

int Depot::getTrainsCapacity() const
{
	return m_trainsCapacity;
}

int Depot::getCarriagesCapacity()const
{
	return m_carriagesCapacity;
}

int Depot::getTrainsCount() const
{
	return m_Trains.size();
}
int Depot::getCarriagesCount() const
{
	return m_Carriages.size();
}

void Depot::isTrainsFullness() const
{
	if (getTrainsCount() + 1 > getTrainsCapacity())
		throw "Depo already full";
}

bool Depot::hasTrain(int _trainPos) const
{
	if (_trainPos != -1)
		return true;
	return false;
}

int  Depot::findTrain(Train &_train) const
{
	for (int i = 0; i < getTrainsCount(); i++)
		if (m_Trains[i]->getNumber() == _train.getNumber())
			return i;
	return -1;
}

int  Depot::findTrain(int _trainNumber) const
{
	for (int i = 0; i < getTrainsCount(); i++)
		if (m_Trains[i]->getNumber() == _trainNumber)
			return i;
	return -1;
}

void Depot::addTrain(Train * _pTrain)
{
	/*int _trainPos = findTrain(_trainNumber);
	isTrainNotExist( _trainPos);*/
	isTrainsFullness();

	m_Trains.push_back(_pTrain);
}

void Depot::addTrain(int _trainNumber)
{
	/*int _trainPos = findTrain(_trainNumber);
	isTrainNotExist( _trainPos);*/
	isTrainsFullness();
	Train * _pTrain = new Train(_trainNumber);
	m_Trains.push_back(_pTrain);
}

void Depot::addTrain(int _trainNumber, int _maxCarriages)
{
	/*int _trainPos = findTrain(_trainNumber);
	isTrainNotExist(_trainPos);*/
	isTrainsFullness();
	Train * _pTrain = new Train(_trainNumber, _maxCarriages);
	m_Trains.push_back(_pTrain);
}

void Depot::removeTrain(Train &_train)
{
	int _pos = findTrain(_train);
	isTrainExist(_pos);
	m_Trains.erase(m_Trains.begin() + _pos);
	delete m_Trains[_pos];
}

void Depot::removeTrain(int _trainPos)
{
	//delete m_Trains[_trainPos];
	m_Trains.erase(m_Trains.begin() + _trainPos);
}

Train * Depot::getTrain(int _pos) const
{

	isTrainExist( _pos);

	return m_Trains.at(_pos);
}

int Depot::getNCarriages(int _trainNumber)
{
	int _pos = findTrain(_trainNumber);
	isTrainExist(_pos);
	return m_Trains[_pos]->getNCarriages();
}

void Depot::isCarriagesFullness() const
{
	if (getCarriagesCount() + 1 > getCarriagesCapacity())
		throw "Depo already full";
}

bool Depot::hasCarriage(int _carriageNumber) const
{
	if (findCarriage(_carriageNumber) != -1)
		return true;
	else return false;
}

int Depot::findCarriage(int _carriageNumber)const
{
	for (int i = 0; i < getCarriagesCount(); i++)
		if (m_Carriages[i]->getCarriageNumber() == _carriageNumber)
			return i;
	return -1;
}

void Depot::addCarriage(int _carriageNumber, int _capacity)
{
	if (hasCarriage(_carriageNumber))
	isCarriagesFullness();
	Carriage * _pCarriage = new Carriage(_carriageNumber, _capacity);
	m_Carriages.push_back(_pCarriage);
}

void Depot::addCarriage(int _carriageNumber)
{
	if (hasCarriage(_carriageNumber))
		throw "Carriage is already exist";
	isCarriagesFullness();
	Carriage * _pCarriage = new Carriage(_carriageNumber);
	m_Carriages.push_back(_pCarriage);
}

void Depot::removeCarriage(int _carriageNumber)
{
	int _pos = findCarriage(_carriageNumber);
	//isCarriageExist(_pos);
	delete m_Carriages[_pos];
	m_Carriages.erase(m_Carriages.begin() + _pos);
}

Carriage * Depot::getCarriage(int _carriageNumber) const
{
	nonpositiveNumber(_carriageNumber);
	int _pos = findCarriage(_carriageNumber);
	isCarriageExist( _pos);
	return m_Carriages.at(_pos);
}

void Depot::areHasCarriagesIntoTrain(int _trainNumber) const
{
	int _trainPos = findTrain(_trainNumber);
	isTrainExist(_trainPos);
	m_Trains[_trainPos]->hasCarriages();
}

//void Depot::hasHumans(int _trainPos) const
//{
//	isTrainExist(_trainPos);
//	if (!m_Trains[_trainPos]->isEmpty())
//		throw "Someone already at the train";
//}

void Depot::findHuman(std::string _humanName) const//íå äîëæíî á³òü â äåïî
{
	for (int i = 0; i < getTrainsCount(); i++)
	{
		if (m_Trains[i]->findHuman(_humanName) != -1)
		throw "Human already at the train";
	}
}

void Depot::addCarriageToTrain(int _trainNumber, int _carriageNumber)
{
	int _carriagePos = findCarriage(_carriageNumber);
	isCarriageExist(_carriagePos);
	int _trainPos = findTrain(_trainNumber);
	isTrainExist(_trainPos);

	m_Trains[_trainPos]->addCarriage(m_Carriages[_carriagePos]);
	m_Carriages.erase(m_Carriages.begin() + _carriagePos);
}

void Depot::unfastenCarriage(int _trainNumber, int _carriageNumber)
{
	int _trainPos = findTrain(_trainNumber);
//	isTrainExist( _trainPos);
	int _carriagePos=m_Trains[_trainPos]->findCarriage(_carriageNumber);
	if (_carriagePos == -1)
		throw "Carriage is not on this train";
	m_Carriages.push_back(m_Trains[_trainPos]->getCarriage(_carriagePos));
	m_Trains[_trainPos]->removeCarriage(_carriageNumber);
}


text:
Classifying between positive and negative images, using the evoked *valence* in the Emotion6 dataset.

## Tasks

- [x] Generate positive(+1)/negative(0) labels for the Emotion6 database using the valence score provided (see [setup]())
- [x] _Fine-tune_ the AlexNet model using the Emotion6 positive/negative labels.
- [x] _Fine-tune_ the Places CNN model using the Emotion6 positive/negative labels.
- [x] Compose a mosaic image given the classification results with the different models (e.g. green border for images classified as positive, red for negative).
- [x] Change the learning rate and decay of the _new_ layer in the places net, so that the weights of this layer during finetuning change faster than the pretrained layers.
- [ ] Visualize the response of the hidden layers to the test images with the Places net before and after the finetuning, to compare responses.
- [ ] Repeat the fine tuning with a single output of the net. Instead of using a Softmax-based Loss function, try a Sigmoid-based loss-layer.
- [x] Draw a representation of the learning curve (accuracy v. number of iterations).
- [ ] Train regression model using original valence annotations.

### e1. Fine-tuning the AlexNet model to classify images as _emotionally_ positive/negative:

After generating the positive/negative labels by thresholding the valence ground-truth scores, the AlexNet model weights are used as the starting point for training a 2 class classifier.

Finetuning existing nets is relatively easy with Caffe. We need the following files:

1. A solver prototxt file to tell Caffe how do we want to train the net (see the [Caffe docs](https://github.com/BVLC/caffe/wiki/Solver-Prototxt) for more info). We will name our solver `e1.solver.prototxt`. If you modify an existing solver, make sure that it points to the right `net` file (see below):
    ```
    net: "e1.train_val.prototxt"
    ```
2. A train prototxt file to define the structure of the net. We will use a modified version of the Model Zoo's AlexNet model (`$CAFFE_ROOT/models/bvlc_alexnet/train_val.prototxt`). We copy this model to `e1.train_val.prototxt` and make two changes:
    - The data layers (at the top of the file) are modified to use the Emotion6 image lists:

    ```
    layer {
      name: "data"
      type: "ImageData" <<< The data layer consists of image files
      top: "data"
      top: "label"
      include {
        phase: TRAIN
      }

      image_data_param {
        source: "em6_posneg_train.txt" <<< New source of images
        batch_size: 50
        new_height: 256
        new_width: 256
      }
    }
    ```

    - The output layer (`fc8`) is modified: the number of outputs is changed to 2, corresponding to our positive/negative classes:

    ```
        layer {
          name: "fc8_emotion6" <<< Changing the name of the layer is important!
          type: "InnerProduct"
          bottom: "fc7"
          top: "fc8_emotion6"
          ...
          inner_product_param {
            num_output: 2 # <<< The number of outputs has changed
            ...
          }
        }
    ```

    Also, notice that the name of the layer has changed to `fc8_emotion6`. This is important as it will tell Caffe this is a new layer.

    _This 2-output scheme may not be the best approach, as the two classes are clearly disjoint. We'll use a 1-output layer in upcoming tests (notice this will require a Sigmoid-based Loss instead of a Softmax-based loss)_
3. The pre-trained AlexNet model (`$CAFFE_ROOT/models/bvlc_alexnet/bvlc_alexnet.caffemodel`), which is a *binary* file containing weights for our net.

##### Fine tuning procedure

Once we have our files, we simply run the `caffe train` command, using our solver file and the option `-weights`, which tells Caffe to start training from the weights of AlexNet:

    caffe train -solver e1.solver.prototxt -weights $CAFFE_ROOT/models/bvlc_alexnet/bvlc_alexnet.caffemodel -gpu 0 &>e1.log

The last part (`&>e1.log`) will redirect the training log messages to our log file.

_Finetuning magic: After running this command, Caffe will detect the correspondence of the layers in `e1.train_val.prototxt` file and the existing layers in the binary model (`bvlc_alexnet.caffemodel`). However, as the `fc8_emotion6` layer is not present in the original model, Caffe will add this layer to our new model and initialize its weights according to our net file._

    ...
    I0617 11:10:50.648298 30653 caffe.cpp:129] Finetuning from /<path>/bvlc_alexnet.caffemodel
    ...
    I0617 11:11:07.893702 30653 net.cpp:752] Ignoring source layer fc8

### e2. Fine-tuning the placesCNN model to classify images as _emotionally_ positive/negative (same lr weights in all layers):

Similarly to the previous experiment, this one tries to _update_ a pretrained model to cope with the same 2-class classification problem. The structure of the solver and the required files is very similar, with the following considerations:

- The places CNN model has been downloaded from [here](http://places.csail.mit.edu/model/placesCNN_upgraded.tar.gz) and the files have been saved in `$CAFFE_ROOT/extra_models/placesCNN_upgraded`.
- The net file (`e2.train_val.prototxt`) has been modified as in the previous example to use the Emotion6 images as input. Additionally, the prototxt has been updated to follow the current Caffe data format, by using the `$CAFFE_ROOT/build/tools/upgrade_net_proto_text` binary.
- **learning rate**: to analyze the effect of using different fine tuning strategies, the learning rate of the _new_ layer has been kept unaltered:

```
layer {
  name: "fc8_emotion6"
  type: "InnerProduct"
  bottom: "fc7"
  top: "fc8_emotion6"
  param {
    lr_mult: 1 << same weights as other layers'
    decay_mult: 1
  }
  param {
    lr_mult: 2 << same weights as other layers'
    decay_mult: 0
  }
  inner_product_param {
    num_output: 2
    ...
  }
}

```

### e3. Fine-tuning the placesCNN model to classify images as _emotionally_ positive/negative (higher lr in new layer):

This test repeats the **e2** experiment with a higher learning rate in the new layer (`fc8_emotion6`) and compares the achieved results with the results obtained in the previous case. To do so, we repeat fine tuning with a 10x increase of the -relative- learning rate weights of this last layer:

```
layer {
  name: "fc8_emotion6"
  type: "InnerProduct"
  bottom: "fc7"
  top: "fc8_emotion6"
  param {
    lr_mult: 10 << higher weights than pretrained layers'
    decay_mult: 1
  }
  param {
    lr_mult: 20 << higher weights than pretrained layers'
    decay_mult: 0
  }
  inner_product_param {
    num_output: 2
    ...
  }
}

```

### e4. Fine-tuning of the placesCNN model for classification with 1-output net

_The `lr_mult` values in the `fc8_emotion` layer will be the same as in `e2`_

Changing the output layer to provide one single output value implies that we have to use a different `loss` layer in training (a Sigmoid-based loss function). We should obtain the same accuracy as in e2.

_Softmax regression is actually a generalization of logistic regression. More info on the relationship between Softmax Regression and Logistic Regression [here](http://ufldl.stanford.edu/tutorial/supervised/SoftmaxRegression/)_

### Classification results (e1, e2, e3)

![Accuracy](e1_e2_e3.png)

### e5. Finetuning the placesCNN model for regression using the original Emotion6 valence scores


text:
import upperFirst from 'lodash/upperFirst';
export default function (cards, playerClass) {
  return cards.filter(card => card.playerClass === upperFirst(playerClass) || card.playerClass === "Neutral");
}


text:
Tournament Products

    {% for tournament in tournament_list %}

{{ tournament.tournament.title }} - ID:{{ tournament.price }}

    {% empty %}

No products are available

    {% endfor %}


text:
CREATE SCHEMA IF NOT EXISTS __audit;

CREATE OR REPLACE FUNCTION __audit.if_modified_func() RETURNS TRIGGER AS $body$
DECLARE
    excluded_cols TEXT[] = ARRAY[]::TEXT[];
    r record;
    row_data jsonb;
    changed_fields jsonb;

    app_user_id INTEGER;
    app_ip_address inet;
    app_session TEXT;
    client_query TEXT;
    statement_only BOOLEAN = 'f';
BEGIN
    IF TG_WHEN <> 'AFTER' THEN
        RAISE EXCEPTION '__audit.if_modified_func() may only run as an AFTER trigger';
    END IF;

    -- Inject the data from the app settings if they exist.
    -- We need to do this in a transaction, as there doesn't
    -- seem to be any way to test existence.
    BEGIN
      SELECT INTO app_user_id CURRENT_SETTING('app.user');
      SELECT INTO app_ip_address CURRENT_SETTING('app.ip_address');
      SELECT INTO app_session CURRENT_SETTING('app.session');
    EXCEPTION WHEN OTHERS THEN
    END;

    IF TG_ARGV[0]::boolean IS DISTINCT FROM 'f'::boolean THEN
      client_query = current_query();
    ELSE
      client_query = NULL;
    END IF;

    IF TG_ARGV[1] IS NOT NULL THEN
        excluded_cols = TG_ARGV[1]::text[];
    END IF;

    IF (TG_OP = 'UPDATE' AND TG_LEVEL = 'ROW') THEN
        -- Convert our table to a json structure.
        row_data = to_json(OLD.*)::jsonb;
        -- Remove any columns we want to exclude, and then any
        -- columns that still have the same value as before the update.
        changed_fields =  to_json(NEW.*)::jsonb - excluded_cols - row_data;
        IF changed_fields = '{}'::jsonb THEN
            -- All changed fields are ignored. Skip this update.
            RETURN NULL;
        END IF;
    ELSIF (TG_OP = 'DELETE' AND TG_LEVEL = 'ROW') THEN
        row_data = to_json(OLD.*)::jsonb - excluded_cols;
    ELSIF (TG_OP = 'INSERT' AND TG_LEVEL = 'ROW') THEN
        row_data = to_json(NEW.*)::jsonb - excluded_cols;
    ELSIF (TG_LEVEL = 'STATEMENT' AND TG_OP IN ('INSERT','UPDATE','DELETE','TRUNCATE')) THEN
        statement_only = 't';
    ELSE
        RAISE EXCEPTION '[__audit.if_modified_func] - Trigger func added as trigger for unhandled case: %, %',TG_OP, TG_LEVEL;
        RETURN NULL;
    END IF;

    EXECUTE 'SET search_path TO ' || TG_TABLE_SCHEMA::text || ',public,__audit;';

    INSERT INTO "audit_auditlog" (
      "action", "table_name",
      "relid",
      "timestamp", "transaction_id",
      "client_query", "statement_only",
      "row_data", "changed_fields",
      "app_user_id", "app_ip_address"
    ) VALUES (
      substring(TG_OP, 1, 1), TG_TABLE_NAME::text,
      TG_TABLE_NAME::regclass::oid,
      current_timestamp, txid_current(),
      client_query, statement_only,
      row_data, changed_fields,
      app_user_id, app_ip_address
    );
    RETURN NULL;
END;
$body$
LANGUAGE plpgsql
SECURITY DEFINER;

COMMENT ON FUNCTION __audit.if_modified_func() IS $body$
Track changes to a table at the statement and/or row level.

Optional parameters to trigger in CREATE TRIGGER call:

param 0: boolean, whether to log the query text. Default 't'.

param 1: text[], columns to ignore in updates. Default [].

         Updates to ignored cols are omitted from changed_fields.

         Updates with only ignored cols changed are not inserted
         into the audit log.

         Almost all the processing work is still done for updates
         that ignored. If you need to save the load, you need to use
         WHEN clause on the trigger instead.

         No warning or error is issued if ignored_cols contains columns
         that do not exist in the target table. This lets you specify
         a standard set of ignored columns.

There is no parameter to disable logging of values. Add this trigger as
a 'FOR EACH STATEMENT' rather than 'FOR EACH ROW' trigger if you do not
want to log row values.

Note that the user name logged is the login role for the session. The audit trigger
cannot obtain the active role because it is reset by the SECURITY DEFINER invocation
of the audit trigger its self.

If a (temporary, probably) table exists called _app_user, then this will supply
a user_id and ip_address that will be added to the log. This allows for you
to associate events with application level, rather than database users.
$body$;