text:
package org.bowlerframework.extractors

import org.bowlerframework.Request

/**
 * Created by IntelliJ IDEA.
 * User: wfaler
 * Date: 20/04/2011
 * Time: 23:17
 * To change this template use File | Settings | File Templates.
 */

class Default[T](value: T){
  def unapply(request: Request): Option[T] = Option(value)
}


text:
package com.intellij.psi.impl.source.tree.java;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.Constants;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.tree.ChildRole;
import com.intellij.psi.impl.source.tree.CompositeElement;
import com.intellij.psi.impl.source.tree.CompositePsiElement;
import com.intellij.psi.scope.ElementClassFilter;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.scope.processor.FilterScopeProcessor;
import com.intellij.psi.tree.ChildRoleBase;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;

public class PsiSwitchLabelStatementImpl extends CompositePsiElement implements PsiSwitchLabelStatement, Constants {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiSwitchLabelStatementImpl");

  public PsiSwitchLabelStatementImpl() {
    super(SWITCH_LABEL_STATEMENT);
  }

  @Override
  public boolean isDefaultCase() {
    return findChildByRoleAsPsiElement(ChildRole.DEFAULT_KEYWORD) != null;
  }

  @Override
  public PsiExpression getCaseValue() {
    return (PsiExpression)findChildByRoleAsPsiElement(ChildRole.CASE_EXPRESSION);
  }

  @Override
  public PsiSwitchStatement getEnclosingSwitchStatement() {
    final CompositeElement guessedSwitch = getTreeParent().getTreeParent();
    return guessedSwitch != null && guessedSwitch.getElementType() == SWITCH_STATEMENT
           ? (PsiSwitchStatement)SourceTreeToPsiMap.treeElementToPsi(guessedSwitch)
           : null;
  }

  @Override
  public ASTNode findChildByRole(int role) {
    LOG.assertTrue(ChildRole.isUnique(role));
    switch(role){
      default:
        return null;

      case ChildRole.CASE_KEYWORD:
        return findChildByType(CASE_KEYWORD);

      case ChildRole.DEFAULT_KEYWORD:
        return findChildByType(DEFAULT_KEYWORD);

      case ChildRole.CASE_EXPRESSION:
        return findChildByType(EXPRESSION_BIT_SET);

      case ChildRole.COLON:
        return findChildByType(COLON);
    }
  }

  @Override
  public int getChildRole(@NotNull ASTNode child) {
    LOG.assertTrue(child.getTreeParent() == this);
    IElementType i = child.getElementType();
    if (i == CASE_KEYWORD) {
      return ChildRole.CASE_KEYWORD;
    }
    else if (i == DEFAULT_KEYWORD) {
      return ChildRole.DEFAULT_KEYWORD;
    }
    else if (i == COLON) {
      return ChildRole.COLON;
    }
    else {
      if (EXPRESSION_BIT_SET.contains(child.getElementType())) {
        return ChildRole.CASE_EXPRESSION;
      }
      else {
        return ChildRoleBase.NONE;
      }
    }
  }

  @Override
  public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) {
    if (lastParent == null) return true;

    final PsiSwitchStatement switchStatement = getEnclosingSwitchStatement();
    if (switchStatement != null) {
      final PsiExpression expression = switchStatement.getExpression();
      if (expression != null && expression.getType() instanceof PsiClassType) {
        final PsiClass aClass = ((PsiClassType)expression.getType()).resolve();
        if(aClass != null) aClass.processDeclarations(new FilterScopeProcessor(ElementClassFilter.ENUM_CONST, processor), state, this, place);
      }
    }
    return true;
  }

  @Override
  public void accept(@NotNull PsiElementVisitor visitor) {
    if (visitor instanceof JavaElementVisitor) {
      ((JavaElementVisitor)visitor).visitSwitchLabelStatement(this);
    }
    else {
      visitor.visitElement(this);
    }
  }

  public String toString() {
    return "PsiSwitchLabelStatement";
  }
}

redpajama_set_name: RedPajamaGithub


text:
module.exports = require('mixin-class')(
    require('./base'),
    {
        fetch: function(fields) {
            console.log('%c[cascade] %c' + fields.map(function(field) {
                return field.type + '.' + field.category
            }).join (','), 'color: green', 'color: black')

            return this.fetcher.fetch(fields)
        }
    }
);


text:
"""Distributes transpiration based upon a rooting depth and a wilting-point water-potential factor.
"""

import sys, os
sys.path.append(os.path.join(os.environ['ATS_SRC_DIR'], "tools", "evaluator_generator"))
from evaluator_generator import generate_evaluator

deps = [("pressure", "p"),
        ("rooting_depth_fraction", "f_root"),
        ("transpiration", "trans_total")]
params = [("wp_min", "double", "wilting point [Pa]", -2.0e6),]

generate_evaluator("transpiration_distribution", "Flow",
                   "transpiration distribution via rooting depth", "transpiration",
                   deps, params, doc=__doc__)


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Database with allowed values for configuration stored in the $cfg array,
 * used by setup script and user preferences to generate forms.
 *
 * @package PhpMyAdmin
 */

if (!defined('PHPMYADMIN')) {
    exit;
}

/**
 * Value meaning:
 * o array - select field, array contains allowed values
 * o string - type override
 *
 * Use normal array, paths won't be expanded
 */
$cfg_db = array();

$cfg_db['Servers'] = array(
    1 => array(
        'port'         => 'integer',
        'connect_type' => array('tcp', 'socket'),
        'auth_type'    => array('config', 'http', 'signon', 'cookie'),
        'AllowDeny'    => array(
            'order' => array('', 'deny,allow', 'allow,deny', 'explicit')
        ),
        'only_db'      => 'array'
    )
);
$cfg_db['RecodingEngine'] = array('auto', 'iconv', 'recode', 'mb', 'none');
$cfg_db['OBGzip'] = array('auto', true, false);
$cfg_db['MemoryLimit'] = 'short_string';
$cfg_db['NavigationLogoLinkWindow'] = array('main', 'new');
$cfg_db['NavigationTreeDefaultTabTable'] = array(
    'tbl_structure.php', // fields list
    'tbl_sql.php',       // SQL form
    'tbl_select.php',    // search page
    'tbl_change.php',    // insert row page
    'sql.php'            // browse page
);
$cfg_db['NavigationTreeDefaultTabTable2'] = array(
    '', //don't display
    'tbl_structure.php', // fields list
    'tbl_sql.php',       // SQL form
    'tbl_select.php',    // search page
    'tbl_change.php',    // insert row page
    'sql.php'            // browse page
);
$cfg_db['NavigationTreeDbSeparator'] = 'short_string';
$cfg_db['NavigationTreeTableSeparator'] = 'short_string';
$cfg_db['TableNavigationLinksMode'] = array(
    'icons' => __('Icons'),
    'text'  => __('Text'),
    'both'  => __('Both')
);
$cfg_db['MaxRows'] = array(25, 50, 100, 250, 500);
$cfg_db['Order'] = array('ASC', 'DESC', 'SMART');
$cfg_db['RowActionLinks'] = array(
    'none'  => __('Nowhere'),
    'left'  => __('Left'),
    'right' => __('Right'),
    'both'  => __('Both')
);
$cfg_db['TablePrimaryKeyOrder'] = array(
    'NONE'  => __('None'),
    'ASC'   => __('Ascending'),
    'DESC'  => __('Descending')
);
$cfg_db['ProtectBinary'] = array(false, 'blob', 'noblob', 'all');
$cfg_db['CharEditing'] = array('input', 'textarea');
$cfg_db['TabsMode'] = array(
    'icons' => __('Icons'),
    'text'  => __('Text'),
    'both'  => __('Both')
);
$cfg_db['PDFDefaultPageSize'] = array(
    'A3'     => 'A3',
    'A4'     => 'A4',
    'A5'     => 'A5',
    'letter' => 'letter',
    'legal'  => 'legal'
);
$cfg_db['ActionLinksMode'] = array(
    'icons' => __('Icons'),
    'text'  => __('Text'),
    'both'  => __('Both')
);
$cfg_db['GridEditing'] = array(
    'click' => __('Click'),
    'double-click' => __('Double click'),
    'disabled' => __('Disabled'),
);
$cfg_db['RelationalDisplay'] = array(
    'K' => __('key'),
    'D' => __('display column')
);
$cfg_db['DefaultTabServer'] = array(
    'index.php',               // the welcome page (recommended for multiuser setups)
    'server_databases.php',    // list of databases
    'server_status.php',       // runtime information
    'server_variables.php',    // MySQL server variables
    'server_privileges.php'    // user management
);
$cfg_db['DefaultTabDatabase'] = array(
    'db_structure.php',   // tables list
    'db_sql.php',         // SQL form
    'db_search.php',      // search query
    'db_operations.php'   // operations on database
);
$cfg_db['DefaultTabTable'] = array(
    'tbl_structure.php', // fields list
    'tbl_sql.php',       // SQL form
    'tbl_select.php',    // search page
    'tbl_change.php',    // insert row page
    'sql.php'            // browse page
);
$cfg_db['InitialSlidersState'] = array(
    'open'     => __('Open'),
    'closed'   => __('Closed'),
    'disabled' => __('Disabled')
);
$cfg_db['SendErrorReports'] = array(
    'ask'     => __('Ask before sending error reports'),
    'always'   => __('Always send error reports'),
    'never' => __('Never send error reports')
);
$cfg_db['Import']['format'] = array(
    'csv',    // CSV
    'docsql', // DocSQL
    'ldi',    // CSV using LOAD DATA
    'sql'     // SQL
);
$cfg_db['Import']['charset'] = array_merge(
    array(''),
    $GLOBALS['cfg']['AvailableCharsets']
);
$cfg_db['Import']['sql_compatibility']
    = $cfg_db['Export']['sql_compatibility'] = array(
    'NONE', 'ANSI', 'DB2', 'MAXDB', 'MYSQL323',
    'MYSQL40', 'MSSQL', 'ORACLE',
    // removed; in MySQL 5.0.33, this produces exports that
    // can't be read by POSTGRESQL (see our bug #1596328)
    //'POSTGRESQL',
    'TRADITIONAL'
);
$cfg_db['Import']['csv_terminated'] = 'short_string';
$cfg_db['Import']['csv_enclosed'] = 'short_string';
$cfg_db['Import']['csv_escaped'] = 'short_string';
$cfg_db['Import']['ldi_terminated'] = 'short_string';
$cfg_db['Import']['ldi_enclosed'] = 'short_string';
$cfg_db['Import']['ldi_escaped'] = 'short_string';
$cfg_db['Import']['ldi_local_option'] = array('auto', true, false);
$cfg_db['Export']['_sod_select'] = array(
    'structure'          => __('structure'),
    'data'               => __('data'),
    'structure_and_data' => __('structure and data')
);
$cfg_db['Export']['method'] = array(
    'quick'          => __('Quick - display only the minimal options to configure'),
    'custom'         => __('Custom - display all possible options to configure'),
    'custom-no-form' => __('Custom - like above, but without the quick/custom choice')
);
$cfg_db['Export']['format'] = array(
    'codegen', 'csv', 'excel', 'htmlexcel','htmlword', 'latex', 'ods',
    'odt', 'pdf', 'sql', 'texytext', 'xls', 'xml', 'yaml'
);
$cfg_db['Export']['compression'] = array('none', 'zip', 'gzip');
$cfg_db['Export']['charset'] = array_merge(
    array(''),
    $GLOBALS['cfg']['AvailableCharsets']
);
$cfg_db['Export']['codegen_format'] = array(
    '#', 'NHibernate C# DO', 'NHibernate XML'
);
$cfg_db['Export']['csv_separator'] = 'short_string';
$cfg_db['Export']['csv_terminated'] = 'short_string';
$cfg_db['Export']['csv_enclosed'] = 'short_string';
$cfg_db['Export']['csv_escaped'] = 'short_string';
$cfg_db['Export']['csv_null'] = 'short_string';
$cfg_db['Export']['excel_null'] = 'short_string';
$cfg_db['Export']['excel_edition'] = array(
    'win'           => 'Windows',
    'mac_excel2003' => 'Excel 2003 / Macintosh',
    'mac_excel2008' => 'Excel 2008 / Macintosh'
);
$cfg_db['Export']['sql_structure_or_data'] = $cfg_db['Export']['_sod_select'];
$cfg_db['Export']['sql_type'] = array('INSERT', 'UPDATE', 'REPLACE');
$cfg_db['Export']['sql_insert_syntax'] = array(
    'complete' => __('complete inserts'),
    'extended' => __('extended inserts'),
    'both'     => __('both of the above'),
    'none'     => __('neither of the above')
);
$cfg_db['Export']['xls_null'] = 'short_string';
$cfg_db['Export']['xlsx_null'] = 'short_string';
$cfg_db['Export']['htmlword_structure_or_data'] = $cfg_db['Export']['_sod_select'];
$cfg_db['Export']['htmlword_null'] = 'short_string';
$cfg_db['Export']['ods_null'] = 'short_string';
$cfg_db['Export']['odt_null'] = 'short_string';
$cfg_db['Export']['odt_structure_or_data'] = $cfg_db['Export']['_sod_select'];
$cfg_db['Export']['texytext_structure_or_data'] = $cfg_db['Export']['_sod_select'];
$cfg_db['Export']['texytext_null'] = 'short_string';

/**
 * Default values overrides
 * Use only full paths
 */
$cfg_db['_overrides'] = array();

/**
 * Basic validator assignments (functions from libraries/config/Validator.class.php
 * and 'validators' object in js/config.js)
 * Use only full paths and form ids
 */
$cfg_db['_validators'] = array(
    'CharTextareaCols' => 'validatePositiveNumber',
    'CharTextareaRows' => 'validatePositiveNumber',
    'ExecTimeLimit' => 'validateNonNegativeNumber',
    'Export/sql_max_query_size' => 'validatePositiveNumber',
    'FirstLevelNavigationItems' => 'validatePositiveNumber',
    'ForeignKeyMaxLimit' => 'validatePositiveNumber',
    'Import/csv_enclosed' => array(array('validateByRegex', '/^.?$/')),
    'Import/csv_escaped' => array(array('validateByRegex', '/^.$/')),
    'Import/csv_terminated' => array(array('validateByRegex', '/^.$/')),
    'Import/ldi_enclosed' => array(array('validateByRegex', '/^.?$/')),
    'Import/ldi_escaped' => array(array('validateByRegex', '/^.$/')),
    'Import/ldi_terminated' => array(array('validateByRegex', '/^.$/')),
    'Import/skip_queries' => 'validateNonNegativeNumber',
    'InsertRows' => 'validatePositiveNumber',
    'NumRecentTables' => 'validateNonNegativeNumber',
    'NumFavoriteTables' => 'validateNonNegativeNumber',
    'LimitChars' => 'validatePositiveNumber',
    'LoginCookieValidity' => 'validatePositiveNumber',
    'LoginCookieStore' => 'validateNonNegativeNumber',
    'MaxDbList' => 'validatePositiveNumber',
    'MaxNavigationItems' => 'validatePositiveNumber',
    'MaxCharactersInDisplayedSQL' => 'validatePositiveNumber',
    'MaxRows' => 'validatePositiveNumber',
    'MaxTableList' => 'validatePositiveNumber',
    'MemoryLimit' => array(array('validateByRegex', '/^(-1|(\d+(?:[kmg])?))$/i')),
    'NavigationTreeTableLevel' => 'validatePositiveNumber',
    'QueryHistoryMax' => 'validatePositiveNumber',
    'RepeatCells' => 'validateNonNegativeNumber',
    'Server' => 'validateServer',
    'Server_pmadb' => 'validatePMAStorage',
    'Servers/1/port' => 'validatePortNumber',
    'Servers/1/hide_db' => 'validateRegex',
    'TextareaCols' => 'validatePositiveNumber',
    'TextareaRows' => 'validatePositiveNumber',
    'TrustedProxies' => 'validateTrustedProxies');

/**
 * Additional validators used for user preferences
 */
$cfg_db['_userValidators'] = array(
    'MaxDbList'       => array(
        array('validateUpperBound', 'value:MaxDbList')
    ),
    'MaxTableList'    => array(
        array('validateUpperBound', 'value:MaxTableList')
    ),
    'QueryHistoryMax' => array(
        array('validateUpperBound', 'value:QueryHistoryMax')
    )
);
?>


text:
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
  <link href="http://gmpg.org/xfn/11" rel="profile">

  <title>
    {% if page.title %}{{ page.title }} · {% endif %}
    {{ site.tagline }}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400italic,400,600,700|Abril+Fatface">

  <!-- Icons -->
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/touch-icon-144-precomposed.png?">
  <link rel="shortcut icon" href="/public/favicon.png?">

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

{% if site.mathjax == true %}
<!-- MathJax -->
<script src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
{% endif %}

{% include google_analytics.html %}

<script>
/**
* Function that tracks a click on an outbound link in Google Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label.
*/
var trackOutboundLink = function(url, isExternal) {
    var params = {};

    if (!isExternal) {
        params.hitCallback = function () {
            document.location = url;
        }
    }
    ga('send', 'event', 'outbound', 'click', url, params);

    return isExternal;
}
</script>
</head>


text:
#include <aws/mediaconvert/model/CmafIntervalCadence.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace MediaConvert
  {
    namespace Model
    {
      namespace CmafIntervalCadenceMapper
      {

        static const int FOLLOW_IFRAME_HASH = HashingUtils::HashString("FOLLOW_IFRAME");
        static const int FOLLOW_CUSTOM_HASH = HashingUtils::HashString("FOLLOW_CUSTOM");

        CmafIntervalCadence GetCmafIntervalCadenceForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == FOLLOW_IFRAME_HASH)
          {
            return CmafIntervalCadence::FOLLOW_IFRAME;
          }
          else if (hashCode == FOLLOW_CUSTOM_HASH)
          {
            return CmafIntervalCadence::FOLLOW_CUSTOM;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<CmafIntervalCadence>(hashCode);
          }

          return CmafIntervalCadence::NOT_SET;
        }

        Aws::String GetNameForCmafIntervalCadence(CmafIntervalCadence enumValue)
        {
          switch(enumValue)
          {
          case CmafIntervalCadence::FOLLOW_IFRAME:
            return "FOLLOW_IFRAME";
          case CmafIntervalCadence::FOLLOW_CUSTOM:
            return "FOLLOW_CUSTOM";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace CmafIntervalCadenceMapper
    } // namespace Model
  } // namespace MediaConvert
} // namespace Aws


text:
"""Scarab caches."""
import hashlib

from .loaders import file_names

class OutputCache:
    """Cache that helps filter away any files that are the same.

    Builds a cache from the directory it is given.
    Then uses that cache to eliminate items from a sequence, when used.
    """

    def __init__(self, directory):
        """Create a new OutputCache."""
        self.directory = directory
        self.cache = {
            file_name: self._file_checksum(file_name)
            for file_name in file_names(directory)
        }

    @classmethod
    def _file_checksum(cls, file_name):
        """Get the checksum of the contents of a file."""
        with open(file_name, 'br') as fo:
            return cls._calc_checksum(fo.read())

    @staticmethod
    def _calc_checksum(value):
        """Return the checksum of some bytes."""
        return hashlib.md5(value).hexdigest()

    def filter(self, generator):
        """Yield items from a generator if they are not known."""
        for each in generator:
            value = self._calc_checksum(each['bytes'])
            full_destination = self.directory + '/' + each['destination']
            if self.cache.get(full_destination) == value:
                continue

            yield each
            self.cache[full_destination] = value


text:
package br.eti.kinoshita.testlinkjavaapi.testplan;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import br.eti.kinoshita.testlinkjavaapi.BaseTest;
import br.eti.kinoshita.testlinkjavaapi.model.TestPlan;
import br.eti.kinoshita.testlinkjavaapi.util.TestLinkAPIException;

/**
 * @author Bruno P. Kinoshita - http://www.kinoshita.eti.br
 * @since
 */
public class TestCreateTestPlan extends BaseTest {

    @DataProvider(name = "testPlanData")
    public Object[][] createData() {
	return new Object[][] { { "Sample project", "Sample notes.", true, true } };
    }

    @Test(dataProvider = "testPlanData")
    public void testCreateTestPlan(String testProjectName, String notes,
	    Boolean isActive, Boolean isPublic) {
	this.loadXMLRPCMockData("tl.createTestPlan.xml");

	TestPlan testPlan = null;

	try {
	    testPlan = api.createTestPlan(
		    "Sample plan " + System.currentTimeMillis(),
		    testProjectName, notes, isActive, isPublic);
	} catch (TestLinkAPIException e) {
	    Assert.fail(e.getMessage(), e);
	}

	Assert.assertNotNull(testPlan);

	Assert.assertTrue(testPlan.getId() > 0);
    }

}


text:
require 'faraday'
require 'faraday_middleware'
require 'ruby-dmm/response'
require 'ruby-dmm/version'

module DMM
  class Client

    BASE_URL = 'https://api.dmm.com/affiliate/v3/'.freeze
    DEFAULT_USER_AGENT = "ruby-dmm gem #{DMM::VERSION}".freeze

    def initialize(options = {})
      @api_id       = (ENV['DMM_API_ID']       || options[:api_id])
      @affiliate_id = (ENV['DMM_AFFILIATE_ID'] || options[:affiliate_id])
      @user_agent   = (ENV['DMM_USER_AGENT']   || options[:user_agent] || DEFAULT_USER_AGENT)
    end

    API_MAP = {
      product: 'ItemList',      # 商品情報
      floor:   'FloorList',     # フロア
      actress: 'ActressSearch', # 女優検索
      genre:   'GenreSearch',   # ジャンル検索
      maker:   'MakerSearch',   # メーカー検索
      series:  'SeriesSearch',  # シリーズ検索
      author:  'AuthorSearch',  # 作者検索
    }.freeze

    API_MAP.each do |method, path|
      define_method method do |params = {}|
        get(path, credentials.merge(params))
      end
    end

    private

    def credentials
      {
        api_id:       @api_id,
        affiliate_id: @affiliate_id,
      }
    end

    def get(path, options = {})
      Response.new(connection.get(path, options))
    end

    def connection
      @connection ||= Faraday.new(faraday_options) do |faraday|
        faraday.adapter  Faraday.default_adapter
        faraday.request  :url_encoded
        faraday.response :json
      end
    end

    def faraday_options
      {
        url: BASE_URL,
        headers: {
          user_agent: @user_agent,
        },
      }
    end
  end
end


text:
<?php

namespace backend\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\LoanCarAssessControl;

/**
 * LoanCarAssessControlSearch represents the model behind the search form about `common\models\LoanCarAssessControl`.
 */
class LoanCarAssessControlSearch extends LoanCarAssessControl
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'car_id', 'loan_id', 'put_stor_time', 'control_by_id', 'control_time', 'control_type', 'transfer_time', 'if_all_docment', 'order', 'status', 'created_by', 'created_at', 'updated_at'], 'integer'],
            [['put_stor_reason', 'tag_code', 'car_owner', 'car_certificate_number', 'control_address', 'transfer_person', 'transfer_telephone', 'transfer_card_number', 'car_license_number', 'control_description', 'car_condition', 'remarks'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = LoanCarAssessControl::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'id' => SORT_DESC
                ]
            ]
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'car_id' => $this->car_id,
            'loan_id' => $this->loan_id,
            'put_stor_time' => $this->put_stor_time,
            'control_by_id' => $this->control_by_id,
            'control_time' => $this->control_time,
            'control_type' => $this->control_type,
            'transfer_time' => $this->transfer_time,
            'if_all_docment' => $this->if_all_docment,
            'order' => $this->order,
            'status' => $this->status,
            'created_by' => $this->created_by,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'put_stor_reason', $this->put_stor_reason])
            ->andFilterWhere(['like', 'tag_code', $this->tag_code])
            ->andFilterWhere(['like', 'car_owner', $this->car_owner])
            ->andFilterWhere(['like', 'car_certificate_number', $this->car_certificate_number])
            ->andFilterWhere(['like', 'control_address', $this->control_address])
            ->andFilterWhere(['like', 'transfer_person', $this->transfer_person])
            ->andFilterWhere(['like', 'transfer_telephone', $this->transfer_telephone])
            ->andFilterWhere(['like', 'transfer_card_number', $this->transfer_card_number])
            ->andFilterWhere(['like', 'car_license_number', $this->car_license_number])
            ->andFilterWhere(['like', 'control_description', $this->control_description])
            ->andFilterWhere(['like', 'car_condition', $this->car_condition])
            ->andFilterWhere(['like', 'remarks', $this->remarks]);

        return $dataProvider;
    }
}


text:
package com.alorma.github.libs.contributors.api.dto;

/**
 * Created by Bernat on 20/07/2014.
 */
public class Week {
    public String w;
    public int a;
    public int d;
    public int c;
}


text:
HFColorPicker
=============

A simple colorpicker for iOS.

![Screenshot](https://raw.github.com/hfrahmann/HFColorPicker/master/screenshot.png)

How to use
----------

In the InterfaceBuilder or Storyboard you just add a normal view element to your view and set the class to "HFColorPickerView".
Then just connect the delegate to your ViewController.

Now you have import the *HFColorPickerView.h* in your ViewController and add the delegate.

```
//...
#import "HFColorPickerView.h"

@interface DemoTableViewController : UITableViewController <HFColorPickerViewDelegate>
//...
```

There is only one delegate method that needs to be implemented.

```
- (void)colorPicker:(HFColorPickerView *)colorPickerView selectedColor:(UIColor *)selectedColor;
```

These are the configuration properties for ColorPickerView:

```
_colorPickerView.colors = @[ [UIColor redColor], [UIColor blueColor], [UIColor greenColor], [UIColor yellowColor] ];

// optional:
_colorPickerView.topSpace = 5.0f;
_colorPickerView.buttonDiameter = 20.0f;
_colorPickerView.selectedIndex = 2;
```

License
-------

This project is licensed under the MIT-License.


text:
namespace MediaWiki.Query.CategoryMembers
{
    public class QueryContinue
    {
        public Categorymembers categorymembers { get; set; }
    }
}


text:
<?php

namespace Axis\S1\Twig\Environment;

/**
 * Symfony specific Twig Environment.
 *
 * Designed to be used via AxisServiceContainer plugin
 *
 * @author     Ivan Voskoboynyk
 */
class Environment extends \Twig_Environment
{
  /**
   * @var \sfContext
   */
  protected $context = null;

  /**
   * @param \Twig_LoaderInterface $loader
   * @param array $options
   * @param $context
   * @param array|\Twig_ExtensionInterface[] $extensions
   */
  public function __construct(\Twig_LoaderInterface $loader, array $options = array(), $context, $extensions = array())
  {
    $this->context = $context;
    parent::__construct($loader, $options);

    $this->setExtensions($extensions);
  }

  /**
   * Returns sfContext this can be used in filters.
   *
   * @return \sfContext
   */
  public function getContext()
  {
    return $this->context;
  }
}


text:
import React from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import { actions as counterActions } from '../redux/modules/counter'
import styles from './HomeView.scss'
// import Navbar from '../components/navigation'

// import constants from 'utils/constants'
// import Firebase from 'firebase'
// const ref = new Firebase(constants.FIREBASE)

// We define mapStateToProps where we'd normally use
// the @connect decorator so the data requirements are clear upfront, but then
// export the decorated component after the main class definition so
// the component can be tested w/ and w/o being connected.
// See: http://rackt.github.io/redux/docs/recipes/WritingTests.html

const mapStateToProps = (state) => ({
  counter: state.counter,
  auth: state.auth
})

export class HomeView extends React.Component {

  static propTypes = {
    counter: React.PropTypes.number.isRequired,
    doubleAsync: React.PropTypes.func.isRequired,
    increment: React.PropTypes.func.isRequired,
    history: React.PropTypes.object,
    auth: React.PropTypes.object
  }

  render () {
    console.log(this)
    return (

Welcome {this.props.auth.uid}

          Sample Counter:
          {this.props.counter}

        <button className='btn btn-default'
                onClick={() => this.props.increment(1)}>
          Increment
        </button>
        <button className='btn btn-default'
                onClick={this.props.doubleAsync}>
          Double (Async)
        </button>

        <Link to='/about'>Go To About View</Link>

    )
  }
}

export default connect(mapStateToProps, counterActions)(HomeView)


text:
package integration

import (
	. "gopkg.in/check.v1"

	"fmt"
	"strings"
)

func (s *QemuSuite) TestElideCmdLine(c *C) {
	extra := "cc.hostname=nope rancher.password=three"
	runArgs := []string{
		"--fresh",
		"--append",
		"cc.something=yes rancher.password=two",
		"--append-init",
		extra,
	}
	s.RunQemuWith(c, runArgs...)

	s.CheckOutput(c, "nope\n", Equals, "hostname")
	cmdline := s.CheckOutput(c, "", Not(Equals), "cat /proc/cmdline")
	if strings.Contains(cmdline, extra) {
		c.Errorf("/proc/cmdline (%s) contains info that should be elided (%s)", cmdline, extra)
	}
	s.CheckOutput(c,
		fmt.Sprintf("/init %s\n", extra),
		Equals,
		"sudo ros config get rancher.environment.EXTRA_CMDLINE",
	)
	// TODO: it seems that rancher.password and rancher.autologin are in `ros config export`, but accessible as `ros config get`
	s.CheckOutput(c, "\n", Equals, "sudo ros config get rancher.password")
	s.CheckOutput(c,
		"EXTRA_CMDLINE: /init cc.hostname=nope rancher.password=three\n"+
			"    EXTRA_CMDLINE: /init cc.hostname=nope rancher.password=three\n"+
			"  password: three\n",
		Equals,
		"sudo ros config export | grep password",
	)

	// And then add a service.yml file example.
	s.CheckCall(c,
		`echo 'test:
  image: alpine
  command: echo "tell me a secret ${EXTRA_CMDLINE}"
  labels:
    io.rancher.os.scope: system
  environment:
  - EXTRA_CMDLINE
' > test.yml`)
	s.CheckCall(c, "sudo mv test.yml /var/lib/rancher/conf/test.yml")
	s.CheckCall(c, "sudo ros service enable /var/lib/rancher/conf/test.yml")
	s.CheckCall(c, "sudo ros service up test")
	s.CheckOutput(c,
		"test_1 | tell me a secret /init cc.hostname=nope rancher.password=three\n",
		Equals,
		"sudo ros service logs test | grep secret",
	)

	// TODO: add a test showing we have the right password set
}


text:
package com.burning.iplay.ui.news.focuse.topic;

import com.burning.iplay.bean.news.ArticleListBean;
import com.burning.iplay.bean.RequestParamsBean;
import com.burning.iplay.ui.refresh.RefreshContract;

import java.util.List;

/**
 * @author Kiven
 * @time 2017-2-20  0:37
 * Email f842728368@163.com
 * @desc
 */
public interface TopicContract {

    interface View extends RefreshContract.View<ArticleListBean> {

        @Override
        void refreshRecyclerView(List<ArticleListBean> datas);

        /**
         * 根据P层传入的数据来决定ImageButton的显示图片
         */
        void updateFocuseState(boolean isFocused);
    }

    interface Presenter<T extends View> extends RefreshContract.Presenter<T> {
        @Override
        void requestData(RequestParamsBean params);

        /**
         * 关注ImageButton的点击事件,改变关注状态
         */
        void changeFocuseState();
    }
}


text:
goog.provide('ol.interaction.Pointer');

goog.require('goog.asserts');
goog.require('goog.functions');
goog.require('goog.object');
goog.require('ol.MapBrowserEvent');
goog.require('ol.MapBrowserEvent.EventType');
goog.require('ol.MapBrowserPointerEvent');
goog.require('ol.Pixel');
goog.require('ol.interaction.Interaction');

/**
 * @classdesc
 * Abstract base class; normally only used for creating subclasses and not
 * instantiated in apps.
 *
 * @constructor
 * @extends {ol.interaction.Interaction}
 */
ol.interaction.Pointer = function() {

  goog.base(this);

  /**
   * @type {boolean}
   * @protected
   */
  this.handlingDownUpSequence = false;

  /**
   * @type {Object.<number, ol.pointer.PointerEvent>}
   * @private
   */
  this.trackedPointers_ = {};

  /**
   * @type {Array.<ol.pointer.PointerEvent>}
   * @protected
   */
  this.targetPointers = [];

};
goog.inherits(ol.interaction.Pointer, ol.interaction.Interaction);

/**
 * @param {Array.<ol.pointer.PointerEvent>} pointerEvents
 * @return {ol.Pixel} Centroid pixel.
 */
ol.interaction.Pointer.centroid = function(pointerEvents) {
  var length = pointerEvents.length;
  var clientX = 0;
  var clientY = 0;
  for (var i = 0; i < length; i++) {
    clientX += pointerEvents[i].clientX;
    clientY += pointerEvents[i].clientY;
  }
  return [clientX / length, clientY / length];
};

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @return {boolean} Whether the event is a pointerdown, pointerdrag
 *     or pointerup event.
 * @private
 */
ol.interaction.Pointer.prototype.isPointerDraggingEvent_ =
    function(mapBrowserEvent) {
  var type = mapBrowserEvent.type;
  return (
      type === ol.MapBrowserEvent.EventType.POINTERDOWN ||
      type === ol.MapBrowserEvent.EventType.POINTERDRAG ||
      type === ol.MapBrowserEvent.EventType.POINTERUP);
};

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @private
 */
ol.interaction.Pointer.prototype.updateTrackedPointers_ =
    function(mapBrowserEvent) {
  if (this.isPointerDraggingEvent_(mapBrowserEvent)) {
    var event = mapBrowserEvent.pointerEvent;

    if (mapBrowserEvent.type == ol.MapBrowserEvent.EventType.POINTERUP) {
      delete this.trackedPointers_[event.pointerId];
    } else if (mapBrowserEvent.type ==
        ol.MapBrowserEvent.EventType.POINTERDOWN) {
      this.trackedPointers_[event.pointerId] = event;
    } else if (event.pointerId in this.trackedPointers_) {
      // update only when there was a pointerdown event for this pointer
      this.trackedPointers_[event.pointerId] = event;
    }
    this.targetPointers = goog.object.getValues(this.trackedPointers_);
  }
};

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @protected
 */
ol.interaction.Pointer.prototype.handlePointerDrag = goog.nullFunction;

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @protected
 * @return {boolean} Capture dragging.
 */
ol.interaction.Pointer.prototype.handlePointerUp = goog.functions.FALSE;

/**
 * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event.
 * @protected
 * @return {boolean} Capture dragging.
 */
ol.interaction.Pointer.prototype.handlePointerDown = goog.functions.FALSE;

/**
 * @inheritDoc
 */
ol.interaction.Pointer.prototype.handleMapBrowserEvent =
    function(mapBrowserEvent) {
  if (!(mapBrowserEvent instanceof ol.MapBrowserPointerEvent)) {
    return true;
  }

  var stopEvent = false;
  this.updateTrackedPointers_(mapBrowserEvent);
  if (this.handlingDownUpSequence) {
    if (mapBrowserEvent.type ==
        ol.MapBrowserEvent.EventType.POINTERDRAG) {
      this.handlePointerDrag(mapBrowserEvent);
    } else if (mapBrowserEvent.type ==
        ol.MapBrowserEvent.EventType.POINTERUP) {
      this.handlingDownUpSequence =
          this.handlePointerUp(mapBrowserEvent);
    }
  }
  if (mapBrowserEvent.type == ol.MapBrowserEvent.EventType.POINTERDOWN) {
    var handled = this.handlePointerDown(mapBrowserEvent);
    this.handlingDownUpSequence = handled;
    stopEvent = this.shouldStopEvent(handled);
  }
  return !stopEvent;
};

/**
 * This method allows inheriting classes to stop the event from being
 * passed to further interactions. For example, this is required for
 * interaction `DragRotateAndZoom`.
 *
 * @protected
 * @param {boolean} handled Was the event handled by the interaction?
 * @return {boolean} Should the event be stopped?
 */
ol.interaction.Pointer.prototype.shouldStopEvent = goog.functions.FALSE;


text:
copyright:

  years: 2016, 2017

lastupdated: "2017-04-06"

---

{:shortdesc: .shortdesc}
{:new_window: target="_blank"}
{:codeblock: .codeblock}
{:screen: .screen}

<!-- audience blue staging only begin -->

# Monitoring and logging for Cloud Foundry apps in Dedicated and Local
{: #dedicated_apps_ml_ov}

In {{site.data.keyword.Bluemix_dedicated_notm}} and {{site.data.keyword.Bluemix_local_notm:}}, Cloud Foundry apps come with built-in logging. You can review the data that is collected from your apps on the {{site.data.keyword.Bluemix_notm}} console.
{:shortdesc}

Cloud Foundry apps use Cloud Foundry loggregator to monitor and forward logs from outside of the app. You don't need to install agents inside of the app.

## Hardware requirements

| **Requirement** |    **1 node**     | **3 nodes for high availability** |
|-----------------|-------------------|-------------------|
vCPU | 19 | 57 |
Memory | 80 GB | 240 GB |
Local storage | 2.98 TB | 8.94 TB |
{: caption="Table 1. Logging hardware requirements for {{site.data.keyword.Bluemix_local_notm:}}" caption-side="top"}

## Setup

In {{site.data.keyword.Bluemix}} Dedicated and {{site.data.keyword.Bluemix}} Local, logs are active for all apps by default. To view information about reading standard logs, see Logging for apps running on Cloud Foundry. In addition, advanced logging can be enabled in {{site.data.keyword.Bluemix}} Dedicated and {{site.data.keyword.Bluemix}} Local environments.

## Log retention

In {{site.data.keyword.Bluemix}} Dedicated and {{site.data.keyword.Bluemix}} Local Cloud Foundry apps, log data is stored for 30 days by default.

## Viewing logs for Cloud Foundry apps in {{site.data.keyword.Bluemix}} Dedicated and {{site.data.keyword.Bluemix}} Local
{: #dedicated_apps_ml_logs_dash}

You can review logs for the apps that you are running on {{site.data.keyword.Bluemix_notm}} Dedicated and {{site.data.keyword.Bluemix_notm}} Local.
{:shortdesc}

To view your app logs, follow these steps.
1. Select a running app.
2. Click **Logs**. In the **Logs** view, you can view logs from your running app..
4. Click the **Advanced View** button. **Advanced View** shows a more detailed view of the logs by using Kibana, a visualization tool that uses logs and time-stamped data to create custom visualizations. For more information about using the advanced view, see the [Kibana User Guide ![External link icon](../../../icons/launch-glyph.svg "External link icon")](https://www.elastic.co/guide/en/kibana/4.1/index.html){: new_window}.

Next, you can customize a Kibana dashboard. See [Advanced log analysis with Kibana](../kibana4/analyzing_logs_Kibana.html#analyzing_logs_Kibana) for more information.

<!-- audience blue staging only end comment -->


text:
package com.thoughtworks.go.config;

import com.thoughtworks.go.config.elastic.ElasticProfile;
import com.thoughtworks.go.config.remote.ConfigRepoConfig;
import com.thoughtworks.go.config.remote.PartialConfig;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.domain.scm.SCM;
import com.thoughtworks.go.listener.EntityConfigChangedListener;
import com.thoughtworks.go.server.service.ConfigRepoService;
import com.thoughtworks.go.server.service.GoConfigService;
import com.thoughtworks.go.serverhealth.HealthStateScope;
import com.thoughtworks.go.serverhealth.ServerHealthService;
import com.thoughtworks.go.serverhealth.ServerHealthState;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Tracks all config-repo parsing states
 */
public class ConfigReposMaterialParseResultManager {
    private final Map<String, PartialConfigParseResult> fingerprintOfPartialToParseResultMap = new ConcurrentHashMap<>();
    private final ServerHealthService serverHealthService;
    private final ConfigRepoService configRepoService;

    ConfigReposMaterialParseResultManager(ServerHealthService serverHealthService, ConfigRepoService configRepoService) {
        this.serverHealthService = serverHealthService;
        this.configRepoService = configRepoService;
    }

    public PartialConfigParseResult get(String fingerprint) {
        PartialConfigParseResult result = fingerprintOfPartialToParseResultMap.get(fingerprint);
        // config repository was never parsed, check if there are any material clone or update related errors
        if (result == null) {
            result = checkForMaterialErrors(fingerprint);
        }

        //config repository was parsed, but does not have merge or clone related errors.
        if (result != null && result.isSuccessful()) {
            HealthStateScope healthStateScope = HealthStateScope.forPartialConfigRepo(fingerprint);
            List<ServerHealthState> serverHealthStates = serverHealthService.filterByScope(healthStateScope);
            if (!serverHealthStates.isEmpty()) {
                result.setException(asError(serverHealthStates.get(0)));

                //clear out the good modification, in case good modification is same as of latest parsed modification
                if (Objects.equals(result.getLatestParsedModification(), result.getGoodModification())) {
                    result.setGoodModification(null);
                    result.setPartialConfig(null);
                }
            }
        }

        return result;
    }

    /**
     * Registers the EntityChangedListener for various classes to mark config-repos for reparse on config updates.
     *
     * @param configService the {@link GoConfigService} to register events
     */
    void attachConfigUpdateListeners(GoConfigService configService) {
        configService.register(new ConfigRepoReparseListener(this));
    }

    /**
     * After a successful update of the server config, we should reparse any failed config-repos in case
     * any upstream dependency issues have been resolved.
     * <p>
     * This clears the last parse states and errors related to config-repos so as to allow reparsing. Should be
     * used by ConfigChangedListener and EntityConfigChangedListener instances to hook into config update events.
     */
    void markFailedResultsForReparse() {
        for (Map.Entry<String, PartialConfigParseResult> entry : fingerprintOfPartialToParseResultMap.entrySet()) {
            String fingerprint = entry.getKey();
            PartialConfigParseResult result = entry.getValue();

            HealthStateScope scope = HealthStateScope.forPartialConfigRepo(fingerprint);
            List<ServerHealthState> serverHealthErrors = serverHealthService.filterByScope(scope);

            if (!serverHealthErrors.isEmpty() || !result.isSuccessful()) {
                result.setLatestParsedModification(null); // clear modification to allow a reparse to happen
            }
        }
    }

    private PartialConfigParseResult checkForMaterialErrors(String fingerprint) {
        MaterialConfig naterial = configRepoService.findByFingerprint(fingerprint).getRepo();
        HealthStateScope healthStateScope = HealthStateScope.forMaterialConfig(naterial);
        List<ServerHealthState> serverHealthStates = serverHealthService.filterByScope(healthStateScope);

        return serverHealthStates.isEmpty() ?
                null :
                PartialConfigParseResult.parseFailed(null, asError(serverHealthStates.get(0)));
    }

    private Exception asError(ServerHealthState serverHealthState) {
        return new Exception(serverHealthState.getMessage().toUpperCase() + "\n" + serverHealthState.getDescription());
    }

    Set<String> allFingerprints() {
        return fingerprintOfPartialToParseResultMap.keySet();
    }

    public void remove(String fingerprint) {
        fingerprintOfPartialToParseResultMap.remove(fingerprint);
    }

    PartialConfigParseResult parseFailed(String fingerprint, Modification modification, Exception exception) {
        PartialConfigParseResult existingResult = get(fingerprint);
        if (existingResult == null) { //if no result exists in the map, create a new one
            return fingerprintOfPartialToParseResultMap.put(fingerprint, PartialConfigParseResult.parseFailed(modification, exception));
        } else {
            PartialConfigParseResult newResult = PartialConfigParseResult.parseFailed(modification, exception);
            newResult.setGoodModification(existingResult.getGoodModification());
            newResult.setPartialConfig(existingResult.lastGoodPartialConfig());
            return fingerprintOfPartialToParseResultMap.put(fingerprint, newResult);
        }
    }

    PartialConfigParseResult parseSuccess(String fingerprint, Modification modification, PartialConfig newPart) {
        //if no result exists in the map, create a new one
        //if already a result exists in the map, override the result, as the latest modification is successful. regardless of the result being successful or failed
        return fingerprintOfPartialToParseResultMap.put(fingerprint, PartialConfigParseResult.parseSuccess(modification, newPart));
    }

    static class ConfigRepoReparseListener extends EntityConfigChangedListener<Object> {
        private final List<Class<?>> configClassesToCareAbout = Arrays.asList(
                PipelineConfig.class,
                EnvironmentConfig.class,
                PipelineTemplateConfig.class,
                SCM.class,
                ConfigRepoConfig.class,
                ElasticProfile.class
        );
        private final ConfigReposMaterialParseResultManager configReposMaterialParseResultManager;

        ConfigRepoReparseListener(ConfigReposMaterialParseResultManager configReposMaterialParseResultManager) {
            this.configReposMaterialParseResultManager = configReposMaterialParseResultManager;
        }

        @Override
        public boolean shouldCareAbout(Object entity) {
            return configClassesToCareAbout.stream().anyMatch(aClass -> aClass.isAssignableFrom(entity.getClass()));
        }

        @Override
        public void onEntityConfigChange(Object entity) {
            configReposMaterialParseResultManager.markFailedResultsForReparse();
        }

        @Override
        public void onConfigChange(CruiseConfig newCruiseConfig) {
            configReposMaterialParseResultManager.markFailedResultsForReparse();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Core2D.Model.Renderer;

namespace Core2D.ViewModels.Renderer
{
    public partial class Cache<TKey, TValue> : ICache<TKey, TValue> where TKey : notnull
    {
        private IDictionary<TKey, TValue?> _storage;
        private readonly Action<TValue>? _dispose;

        public Cache(Action<TValue>? dispose = null)
        {
            _dispose = dispose;
            _storage = new Dictionary<TKey, TValue?>();
        }

        public TValue? Get(TKey key)
        {
            return _storage.TryGetValue(key, out var data) ? data : default;
        }

        public void Set(TKey key, TValue? value)
        {
            if (_storage.ContainsKey(key))
            {
                _storage[key] = value;
            }
            else
            {
                _storage.Add(key, value);
            }
        }

        public void Reset()
        {
            if (_dispose is { })
            {
                foreach (var data in _storage)
                {
                    if (data.Value is not null)
                    {
                        _dispose(data.Value);
                    }
                }
            }
            _storage.Clear();
            _storage = new Dictionary<TKey, TValue?>();
        }
    }
}


text:
package org.apache.carbondata.mv.plans.util

import org.apache.spark.sql.catalyst.analysis._
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.optimizer._
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, _}
import org.apache.spark.sql.catalyst.rules.{RuleExecutor, _}
import org.apache.spark.sql.internal.SQLConf

import org.apache.carbondata.mv.plans.modular.SparkVersionHelper

object BirdcageOptimizer extends RuleExecutor[LogicalPlan] {

  val conf = new SQLConf()

  protected val fixedPoint = FixedPoint(conf.optimizerMaxIterations)

  def batches: Seq[Batch] = {
    // Technically some of the rules in Finish Analysis are not optimizer rules and belong more
    // in the analyzer, because they are needed for correctness (e.g. ComputeCurrentTime).
    // However, because we also use the analyzer to canonicalized queries (for view definition),
    // we do not eliminate subqueries or compute current time in the analyzer.
    Batch(
      "Finish Analysis", Once,
      EliminateSubqueryAliases,
      EliminateView,
      ReplaceExpressions,
      ComputeCurrentTime,
      //      GetCurrentDatabase(sessionCatalog),
      RewriteDistinctAggregates,
      ReplaceDeduplicateWithAggregate) ::
    //////////////////////////////////////////////////////////////////////////////////////////
    // Optimizer rules start here
    //////////////////////////////////////////////////////////////////////////////////////////
    // - Do the first call of CombineUnions before starting the major Optimizer rules,
    //   since it can reduce the number of iteration and the other rules could add/move
    //   extra operators between two adjacent Union operators.
    // - Call CombineUnions again in Batch("Operator Optimizations"),
    //   since the other rules might make two separate Unions operators adjacent.
    Batch(
      "Union", Once,
      CombineUnions) ::
    Batch(
      "Pullup Correlated Expressions", Once,
      PullupCorrelatedPredicates) ::
    Batch(
      "Subquery", Once,
      OptimizeSubqueries) ::
    Batch(
      "Replace Operators", fixedPoint,
      ReplaceIntersectWithSemiJoin,
      ReplaceExceptWithAntiJoin,
      ReplaceDistinctWithAggregate) ::
    Batch(
      "Aggregate", fixedPoint,
      RemoveLiteralFromGroupExpressions,
      RemoveRepetitionFromGroupExpressions) ::
    Batch(
      "Operator Optimizations", fixedPoint, SparkVersionHelper.seqOfRules
        ++ extendedOperatorOptimizationRules: _*) ::
    Batch(
      "Check Cartesian Products", Once,
      CheckCartesianProducts) ::
    Batch(
      "Object Expressions Optimization", fixedPoint,
      EliminateMapObjects,
      CombineTypedFilters) ::
    Batch(
      "RewriteSubquery", Once,
      RewritePredicateSubquery,
      CollapseProject) :: Nil
  }

  /**
   * Optimize all the subqueries inside expression.
   */
  object OptimizeSubqueries extends Rule[LogicalPlan] {
    def apply(plan: LogicalPlan): LogicalPlan = {
      plan transformAllExpressions {
        case s: SubqueryExpression =>
          s.withNewPlan(SparkVersionHelper.getOptimizedPlan(s))
      }
    }
  }

  /**
   * Override to provide additional rules for the operator optimization batch.
   */
  def extendedOperatorOptimizationRules: Seq[Rule[LogicalPlan]] = {
    Nil
  }
}


text:
"""Ganeti confd client

Clients can use the confd client library to send requests to a group of master
candidates running confd. The expected usage is through the asyncore framework,
by sending queries, and asynchronously receiving replies through a callback.

This way the client library doesn't ever need to "wait" on a particular answer,
and can proceed even if some udp packets are lost. It's up to the user to
reschedule queries if they haven't received responses and they need them.

Example usage::

  client = ConfdClient(...) # includes callback specification
  req = confd_client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
  client.SendRequest(req)
  # then make sure your client calls asyncore.loop() or daemon.Mainloop.Run()
  # ... wait ...
  # And your callback will be called by asyncore, when your query gets a
  # response, or when it expires.

You can use the provided ConfdFilterCallback to act as a filter, only passing
"newer" answer to your callback, and filtering out outdated ones, or ones
confirming what you already got.

"""

# pylint: disable=E0203

# E0203: Access to member %r before its definition, since we use
# objects.py which doesn't explicitly initialise its members

import time
import random

from ganeti import utils
from ganeti import constants
from ganeti import objects
from ganeti import serializer
from ganeti import daemon # contains AsyncUDPSocket
from ganeti import errors
from ganeti import confd
from ganeti import ssconf
from ganeti import compat
from ganeti import netutils
from ganeti import pathutils

class ConfdAsyncUDPClient(daemon.AsyncUDPSocket):
  """Confd udp asyncore client

  This is kept separate from the main ConfdClient to make sure it's easy to
  implement a non-asyncore based client library.

  """
  def __init__(self, client, family):
    """Constructor for ConfdAsyncUDPClient

    @type client: L{ConfdClient}
    @param client: client library, to pass the datagrams to

    """
    daemon.AsyncUDPSocket.__init__(self, family)
    self.client = client

  # this method is overriding a daemon.AsyncUDPSocket method
  def handle_datagram(self, payload, ip, port):
    self.client.HandleResponse(payload, ip, port)

class _Request(object):
  """Request status structure.

  @ivar request: the request data
  @ivar args: any extra arguments for the callback
  @ivar expiry: the expiry timestamp of the request
  @ivar sent: the set of contacted peers
  @ivar rcvd: the set of peers who replied

  """
  def __init__(self, request, args, expiry, sent):
    self.request = request
    self.args = args
    self.expiry = expiry
    self.sent = frozenset(sent)
    self.rcvd = set()

class ConfdClient(object):
  """Send queries to confd, and get back answers.

  Since the confd model works by querying multiple master candidates, and
  getting back answers, this is an asynchronous library. It can either work
  through asyncore or with your own handling.

  @type _requests: dict
  @ivar _requests: dictionary indexes by salt, which contains data
      about the outstanding requests; the values are objects of type
      L{_Request}

  """
  def __init__(self, hmac_key, peers, callback, port=None, logger=None):
    """Constructor for ConfdClient

    @type hmac_key: string
    @param hmac_key: hmac key to talk to confd
    @type peers: list
    @param peers: list of peer nodes
    @type callback: f(L{ConfdUpcallPayload})
    @param callback: function to call when getting answers
    @type port: integer
    @param port: confd port (default: use GetDaemonPort)
    @type logger: logging.Logger
    @param logger: optional logger for internal conditions

    """
    if not callable(callback):
      raise errors.ProgrammerError("callback must be callable")

    self.UpdatePeerList(peers)
    self._SetPeersAddressFamily()
    self._hmac_key = hmac_key
    self._socket = ConfdAsyncUDPClient(self, self._family)
    self._callback = callback
    self._confd_port = port
    self._logger = logger
    self._requests = {}

    if self._confd_port is None:
      self._confd_port = netutils.GetDaemonPort(constants.CONFD)

  def UpdatePeerList(self, peers):
    """Update the list of peers

    @type peers: list
    @param peers: list of peer nodes

    """
    # we are actually called from init, so:
    # pylint: disable=W0201
    if not isinstance(peers, list):
      raise errors.ProgrammerError("peers must be a list")
    # make a copy of peers, since we're going to shuffle the list, later
    self._peers = list(peers)

  def _PackRequest(self, request, now=None):
    """Prepare a request to be sent on the wire.

    This function puts a proper salt in a confd request, puts the proper salt,
    and adds the correct magic number.

    """
    if now is None:
      now = time.time()
    tstamp = "%d" % now
    req = serializer.DumpSignedJson(request.ToDict(), self._hmac_key, tstamp)
    return confd.PackMagic(req)

  def _UnpackReply(self, payload):
    in_payload = confd.UnpackMagic(payload)
    (dict_answer, salt) = serializer.LoadSignedJson(in_payload, self._hmac_key)
    answer = objects.ConfdReply.FromDict(dict_answer)
    return answer, salt

  def ExpireRequests(self):
    """Delete all the expired requests.

    """
    now = time.time()
    for rsalt, rq in self._requests.items():
      if now >= rq.expiry:
        del self._requests[rsalt]
        client_reply = ConfdUpcallPayload(salt=rsalt,
                                          type=UPCALL_EXPIRE,
                                          orig_request=rq.request,
                                          extra_args=rq.args,
                                          client=self,
                                          )
        self._callback(client_reply)

  def SendRequest(self, request, args=None, coverage=0, async=True):
    """Send a confd request to some MCs

    @type request: L{objects.ConfdRequest}
    @param request: the request to send
    @type args: tuple
    @param args: additional callback arguments
    @type coverage: integer
    @param coverage: number of remote nodes to contact; if default
        (0), it will use a reasonable default
        (L{ganeti.constants.CONFD_DEFAULT_REQ_COVERAGE}), if -1 is
        passed, it will use the maximum number of peers, otherwise the
        number passed in will be used
    @type async: boolean
    @param async: handle the write asynchronously

    """
    if coverage == 0:
      coverage = min(len(self._peers), constants.CONFD_DEFAULT_REQ_COVERAGE)
    elif coverage == -1:
      coverage = len(self._peers)

    if coverage > len(self._peers):
      raise errors.ConfdClientError("Not enough MCs known to provide the"
                                    " desired coverage")

    if not request.rsalt:
      raise errors.ConfdClientError("Missing request rsalt")

    self.ExpireRequests()
    if request.rsalt in self._requests:
      raise errors.ConfdClientError("Duplicate request rsalt")

    if request.type not in constants.CONFD_REQS:
      raise errors.ConfdClientError("Invalid request type")

    random.shuffle(self._peers)
    targets = self._peers[:coverage]

    now = time.time()
    payload = self._PackRequest(request, now=now)

    for target in targets:
      try:
        self._socket.enqueue_send(target, self._confd_port, payload)
      except errors.UdpDataSizeError:
        raise errors.ConfdClientError("Request too big")

    expire_time = now + constants.CONFD_CLIENT_EXPIRE_TIMEOUT
    self._requests[request.rsalt] = _Request(request, args, expire_time,
                                             targets)

    if not async:
      self.FlushSendQueue()

  def HandleResponse(self, payload, ip, port):
    """Asynchronous handler for a confd reply

    Call the relevant callback associated to the current request.

    """
    try:
      try:
        answer, salt = self._UnpackReply(payload)
      except (errors.SignatureError, errors.ConfdMagicError), err:
        if self._logger:
          self._logger.debug("Discarding broken package: %s" % err)
        return

      try:
        rq = self._requests[salt]
      except KeyError:
        if self._logger:
          self._logger.debug("Discarding unknown (expired?) reply: %s" % err)
        return

      rq.rcvd.add(ip)

      client_reply = ConfdUpcallPayload(salt=salt,
                                        type=UPCALL_REPLY,
                                        server_reply=answer,
                                        orig_request=rq.request,
                                        server_ip=ip,
                                        server_port=port,
                                        extra_args=rq.args,
                                        client=self,
                                        )
      self._callback(client_reply)

    finally:
      self.ExpireRequests()

  def FlushSendQueue(self):
    """Send out all pending requests.

    Can be used for synchronous client use.

    """
    while self._socket.writable():
      self._socket.handle_write()

  def ReceiveReply(self, timeout=1):
    """Receive one reply.

    @type timeout: float
    @param timeout: how long to wait for the reply
    @rtype: boolean
    @return: True if some data has been handled, False otherwise

    """
    return self._socket.process_next_packet(timeout=timeout)

  @staticmethod
  def _NeededReplies(peer_cnt):
    """Compute the minimum safe number of replies for a query.

    The algorithm is designed to work well for both small and big
    number of peers:
        - for less than three, we require all responses
        - for less than five, we allow one miss
        - otherwise, half the number plus one

    This guarantees that we progress monotonically: 1->1, 2->2, 3->2,
    4->2, 5->3, 6->3, 7->4, etc.

    @type peer_cnt: int
    @param peer_cnt: the number of peers contacted
    @rtype: int
    @return: the number of replies which should give a safe coverage

    """
    if peer_cnt < 3:
      return peer_cnt
    elif peer_cnt < 5:
      return peer_cnt - 1
    else:
      return int(peer_cnt / 2) + 1

  def WaitForReply(self, salt, timeout=constants.CONFD_CLIENT_EXPIRE_TIMEOUT):
    """Wait for replies to a given request.

    This method will wait until either the timeout expires or a
    minimum number (computed using L{_NeededReplies}) of replies are
    received for the given salt. It is useful when doing synchronous
    calls to this library.

    @param salt: the salt of the request we want responses for
    @param timeout: the maximum timeout (should be less or equal to
        L{ganeti.constants.CONFD_CLIENT_EXPIRE_TIMEOUT}
    @rtype: tuple
    @return: a tuple of (timed_out, sent_cnt, recv_cnt); if the
        request is unknown, timed_out will be true and the counters
        will be zero

    """
    def _CheckResponse():
      if salt not in self._requests:
        # expired?
        if self._logger:
          self._logger.debug("Discarding unknown/expired request: %s" % salt)
        return MISSING
      rq = self._requests[salt]
      if len(rq.rcvd) >= expected:
        # already got all replies
        return (False, len(rq.sent), len(rq.rcvd))
      # else wait, using default timeout
      self.ReceiveReply()
      raise utils.RetryAgain()

    MISSING = (True, 0, 0)

    if salt not in self._requests:
      return MISSING
    # extend the expire time with the current timeout, so that we
    # don't get the request expired from under us
    rq = self._requests[salt]
    rq.expiry += timeout
    sent = len(rq.sent)
    expected = self._NeededReplies(sent)

    try:
      return utils.Retry(_CheckResponse, 0, timeout)
    except utils.RetryTimeout:
      if salt in self._requests:
        rq = self._requests[salt]
        return (True, len(rq.sent), len(rq.rcvd))
      else:
        return MISSING

  def _SetPeersAddressFamily(self):
    if not self._peers:
      raise errors.ConfdClientError("Peer list empty")
    try:
      peer = self._peers[0]
      self._family = netutils.IPAddress.GetAddressFamily(peer)
      for peer in self._peers[1:]:
        if netutils.IPAddress.GetAddressFamily(peer) != self._family:
          raise errors.ConfdClientError("Peers must be of same address family")
    except errors.IPAddressError:
      raise errors.ConfdClientError("Peer address %s invalid" % peer)

# UPCALL_REPLY: server reply upcall
# has all ConfdUpcallPayload fields populated
UPCALL_REPLY = 1
# UPCALL_EXPIRE: internal library request expire
# has only salt, type, orig_request and extra_args
UPCALL_EXPIRE = 2
CONFD_UPCALL_TYPES = compat.UniqueFrozenset([
  UPCALL_REPLY,
  UPCALL_EXPIRE,
  ])

class ConfdUpcallPayload(objects.ConfigObject):
  """Callback argument for confd replies

  @type salt: string
  @ivar salt: salt associated with the query
  @type type: one of confd.client.CONFD_UPCALL_TYPES
  @ivar type: upcall type (server reply, expired request, ...)
  @type orig_request: L{objects.ConfdRequest}
  @ivar orig_request: original request
  @type server_reply: L{objects.ConfdReply}
  @ivar server_reply: server reply
  @type server_ip: string
  @ivar server_ip: answering server ip address
  @type server_port: int
  @ivar server_port: answering server port
  @type extra_args: any
  @ivar extra_args: 'args' argument of the SendRequest function
  @type client: L{ConfdClient}
  @ivar client: current confd client instance

  """
  __slots__ = [
    "salt",
    "type",
    "orig_request",
    "server_reply",
    "server_ip",
    "server_port",
    "extra_args",
    "client",
    ]

class ConfdClientRequest(objects.ConfdRequest):
  """This is the client-side version of ConfdRequest.

  This version of the class helps creating requests, on the client side, by
  filling in some default values.

  """
  def __init__(self, **kwargs):
    objects.ConfdRequest.__init__(self, **kwargs)
    if not self.rsalt:
      self.rsalt = utils.NewUUID()
    if not self.protocol:
      self.protocol = constants.CONFD_PROTOCOL_VERSION
    if self.type not in constants.CONFD_REQS:
      raise errors.ConfdClientError("Invalid request type")

class ConfdFilterCallback(object):
  """Callback that calls another callback, but filters duplicate results.

  @ivar consistent: a dictionary indexed by salt; for each salt, if
      all responses ware identical, this will be True; this is the
      expected state on a healthy cluster; on inconsistent or
      partitioned clusters, this might be False, if we see answers
      with the same serial but different contents

  """
  def __init__(self, callback, logger=None):
    """Constructor for ConfdFilterCallback

    @type callback: f(L{ConfdUpcallPayload})
    @param callback: function to call when getting answers
    @type logger: logging.Logger
    @param logger: optional logger for internal conditions

    """
    if not callable(callback):
      raise errors.ProgrammerError("callback must be callable")

    self._callback = callback
    self._logger = logger
    # answers contains a dict of salt -> answer
    self._answers = {}
    self.consistent = {}

  def _LogFilter(self, salt, new_reply, old_reply):
    if not self._logger:
      return

    if new_reply.serial > old_reply.serial:
      self._logger.debug("Filtering confirming answer, with newer"
                         " serial for query %s" % salt)
    elif new_reply.serial == old_reply.serial:
      if new_reply.answer != old_reply.answer:
        self._logger.warning("Got incoherent answers for query %s"
                             " (serial: %s)" % (salt, new_reply.serial))
      else:
        self._logger.debug("Filtering confirming answer, with same"
                           " serial for query %s" % salt)
    else:
      self._logger.debug("Filtering outdated answer for query %s"
                         " serial: (%d < %d)" % (salt, old_reply.serial,
                                                 new_reply.serial))

  def _HandleExpire(self, up):
    # if we have no answer we have received none, before the expiration.
    if up.salt in self._answers:
      del self._answers[up.salt]
    if up.salt in self.consistent:
      del self.consistent[up.salt]

  def _HandleReply(self, up):
    """Handle a single confd reply, and decide whether to filter it.

    @rtype: boolean
    @return: True if the reply should be filtered, False if it should be passed
             on to the up-callback

    """
    filter_upcall = False
    salt = up.salt
    if salt not in self.consistent:
      self.consistent[salt] = True
    if salt not in self._answers:
      # first answer for a query (don't filter, and record)
      self._answers[salt] = up.server_reply
    elif up.server_reply.serial > self._answers[salt].serial:
      # newer answer (record, and compare contents)
      old_answer = self._answers[salt]
      self._answers[salt] = up.server_reply
      if up.server_reply.answer == old_answer.answer:
        # same content (filter) (version upgrade was unrelated)
        filter_upcall = True
        self._LogFilter(salt, up.server_reply, old_answer)
      # else: different content, pass up a second answer
    else:
      # older or same-version answer (duplicate or outdated, filter)
      if (up.server_reply.serial == self._answers[salt].serial and
          up.server_reply.answer != self._answers[salt].answer):
        self.consistent[salt] = False
      filter_upcall = True
      self._LogFilter(salt, up.server_reply, self._answers[salt])

    return filter_upcall

  def __call__(self, up):
    """Filtering callback

    @type up: L{ConfdUpcallPayload}
    @param up: upper callback

    """
    filter_upcall = False
    if up.type == UPCALL_REPLY:
      filter_upcall = self._HandleReply(up)
    elif up.type == UPCALL_EXPIRE:
      self._HandleExpire(up)

    if not filter_upcall:
      self._callback(up)

class ConfdCountingCallback(object):
  """Callback that calls another callback, and counts the answers

  """
  def __init__(self, callback, logger=None):
    """Constructor for ConfdCountingCallback

    @type callback: f(L{ConfdUpcallPayload})
    @param callback: function to call when getting answers
    @type logger: logging.Logger
    @param logger: optional logger for internal conditions

    """
    if not callable(callback):
      raise errors.ProgrammerError("callback must be callable")

    self._callback = callback
    self._logger = logger
    # answers contains a dict of salt -> count
    self._answers = {}

  def RegisterQuery(self, salt):
    if salt in self._answers:
      raise errors.ProgrammerError("query already registered")
    self._answers[salt] = 0

  def AllAnswered(self):
    """Have all the registered queries received at least an answer?

    """
    return compat.all(self._answers.values())

  def _HandleExpire(self, up):
    # if we have no answer we have received none, before the expiration.
    if up.salt in self._answers:
      del self._answers[up.salt]

  def _HandleReply(self, up):
    """Handle a single confd reply, and decide whether to filter it.

    @rtype: boolean
    @return: True if the reply should be filtered, False if it should be passed
             on to the up-callback

    """
    if up.salt in self._answers:
      self._answers[up.salt] += 1

  def __call__(self, up):
    """Filtering callback

    @type up: L{ConfdUpcallPayload}
    @param up: upper callback

    """
    if up.type == UPCALL_REPLY:
      self._HandleReply(up)
    elif up.type == UPCALL_EXPIRE:
      self._HandleExpire(up)
    self._callback(up)

class StoreResultCallback(object):
  """Callback that simply stores the most recent answer.

  @ivar _answers: dict of salt to (have_answer, reply)

  """
  _NO_KEY = (False, None)

  def __init__(self):
    """Constructor for StoreResultCallback

    """
    # answers contains a dict of salt -> best result
    self._answers = {}

  def GetResponse(self, salt):
    """Return the best match for a salt

    """
    return self._answers.get(salt, self._NO_KEY)

  def _HandleExpire(self, up):
    """Expiration handler.

    """
    if up.salt in self._answers and self._answers[up.salt] == self._NO_KEY:
      del self._answers[up.salt]

  def _HandleReply(self, up):
    """Handle a single confd reply, and decide whether to filter it.

    """
    self._answers[up.salt] = (True, up)

  def __call__(self, up):
    """Filtering callback

    @type up: L{ConfdUpcallPayload}
    @param up: upper callback

    """
    if up.type == UPCALL_REPLY:
      self._HandleReply(up)
    elif up.type == UPCALL_EXPIRE:
      self._HandleExpire(up)

def GetConfdClient(callback):
  """Return a client configured using the given callback.

  This is handy to abstract the MC list and HMAC key reading.

  @attention: This should only be called on nodes which are part of a
      cluster, since it depends on a valid (ganeti) data directory;
      for code running outside of a cluster, you need to create the
      client manually

  """
  ss = ssconf.SimpleStore()
  mc_file = ss.KeyToFilename(constants.SS_MASTER_CANDIDATES_IPS)
  mc_list = utils.ReadFile(mc_file).splitlines()
  hmac_key = utils.ReadFile(pathutils.CONFD_HMAC_KEY)
  return ConfdClient(hmac_key, mc_list, callback)


text:
<?xml version="1.0"?>
<!--

-->
<rules xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Paypal:etc/rules.xsd">
    <!-- Website Payments Standard -->
    <payment id="wps_other">
        <events selector="[data-enable='payment']">
            <event value="0" name="deactivate-rule"/>
            <event value="1" name="activate-rule">
                <predicate name="confirm"
                           message="There is already another PayPal solution enabled. Enable this solution instead?"
                           event="deactivate-rule"
                        >
                    <argument name="wpp_ca">wpp_ca</argument>
                    <argument name="paypal_payflowpro_ca">paypal_payflowpro_ca</argument>
                    <argument name="payflow_link_ca">payflow_link_ca</argument>
                    <argument name="express_checkout_other">express_checkout_other</argument>
                </predicate>
            </event>
        </events>
        <relation target="wpp_ca">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="paypal_payflowpro_ca">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="payflow_link_ca">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="express_checkout_other">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target=":self">
            <rule type="simpleMarkEnable" event="activate-rule"/>
            <rule type="simpleDisable" event="deactivate-rule"/>
            <rule type="conflict" event=":load">
                <argument name="wpp_ca">wpp_ca</argument>
                <argument name="paypal_payflowpro_ca">paypal_payflowpro_ca</argument>
                <argument name="payflow_link_ca">payflow_link_ca</argument>
                <argument name="express_checkout_other">express_checkout_other</argument>
            </rule>
        </relation>
    </payment>
    <!-- Website Payments Pro -->
    <payment id="wpp_ca">
        <events selector="[data-enable='payment']">
            <event value="0" name="deactivate-rule"/>
            <event value="1" name="activate-rule">
                <predicate name="confirm"
                           message="There is already another PayPal solution enabled. Enable this solution instead?"
                           event="deactivate-rule"
                        >
                    <argument name="wps_other">wps_other</argument>
                    <argument name="paypal_payflowpro_ca">paypal_payflowpro_ca</argument>
                    <argument name="payflow_link_ca">payflow_link_ca</argument>
                </predicate>
            </event>
        </events>
        <relation target="wps_other">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="paypal_payflowpro_ca">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="payflow_link_ca">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target=":self">
            <rule type="simpleMarkEnable" event="activate-rule"/>
            <rule type="simpleDisable" event="deactivate-rule"/>
            <rule type="conflict" event=":load">
                <argument name="wps_other">wps_other</argument>
                <argument name="paypal_payflowpro_ca">paypal_payflowpro_ca</argument>
                <argument name="payflow_link_ca">payflow_link_ca</argument>
            </rule>
        </relation>
    </payment>
    <!-- Payflow Pro -->
    <payment id="paypal_payflowpro_ca">
        <events selector="[data-enable='payment']">
            <event value="0" name="deactivate-rule"/>
            <event value="1" name="activate-rule">
                <predicate name="confirm"
                           message="There is already another PayPal solution enabled. Enable this solution instead?"
                           event="deactivate-rule"
                        >
                    <argument name="wps_other">wps_other</argument>
                    <argument name="wpp_ca">wpp_ca</argument>
                    <argument name="payflow_link_ca">payflow_link_ca</argument>
                </predicate>
            </event>
        </events>
        <relation target="wps_other">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="wpp_ca">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="payflow_link_ca">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target=":self">
            <rule type="simpleMarkEnable" event="activate-rule"/>
            <rule type="simpleDisable" event="deactivate-rule"/>
            <rule type="conflict" event=":load">
                <argument name="wps_other">wps_other</argument>
                <argument name="wpp_ca">wpp_ca</argument>
                <argument name="payflow_link_ca">payflow_link_ca</argument>
            </rule>
        </relation>
    </payment>
    <!-- Payflow Link (Includes Express Checkout) -->
    <payment id="payflow_link_ca">
        <events selector="[data-enable='payment']">
            <event value="0" name="deactivate-rule"/>
            <event value="1" name="activate-rule">
                <predicate name="confirm"
                           message="There is already another PayPal solution enabled. Enable this solution instead?"
                           event="deactivate-rule"
                        >
                    <argument name="wps_other">wps_other</argument>
                    <argument name="wpp_ca">wpp_ca</argument>
                    <argument name="paypal_payflowpro_ca">paypal_payflowpro_ca</argument>
                </predicate>
            </event>
        </events>
        <relation target="wps_other">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="wpp_ca">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="paypal_payflowpro_ca">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target="express_checkout_other">
            <rule type="simpleMarkEnable" event="activate-rule"/>
            <rule type="paypalExpressDisable" event="activate-rule"/>
            <rule type="paypalExpressLockConfiguration" event="activate-rule"/>
            <rule type="paypalExpressMarkDisable" event="deactivate-rule">
                <argument name="payflow_link_ca">payflow_link_ca</argument>
            </rule>
            <rule type="paypalExpressUnlockConfiguration" event="deactivate-rule">
                <argument name="payflow_link_ca">payflow_link_ca</argument>
            </rule>
        </relation>
        <relation target=":self">
            <rule type="simpleMarkEnable" event="activate-rule"/>
            <rule type="simpleDisable" event="deactivate-rule"/>
            <rule type="payflowExpressEnable" event="activate-rule"/>
            <rule type="payflowExpressDisable" event="deactivate-rule"/>
            <rule type="payflowExpressLockConditional" event=":load"/>
            <rule type="conflict" event=":load">
                <argument name="wps_other">wps_other</argument>
                <argument name="wpp_ca">wpp_ca</argument>
                <argument name="paypal_payflowpro_ca">paypal_payflowpro_ca</argument>
                <argument name="express_checkout_other">express_checkout_other</argument>
            </rule>
        </relation>
    </payment>
    <!-- Express Checkout -->
    <payment id="express_checkout_other">
        <events selector="[data-enable='payment']">
            <event value="0" name="deactivate-rule"/>
            <event value="1" name="activate-rule">
                <predicate name="confirm"
                           message="There is already another PayPal solution enabled. Enable this solution instead?"
                           event="deactivate-rule"
                        >
                    <argument name="wps_other">wps_other</argument>
                </predicate>
            </event>
        </events>
        <events selector="[data-enable='in-context-api']">
            <event value="0" name="deactivate-in-context-api"/>
            <event value="1" name="activate-in-context-api"/>
        </events>
        <relation target="wps_other">
            <rule type="disable" event="activate-rule"/>
        </relation>
        <relation target=":self">
            <rule type="simpleMarkEnable" event="activate-rule"/>
            <rule type="paypalExpressMarkDisable" event="deactivate-rule">
                <argument name="wps_other">wps_other</argument>
                <argument name="payflow_link_ca">payflow_link_ca</argument>
            </rule>
            <rule type="inContextEnable" event="activate-rule"/>
            <rule type="inContextDisable" event="deactivate-rule"/>
            <rule type="inContextShowMerchantId" event="activate-rule"/>
            <rule type="inContextHideMerchantId" event="deactivate-rule"/>
            <rule type="inContextActivate" event="activate-in-context-api"/>
            <rule type="inContextDeactivate" event="deactivate-in-context-api"/>
            <rule type="inContextDisableConditional" event=":load"/>
            <rule type="conflict" event=":load">
                <argument name="wps_other">wps_other</argument>
                <argument name="payflow_link_ca">payflow_link_ca</argument>
            </rule>
            <rule type="paypalExpressLockConfigurationConditional" event=":load">
                <argument name="payflow_link_ca">payflow_link_ca</argument>
            </rule>
        </relation>
    </payment>
</rules>