text:
import {Expression} from './ast';
import {createOverrideContext} from './scope';
import {ExpressionObserver} from './expression-observer';

export function hasDeclaredDependencies(descriptor) {
  return !!(descriptor && descriptor.get && descriptor.get.dependencies);
}

export function declarePropertyDependencies(ctor, propertyName, dependencies) {
  let descriptor = Object.getOwnPropertyDescriptor(ctor.prototype, propertyName);
  descriptor.get.dependencies = dependencies;
}

export function computedFrom(...rest) {
  return function(target, key, descriptor) {
    descriptor.get.dependencies = rest;
    return descriptor;
  };
}

export class ComputedExpression extends Expression {
  constructor(name, dependencies) {
    super();

    this.name = name;
    this.dependencies = dependencies;
    this.isAssignable = true;
  }

  evaluate(scope, lookupFunctions) {
    return scope.bindingContext[this.name];
  }

  assign(scope, value) {
    scope.bindingContext[this.name] = value;
  }

  accept(visitor) {
    throw new Error('not implemented');
  }

  connect(binding, scope) {
    let dependencies = this.dependencies;
    let i = dependencies.length;
    while (i--) {
      dependencies[i].connect(binding, scope);
    }
  }
}

export function createComputedObserver(obj, propertyName, descriptor, observerLocator) {
  let dependencies = descriptor.get.dependencies;
  if (!(dependencies instanceof ComputedExpression)) {
    let i = dependencies.length;
    while (i--) {
      dependencies[i] = observerLocator.parser.parse(dependencies[i]);
    }
    dependencies = descriptor.get.dependencies = new ComputedExpression(propertyName, dependencies);
  }

  let scope = { bindingContext: obj, overrideContext: createOverrideContext(obj) };
  return new ExpressionObserver(scope, dependencies, observerLocator);
}


text:
CURRENT_DIR=$( cd "$( dirname "$0" )" && pwd )
echo "Current directory: $CURRENT_DIR"

PARENT_DIR="$(dirname "$CURRENT_DIR")"
echo "Parent directory: $PARENT_DIR"

YANEL_SRC="$(dirname "$PARENT_DIR")"
echo "Yanel source directory: $YANEL_SRC"

echo "Build Yanel and run Canoo Web Tests."

cd $YANEL_SRC
./yanel.sh stop
./build.sh clean -DanswerCleanTomcatClusterNode1=yes
./build.sh -Dgwt.compile.skip=true
./yanel.sh start

#cd $YANEL_SRC/src/realms/yanel-website/src/test/canoo
#$YANEL_SRC/tools/apache-ant/bin/ant -Dwt.headless=

cd $YANEL_SRC
./yanel.sh stop

redpajama_set_name: RedPajamaGithub


text:
var util = {};
var embedder = {};
embedder.baseGuestURL = '';
embedder.emptyGuestURL = '';
embedder.windowOpenGuestURL = '';
embedder.noReferrerGuestURL = '';
embedder.redirectGuestURL = '';
embedder.redirectGuestURLDest = '';
embedder.closeSocketURL = '';
embedder.tests = {};

embedder.setUp_ = function(config) {
  if (!config || !config.testServer) {
    return;
  }
  embedder.baseGuestURL = 'http://localhost:' + config.testServer.port;
  embedder.emptyGuestURL = embedder.baseGuestURL +
      '/extensions/platform_apps/web_view/shim/empty_guest.html';
};

window.runTest = function(testName, appToEmbed) {
  if (!embedder.test.testList[testName]) {
    window.console.log('Incorrect testName: ' + testName);
    embedder.test.fail();
    return;
  }

  // Run the test.
  embedder.test.testList[testName](appToEmbed);
};

var LOG = function(msg) {
  window.console.log(msg);
};

embedder.test = {};
embedder.test.succeed = function() {
  chrome.test.sendMessage('TEST_PASSED');
};

embedder.test.fail = function() {
  chrome.test.sendMessage('TEST_FAILED');
};

embedder.test.assertEq = function(a, b) {
  if (a != b) {
    console.log('assertion failed: ' + a + ' != ' + b);
    embedder.test.fail();
  }
};

embedder.test.assertTrue = function(condition) {
  if (!condition) {
    console.log('assertion failed: true != ' + condition);
    embedder.test.fail();
  }
};

embedder.test.assertFalse = function(condition) {
  if (condition) {
    console.log('assertion failed: false != ' + condition);
    embedder.test.fail();
  }
};

// Tests begin.
function testAppViewWithUndefinedDataShouldSucceed(appToEmbed) {
  var appview = new AppView();
  LOG('appToEmbed  ' + appToEmbed);
  document.body.appendChild(appview);
  // Step 1: Attempt to connect to a non-existant app.
  LOG('attempting to connect to non-existant app.');
  appview.connect('abc123', undefined, function(success) {
    // Make sure we fail.
    if (success) {
      LOG('UNEXPECTED CONNECTION.');
      embedder.test.fail();
      return;
    }
    LOG('failed to connect to non-existant app.');
    LOG('attempting to connect to known app.');
    // Step 2: Attempt to connect to an app we know exists.
    appview.connect(appToEmbed, undefined, function(success) {
      // Make sure we don't fail.
      if (!success) {
        LOG('FAILED TO CONNECT.');
        embedder.test.fail();
        return;
      }
      LOG('CONNECTED.');
      embedder.test.succeed();
    });
  });
};

function testAppViewRefusedDataShouldFail(appToEmbed) {
  var appview = new AppView();
  LOG('appToEmbed  ' + appToEmbed);
  document.body.appendChild(appview);
  LOG('Attempting to connect to app with refused params.');
  appview.connect(appToEmbed, { 'foo': 'bar' }, function(success) {
    // Make sure we fail.
    if (success) {
      LOG('UNEXPECTED CONNECTION.');
      embedder.test.fail();
      return;
    }
    LOG('FAILED TO CONNECT.');
    embedder.test.succeed();
  });
};

function testAppViewGoodDataShouldSucceed(appToEmbed) {
  var appview = new AppView();
  LOG('appToEmbed  ' + appToEmbed);
  document.body.appendChild(appview);
  LOG('Attempting to connect to app with good params.');
  // Step 2: Attempt to connect to an app with good params.
  appview.connect(appToEmbed, { 'foo': 'bleep' }, function(success) {
    // Make sure we don't fail.
    if (!success) {
      LOG('FAILED TO CONNECT.');
      embedder.test.fail();
      return;
    }
    LOG('CONNECTED.');
    embedder.test.succeed();
  });
};

function testAppViewMultipleConnects(appToEmbed) {
  var appview = new AppView();
  LOG('appToEmbed  ' + appToEmbed);
  document.body.appendChild(appview);
  var connections = 0;
  var callback = function(success) {
    if (!success) {
      LOG('FAILED TO CONNECT.');
      embedder.test.fail();
      return;
    }
    ++connections;
    LOG('CONNECTED. (' + connections + ' / 10)');
    if (connections == 10) {
      embedder.test.succeed();
      return;
    }
  }
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
  appview.connect(appToEmbed, { 'foo': 'bleep' }, callback);
};

embedder.test.testList = {
  'testAppViewWithUndefinedDataShouldSucceed':
      testAppViewWithUndefinedDataShouldSucceed,
  'testAppViewRefusedDataShouldFail': testAppViewRefusedDataShouldFail,
  'testAppViewGoodDataShouldSucceed': testAppViewGoodDataShouldSucceed,
  'testAppViewMultipleConnects': testAppViewMultipleConnects
};

onload = function() {
  chrome.test.getConfig(function(config) {
    embedder.setUp_(config);
    chrome.test.sendMessage('Launched');
  });
};


text:
import classic from 'ember-classic-decorator';
import { tagName } from '@ember-decorators/component';
import { action, computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import Component from '@ember/component';
import StyleBindingsMixin from 'ember-tree-utils/mixins/style-bindings';
import WithConfigMixin from 'ember-tree-utils/mixins/with-config';
/**
 * An icon action of a tree node
 * @class TreeNodeIconAction
 */

@classic
@tagName('span')
export default class TreeNodeIconAction extends Component.extend(
  WithConfigMixin,
  StyleBindingsMixin
) {
  //('stickyMode:sticky')
  layoutName = 'em-tree-node-icon-action';

  /**
   * Bind the visibility css property,
   * this is required for the `sticky` property
   * @property styleBindings
   * @private
   */
  styleBindings = ['visibility'];

  @alias('meta.name')
  iconName;

  @computed('meta.classes')
  get iconClass() {
    return this.meta?.classes?.join(' ');
  }
  /**
   * Defines the css visibility according to the value of the `sticky` property
   * @property visibility
   * @private
   */
  @computed('sticky')
  get visibility() {
    return this.sticky ? 'visible' : null;
  }

  /**
   * 'true' if the action icon should be sticky and not disappear when item is not hovered
   * @property sticky
   * @public
   */
  sticky = false;

  @computed('sticky')
  get stickyMode() {
    return this.sticky ? 'true' : null;
  }

  init() {
    super.init();
  }

  /**
   * Invoked when the action is clicked
   * @method invoke
   */
  @action
  handleClick() {
    this.meta?.action(this);
  }
}


text:
module Rubel
  RuntimeEnvironment = Runtime::Loader.runtime
  class Base < RuntimeEnvironment
    include ::Rubel::Functions::Defaults
  end
end


text:
package org.gradle.api.internal.tasks.scala;

import org.gradle.api.internal.tasks.compile.JavaCompileSpec;

public interface ScalaJavaJointCompileSpec extends ScalaCompileSpec, JavaCompileSpec {
}


text:
package de.schwedt.weightlifting.app.helper;

import android.content.Context;

import java.io.File;

public class FileCache {

    private File cacheDir;

    public FileCache(Context context) {
        // Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "WeightliftingApp");
        else
            cacheDir = context.getCacheDir();
        if (!cacheDir.exists())
            cacheDir.mkdirs();
    }

    public File getFile(String url) {
        String filename = String.valueOf(url.hashCode());
        // String filename = URLEncoder.encode(url);
        return new File(cacheDir, filename);

    }

}


text:
module Neptune
  class Error < StandardError
    attr_reader :cause

    def initialize(message = nil, cause = $!) #:nodoc:
      super(message)
      @cause = cause
      set_backtrace(cause.backtrace) if cause
    end
  end

  class APIError < Error
    # Error code that came back from the cluster
    # @return [Neptune::ErrorCode]
    attr_reader :error_code

    def initialize(error_code, *args) #:nodoc:
      super("Received error from server: #{error_code.name} (#{error_code.id})", *args)
    end
  end

  # Data parse errors
  class EncodingError < Error;end
  class DecodingError < Error;end

  # Connection errors
  class ConnectionError < Error; end
end


text:
namespace RPGEngine{
	namespace Components{

		Component::Component(Entities::Entity* e){
			this->entity = e;
		}

		void Component::Update(){

		}

		void Component::Render(sf::RenderWindow& window){

		}
	}
}


text:
package com.google.cloud.bigtable.beam;

import static org.junit.Assert.assertEquals;

import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.hadoop.conf.Configuration;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import com.google.cloud.bigtable.beam.CloudBigtableConfiguration;
import com.google.cloud.bigtable.beam.CloudBigtableTableConfiguration;
import com.google.cloud.bigtable.hbase.BigtableOptionsFactory;

/**
 * Tests for {@link CloudBigtableTableConfiguration}.
 */
@RunWith(JUnit4.class)
public class CloudBigtableTableConfigurationTest {

  private static final String PROJECT = "my_project";
  private static final String INSTANCE = "instance";
  private static final String TABLE = "some-zone-1a";

  protected static CloudBigtableTableConfiguration buildConfiguration() {
    return configure(new CloudBigtableTableConfiguration.Builder().withTableId(TABLE)).build();
  }

  protected static <ConfigurationBuilder extends CloudBigtableConfiguration.Builder>
      ConfigurationBuilder configure(ConfigurationBuilder builder) {
    builder.withProjectId(PROJECT).withInstanceId(INSTANCE);
    return builder;
  }

  @Test
  public void testHBaseConfig() {
    CloudBigtableTableConfiguration underTest = buildConfiguration();

    Configuration config = underTest.toHBaseConfig();

    assertEquals(PROJECT, config.get(BigtableOptionsFactory.PROJECT_ID_KEY));
    assertEquals(INSTANCE, config.get(BigtableOptionsFactory.INSTANCE_ID_KEY));
    assertEquals(TABLE, underTest.getTableId());
  }

  @Test
  public void testEquals() {
    CloudBigtableTableConfiguration underTest1 = buildConfiguration();
    CloudBigtableTableConfiguration underTest2 = buildConfiguration();
    CloudBigtableTableConfiguration underTest3 =
        underTest1.toBuilder().withConfiguration("somekey", "somevalue").build();
    CloudBigtableTableConfiguration underTest4 =
        underTest1.toBuilder().withProjectId("other_project").build();
    CloudBigtableConfiguration underTest5 =
        configure(new CloudBigtableConfiguration.Builder()).build();

    // Test CloudBigtableTableConfiguration that should be equal.
    Assert.assertEquals(underTest1, underTest2);

    // Test CloudBigtableTableConfiguration with different additionalConfigurations are not equal.
    Assert.assertNotEquals(underTest1, underTest3);

    // Test CloudBigtableTableConfiguration with different ProjectId are not equal.
    Assert.assertNotEquals(underTest1, underTest4);

    // Test CloudBigtableTableConfiguration is not equal to a similar CloudBigtableConfiguration.
    Assert.assertNotEquals(underTest1, underTest5);

    // Test CloudBigtableConfiguration is not equal to a similar CloudBigtableTableConfiguration.
    // (reversed order from the previous test)
    Assert.assertNotEquals(underTest5, underTest1);
  }

  @Test
  public void testToBuilder(){
    CloudBigtableTableConfiguration underTest =
        buildConfiguration().toBuilder().withConfiguration("somekey", "somevalue").build();
    CloudBigtableTableConfiguration copy = underTest.toBuilder().build();
    Assert.assertNotSame(underTest, copy);
    Assert.assertEquals(underTest, copy);
  }

  /**
   * This ensures that the config built from regular parameters are the same as the config built
   * from runtime parameters, so that we don't have to use runtime parameters to repeat the same
   * tests.
   */
  @Test
  public void testRegularAndRuntimeParametersAreEqual() {
    CloudBigtableTableConfiguration withRegularParameters =
        buildConfiguration().toBuilder().withConfiguration("somekey", "somevalue").build();
    CloudBigtableTableConfiguration withRuntimeParameters =
        new CloudBigtableTableConfiguration.Builder()
            .withTableId(StaticValueProvider.of(TABLE))
            .withProjectId(StaticValueProvider.of(PROJECT))
            .withInstanceId(StaticValueProvider.of(INSTANCE))
            .withConfiguration("somekey", StaticValueProvider.of("somevalue"))
            .build();
    Assert.assertNotSame(withRegularParameters, withRuntimeParameters);
    Assert.assertEquals(withRegularParameters, withRuntimeParameters);
  }
}


text:
import mock
import pytest

from pyramid import httpexceptions as exc
from mock import PropertyMock
from mock import MagicMock
from annotran.reports import views
from annotran.admin import *

_SENTINEL = object()

def _mock_request(feature=None, settings=None, params=None,
                  authenticated_userid=_SENTINEL, route_url=None, **kwargs):
    """Return a mock Pyramid request object."""
    params = params or {"foo": "bar"}
    if authenticated_userid is _SENTINEL:
        authenticated_userid = "acct:fred@annotran.com"
    return mock.Mock(
        feature=feature or (lambda feature: True),
        registry=mock.Mock(settings=settings or {}),
        params=params, POST=params,
        authenticated_userid=authenticated_userid,
        route_url=route_url or mock.Mock(return_value="test-read-url"),
        **kwargs)

def test_add_report_to_db():
    """
        This should add a new report to the database session.
        After successfully creating a new report it should redirect.
    """
    with mock.patch('annotran.languages.models.Language') as language:
        language.get_by_public_language_id = MagicMock(return_value=language)

        with mock.patch('annotran.pages.models.Page') as page:
            page.get_by_uri = MagicMock(return_value=page)

            with mock.patch('h.groups.models.Group') as group:
                group.get_by_pubid = MagicMock(return_value=group)

                with mock.patch('h.models.User') as user:
                    propUser = PropertyMock(return_value=2897)
                    type(user).id = propUser
                    user.get_by_username = MagicMock(return_value=user)

                    with mock.patch('annotran.translations.models.Translation') as translation:
                        propPage = PropertyMock(return_value=2897)
                        type(translation).page_id = propPage

                        propLang = PropertyMock(return_value=2897)
                        type(translation).language_id = propLang

                        propGroup = PropertyMock(return_value=2897)
                        type(translation).group_id = propGroup

                        translation.get_translation = MagicMock(return_value=translation)

                        request = _mock_request(authenticated_user=mock.Mock(username="test"),
                                                matchdict={'public_language_id': '12345',
                                                           'public_group_id': '12345',
                                                           'user_id': '12345',
                                                           'page_uri': 'http://www.annotran_test.com/'})
                        result = views.add_report(request)
                        request.db.add.assert_called_once()
                        assert result == {}

def test_add_report_to_db_pg_auth_rep_group_lang_none():
    """
        This should raise HTTPNotFound as all page, author, reporter, group, and language is None.
    """
    request = _mock_request(authenticated_user=mock.Mock(username="test"),
                            matchdict={'public_language_id': '12345',
                                       'public_group_id': '12345',
                                       'user_id': '12345',
                                       'page_uri': 'http://www.annotran_test.com/'})
    with pytest.raises(exc.HTTPNotFound):
        views.add_report(request)

def test_add_report_to_db_translation_none():
    """
        This should raise HTTPNotFound as translation is None.
    """
    with mock.patch('annotran.languages.models.Language') as language:
        language.get_by_public_language_id = MagicMock(return_value=language)

        with mock.patch('annotran.pages.models.Page') as page:
            page.get_by_uri = MagicMock(return_value=page)

            with mock.patch('h.groups.models.Group') as group:
                group.get_by_pubid = MagicMock(return_value=group)

                with mock.patch('h.models.User') as user:
                    user.get_by_username = MagicMock(return_value=user)

                    with mock.patch('annotran.translations.models.Translation') as translation:
                        translation.get_translation = MagicMock(return_value=None)

                        request = _mock_request(authenticated_user=mock.Mock(username="test"),
                                                matchdict={'public_language_id': '12345',
                                                           'public_group_id': '12345',
                                                           'user_id': '12345',
                                                           'page_uri': 'http://www.annotran_test.com/'})
                        with pytest.raises(exc.HTTPNotFound):
                            views.add_report(request)

def test_add_existing_report_to_db():
    """
        This should not add a new report to the database session as the one already exists.
    """
    with mock.patch('annotran.languages.models.Language') as language:
        language.get_by_public_language_id = MagicMock(return_value=language)

        with mock.patch('annotran.pages.models.Page') as page:
            page.get_by_uri = MagicMock(return_value=page)

            with mock.patch('h.groups.models.Group') as group:
                group.get_by_pubid = MagicMock(return_value=group)

                with mock.patch('h.models.User') as user:
                    user.get_by_username = MagicMock(return_value=user)

                    with mock.patch('annotran.translations.models.Translation') as translation:
                        translation.get_translation = MagicMock(return_value=translation)

                        with mock.patch('annotran.reports.models.Report') as report:
                            report.get_report = MagicMock(return_value=report)

                            request = _mock_request(authenticated_user=mock.Mock(username="test"),
                                                    matchdict={'public_language_id': '12345',
                                                               'public_group_id': '12345',
                                                               'user_id': '12345',
                                                               'page_uri': 'http://www.annotran_test.com/'})
                            result = views.add_report(request)
                            assert not request.db.add.called
                            assert isinstance(result, exc.HTTPBadRequest)


text:
<?php

final class DifferentialChangeset
  extends DifferentialDAO
  implements
    PhabricatorPolicyInterface,
    PhabricatorDestructibleInterface {

  protected $diffID;
  protected $oldFile;
  protected $filename;
  protected $awayPaths;
  protected $changeType;
  protected $fileType;
  protected $metadata = array();
  protected $oldProperties;
  protected $newProperties;
  protected $addLines;
  protected $delLines;

  private $unsavedHunks = array();
  private $hunks = self::ATTACHABLE;
  private $diff = self::ATTACHABLE;

  const TABLE_CACHE = 'differential_changeset_parse_cache';

  const METADATA_TRUSTED_ATTRIBUTES = 'attributes.trusted';
  const METADATA_UNTRUSTED_ATTRIBUTES = 'attributes.untrusted';
  const METADATA_EFFECT_HASH = 'hash.effect';

  const ATTRIBUTE_GENERATED = 'generated';

  protected function getConfiguration() {
    return array(
      self::CONFIG_SERIALIZATION => array(
        'metadata'      => self::SERIALIZATION_JSON,
        'oldProperties' => self::SERIALIZATION_JSON,
        'newProperties' => self::SERIALIZATION_JSON,
        'awayPaths'     => self::SERIALIZATION_JSON,
      ),
      self::CONFIG_COLUMN_SCHEMA => array(
        'oldFile' => 'bytes?',
        'filename' => 'bytes',
        'changeType' => 'uint32',
        'fileType' => 'uint32',
        'addLines' => 'uint32',
        'delLines' => 'uint32',

        // T6203/NULLABILITY
        // These should all be non-nullable, and store reasonable default
        // JSON values if empty.
        'awayPaths' => 'text?',
        'metadata' => 'text?',
        'oldProperties' => 'text?',
        'newProperties' => 'text?',
      ),
      self::CONFIG_KEY_SCHEMA => array(
        'diffID' => array(
          'columns' => array('diffID'),
        ),
      ),
    ) + parent::getConfiguration();
  }

  public function getAffectedLineCount() {
    return $this->getAddLines() + $this->getDelLines();
  }

  public function attachHunks(array $hunks) {
    assert_instances_of($hunks, 'DifferentialHunk');
    $this->hunks = $hunks;
    return $this;
  }

  public function getHunks() {
    return $this->assertAttached($this->hunks);
  }

  public function getDisplayFilename() {
    $name = $this->getFilename();
    if ($this->getFileType() == DifferentialChangeType::FILE_DIRECTORY) {
      $name .= '/';
    }
    return $name;
  }

  public function getOwnersFilename() {
    // TODO: For Subversion, we should adjust these paths to be relative to
    // the repository root where possible.

    $path = $this->getFilename();

    if (!isset($path[0])) {
      return '/';
    }

    if ($path[0] != '/') {
      $path = '/'.$path;
    }

    return $path;
  }

  public function addUnsavedHunk(DifferentialHunk $hunk) {
    if ($this->hunks === self::ATTACHABLE) {
      $this->hunks = array();
    }
    $this->hunks[] = $hunk;
    $this->unsavedHunks[] = $hunk;
    return $this;
  }

  public function save() {
    $this->openTransaction();
      $ret = parent::save();
      foreach ($this->unsavedHunks as $hunk) {
        $hunk->setChangesetID($this->getID());
        $hunk->save();
      }
    $this->saveTransaction();
    return $ret;
  }

  public function delete() {
    $this->openTransaction();

      $hunks = id(new DifferentialHunk())->loadAllWhere(
        'changesetID = %d',
        $this->getID());
      foreach ($hunks as $hunk) {
        $hunk->delete();
      }

      $this->unsavedHunks = array();

      queryfx(
        $this->establishConnection('w'),
        'DELETE FROM %T WHERE id = %d',
        self::TABLE_CACHE,
        $this->getID());

      $ret = parent::delete();
    $this->saveTransaction();
    return $ret;
  }

  /**
   * Test if this changeset and some other changeset put the affected file in
   * the same state.
   *
   * @param DifferentialChangeset Changeset to compare against.
   * @return bool True if the two changesets have the same effect.
   */
  public function hasSameEffectAs(DifferentialChangeset $other) {
    if ($this->getFilename() !== $other->getFilename()) {
      return false;
    }

    $hash_key = self::METADATA_EFFECT_HASH;

    $u_hash = $this->getChangesetMetadata($hash_key);
    if ($u_hash === null) {
      return false;
    }

    $v_hash = $other->getChangesetMetadata($hash_key);
    if ($v_hash === null) {
      return false;
    }

    if ($u_hash !== $v_hash) {
      return false;
    }

    // Make sure the final states for the file properties (like the "+x"
    // executable bit) match one another.
    $u_props = $this->getNewProperties();
    $v_props = $other->getNewProperties();
    ksort($u_props);
    ksort($v_props);

    if ($u_props !== $v_props) {
      return false;
    }

    return true;
  }

  public function getSortKey() {
    $sort_key = $this->getFilename();
    // Sort files with ".h" in them first, so headers (.h, .hpp) come before
    // implementations (.c, .cpp, .cs).
    $sort_key = str_replace('.h', '.!h', $sort_key);
    return $sort_key;
  }

  public function makeNewFile() {
    $file = mpull($this->getHunks(), 'makeNewFile');
    return implode('', $file);
  }

  public function makeOldFile() {
    $file = mpull($this->getHunks(), 'makeOldFile');
    return implode('', $file);
  }

  public function makeChangesWithContext($num_lines = 3) {
    $with_context = array();
    foreach ($this->getHunks() as $hunk) {
      $context = array();
      $changes = explode("\n", $hunk->getChanges());
      foreach ($changes as $l => $line) {
        $type = substr($line, 0, 1);
        if ($type == '+' || $type == '-') {
          $context += array_fill($l - $num_lines, 2 * $num_lines + 1, true);
        }
      }
      $with_context[] = array_intersect_key($changes, $context);
    }
    return array_mergev($with_context);
  }

  public function getAnchorName() {
    return 'change-'.PhabricatorHash::digestForAnchor($this->getFilename());
  }

  public function getAbsoluteRepositoryPath(
    PhabricatorRepository $repository = null,
    DifferentialDiff $diff = null) {

    $base = '/';
    if ($diff && $diff->getSourceControlPath()) {
      $base = id(new PhutilURI($diff->getSourceControlPath()))->getPath();
    }

    $path = $this->getFilename();
    $path = rtrim($base, '/').'/'.ltrim($path, '/');

    $svn = PhabricatorRepositoryType::REPOSITORY_TYPE_SVN;
    if ($repository && $repository->getVersionControlSystem() == $svn) {
      $prefix = $repository->getDetail('remote-uri');
      $prefix = id(new PhutilURI($prefix))->getPath();
      if (!strncmp($path, $prefix, strlen($prefix))) {
        $path = substr($path, strlen($prefix));
      }
      $path = '/'.ltrim($path, '/');
    }

    return $path;
  }

  public function attachDiff(DifferentialDiff $diff) {
    $this->diff = $diff;
    return $this;
  }

  public function getDiff() {
    return $this->assertAttached($this->diff);
  }

  public function newFileTreeIcon() {
    $file_type = $this->getFileType();
    $change_type = $this->getChangeType();

    $change_icons = array(
      DifferentialChangeType::TYPE_DELETE => 'fa-file-o',
    );

    if (isset($change_icons[$change_type])) {
      $icon = $change_icons[$change_type];
    } else {
      $icon = DifferentialChangeType::getIconForFileType($file_type);
    }

    $change_colors = array(
      DifferentialChangeType::TYPE_ADD => 'green',
      DifferentialChangeType::TYPE_DELETE => 'red',
      DifferentialChangeType::TYPE_MOVE_AWAY => 'orange',
      DifferentialChangeType::TYPE_MOVE_HERE => 'orange',
      DifferentialChangeType::TYPE_COPY_HERE => 'orange',
      DifferentialChangeType::TYPE_MULTICOPY => 'orange',
    );

    $color = idx($change_colors, $change_type, 'bluetext');

    return id(new PHUIIconView())
      ->setIcon($icon.' '.$color);
  }

  public function getFileTreeClass() {
    switch ($this->getChangeType()) {
      case DifferentialChangeType::TYPE_ADD:
        return 'filetree-added';
      case DifferentialChangeType::TYPE_DELETE:
        return 'filetree-deleted';
      case DifferentialChangeType::TYPE_MOVE_AWAY:
      case DifferentialChangeType::TYPE_MOVE_HERE:
      case DifferentialChangeType::TYPE_COPY_HERE:
      case DifferentialChangeType::TYPE_MULTICOPY:
        return 'filetree-movecopy';
    }

    return null;
  }

  public function setChangesetMetadata($key, $value) {
    if (!is_array($this->metadata)) {
      $this->metadata = array();
    }

    $this->metadata[$key] = $value;

    return $this;
  }

  public function getChangesetMetadata($key, $default = null) {
    if (!is_array($this->metadata)) {
      return $default;
    }

    return idx($this->metadata, $key, $default);
  }

  private function setInternalChangesetAttribute($trusted, $key, $value) {
    if ($trusted) {
      $meta_key = self::METADATA_TRUSTED_ATTRIBUTES;
    } else {
      $meta_key = self::METADATA_UNTRUSTED_ATTRIBUTES;
    }

    $attributes = $this->getChangesetMetadata($meta_key, array());
    $attributes[$key] = $value;
    $this->setChangesetMetadata($meta_key, $attributes);

    return $this;
  }

  private function getInternalChangesetAttributes($trusted) {
    if ($trusted) {
      $meta_key = self::METADATA_TRUSTED_ATTRIBUTES;
    } else {
      $meta_key = self::METADATA_UNTRUSTED_ATTRIBUTES;
    }

    return $this->getChangesetMetadata($meta_key, array());
  }

  public function setTrustedChangesetAttribute($key, $value) {
    return $this->setInternalChangesetAttribute(true, $key, $value);
  }

  public function getTrustedChangesetAttributes() {
    return $this->getInternalChangesetAttributes(true);
  }

  public function getTrustedChangesetAttribute($key, $default = null) {
    $map = $this->getTrustedChangesetAttributes();
    return idx($map, $key, $default);
  }

  public function setUntrustedChangesetAttribute($key, $value) {
    return $this->setInternalChangesetAttribute(false, $key, $value);
  }

  public function getUntrustedChangesetAttributes() {
    return $this->getInternalChangesetAttributes(false);
  }

  public function getUntrustedChangesetAttribute($key, $default = null) {
    $map = $this->getUntrustedChangesetAttributes();
    return idx($map, $key, $default);
  }

  public function getChangesetAttributes() {
    // Prefer trusted values over untrusted values when both exist.
    return
      $this->getTrustedChangesetAttributes() +
      $this->getUntrustedChangesetAttributes();
  }

  public function getChangesetAttribute($key, $default = null) {
    $map = $this->getChangesetAttributes();
    return idx($map, $key, $default);
  }

  public function isGeneratedChangeset() {
    return $this->getChangesetAttribute(self::ATTRIBUTE_GENERATED);
  }

/* -(  PhabricatorPolicyInterface  )----------------------------------------- */

  public function getCapabilities() {
    return array(
      PhabricatorPolicyCapability::CAN_VIEW,
    );
  }

  public function getPolicy($capability) {
    return $this->getDiff()->getPolicy($capability);
  }

  public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
    return $this->getDiff()->hasAutomaticCapability($capability, $viewer);
  }

/* -(  PhabricatorDestructibleInterface  )----------------------------------- */

  public function destroyObjectPermanently(
    PhabricatorDestructionEngine $engine) {
    $this->openTransaction();

      $hunks = id(new DifferentialHunk())->loadAllWhere(
        'changesetID = %d',
        $this->getID());
      foreach ($hunks as $hunk) {
        $engine->destroyObject($hunk);
      }

      $this->delete();

    $this->saveTransaction();
  }

}


text:
//----------------------------------------------
//            NGUI: Next-Gen UI kit
// Copyright © 2011-2013 Tasharen Entertainment
//----------------------------------------------

using UnityEngine;

/// <summary>
/// Tween the object's position.
/// </summary>

[AddComponentMenu("NGUI/Tween/Position")]
public class TweenPosition : UITweener
{
	public Vector3 from;
	public Vector3 to;

	Transform mTrans;

	public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
	public Vector3 position { get { return cachedTransform.localPosition; } set { cachedTransform.localPosition = value; } }

	override protected void OnUpdate (float factor, bool isFinished) { cachedTransform.localPosition = from * (1f - factor) + to * factor; }

	/// <summary>
	/// Start the tweening operation.
	/// </summary>

	static public TweenPosition Begin (GameObject go, float duration, Vector3 pos)
	{
		TweenPosition comp = UITweener.Begin<TweenPosition>(go, duration);
		comp.from = comp.position;
		comp.to = pos;

		if (duration <= 0f)
		{
			comp.Sample(1f, true);
			comp.enabled = false;
		}
		return comp;
	}
}


text:
r"""Finetune models for multi-backone inputs.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import head2toe.models.finetune as finetune_models

from sklearn import ensemble as skens
from sklearn import feature_selection as skfs
import tensorflow.compat.v2 as tf

class FinetuneFS(finetune_models.Finetune):
  """A `tf.keras.Model` implementation of Finetune Feature Selection (FS).

  This learner trains a linear classifier on top of the features given.
  Additionally it supports having a processing step where a subset of features
  are selected.
  """

  def _select_fraction(self, scores, keep_fraction, keep_fraction_offset,
                       mean_interpolation_coef=0):
    """Given a scoring function returns the indices of high scores features."""
    n_kept = keep_fraction_offset + int(tf.size(scores).numpy() * keep_fraction)
    if mean_interpolation_coef > 0:
      # We need to interpolate the scores towards it's mean.
      scores, _ = self._interpolate_scores_towards_mean(
          scores, mean_interpolation_coef)
    _, sorted_indices = tf.nn.top_k(scores, k=n_kept)
    selected_indices = sorted_indices[keep_fraction_offset:]
    return selected_indices

  def _interpolate_scores_towards_mean(self, scores, coef):
    new_scores = []
    mean_scores = []
    for c_scores in tf.split(scores, self.embedding_sizes):
      c_score_mean = tf.reduce_mean(c_scores)
      mean_scores.append(c_score_mean)
      c_scores = c_scores * (1 - coef) + c_score_mean * coef
      new_scores.append(c_scores)
    return tf.concat(new_scores, 0), mean_scores

  def _broadcast_indices(self, kept_indices_all):
    """Splits and removes the offset for indices."""
    start_index = 0
    selected_feature_indices = []
    for embedding_size in self.embedding_sizes:
      end_index = start_index + embedding_size
      kept_indices = tf.boolean_mask(
          kept_indices_all,
          tf.math.logical_and(
              kept_indices_all >= start_index, kept_indices_all < end_index))
      # Remove the offset.
      kept_indices -= start_index

      start_index = end_index
      selected_feature_indices.append(kept_indices)
    return selected_feature_indices

  def _calculate_scores(self, learning_config, dataset):
    # Pre-generate the embeddings
    config_fs = learning_config.feature_selection
    with tf.device('/CPU:0'):
      embeddings, labels = self._embed_dataset(dataset)
    if config_fs.type == 'random':
      concat_embeddings = tf.concat(embeddings, -1)
      all_scores = tf.random.normal(concat_embeddings.shape[1:])
    elif config_fs.type.startswith('variance'):
      concat_embeddings = tf.concat(embeddings, -1)
      all_scores = tf.math.reduce_std(concat_embeddings, axis=0)
    elif config_fs.type.startswith('sklearn'):
      concat_embeddings = tf.concat(embeddings, -1)
      f_name = '_'.join(config_fs.type.strip().split('_')[1:])
      if f_name == 'trees':
        all_scores = skens.ExtraTreesClassifier(n_estimators=50).fit(
            concat_embeddings, labels).feature_importances_
      else:
        score_fn = getattr(skfs, f_name)
        all_scores = skfs.SelectPercentile(score_fn).fit(
            concat_embeddings, labels).scores_
    elif config_fs.type.startswith('connectivity'):
      # We don't care about query performance yet.
      new_config = copy.deepcopy(learning_config)
      # We don't do future selection in this innerloop.
      new_config.feature_selection.type = 'none'
      if new_config.feature_selection.is_overwrite:
        overwrite_dict = new_config.feature_selection.learning_config_overwrite
        for k, v in overwrite_dict.items():
          setattr(new_config, k, v)
      output_head = self._optimize_finetune(new_config, dataset, None,
                                            return_output_head=True)
      # TODO
      weights = output_head.layers[0].kernel

      if config_fs.type == 'connectivity_l1':
        all_scores = tf.reduce_sum(tf.abs(weights), axis=1)
      elif config_fs.type == 'connectivity_l2layer':
        if learning_config.group_lrp_is_embedding:
          # Here we match the groups used in embedding-based
          # group-regularization.
          new_scores = []
          for group in tf.split(weights, self.embedding_sizes, axis=0):
            score = tf.norm(group, axis=1, ord=2)
            group_norm = tf.norm(tf.reshape(group, [-1]), ord=2)
            new_scores.append(tf.ones_like(score) * group_norm)
          all_scores = tf.concat(new_scores, 0)
        else:
          # This is regular feature wise calculation, followed by averaging.
          all_scores = tf.norm(weights, axis=1, ord=2)
          # Score of each feature is equal to the layer score.
          new_scores = [
              tf.ones_like(score) * tf.reduce_mean(score) for score
              in tf.split(all_scores, self.embedding_sizes)]
          all_scores = tf.concat(new_scores, 0)
      elif config_fs.type == 'connectivity_l2':
        all_scores = tf.reduce_sum(weights**2, axis=1)
      elif config_fs.type == 'connectivity_linf':
        all_scores = tf.reduce_max(tf.abs(weights), axis=1)
      else:
        raise ValueError(f'config_fs.type: {config_fs.type} not valid')
      del output_head, weights
    else:
      raise ValueError(f'{config_fs.type} is not valid')
    return all_scores

  def _select_features(self, dataset, learning_config):
    config_fs = learning_config.feature_selection
    if config_fs.type == 'none':
      return None, None
    if config_fs.average_over_k > 1:
      all_scores = []
      for _ in range(config_fs.average_over_k):
        all_scores.append(self._calculate_scores(learning_config, dataset))
      all_scores = tf.reduce_mean(tf.stack(all_scores), 0)
    else:
      all_scores = self._calculate_scores(learning_config, dataset)
    kept_indices_all = self._select_fraction(
        all_scores, config_fs.keep_fraction, config_fs.keep_fraction_offset,
        mean_interpolation_coef=config_fs.mean_interpolation_coef)
    _, mean_scores = self._interpolate_scores_towards_mean(all_scores, 1.)
    selected_feature_indices = self._broadcast_indices(kept_indices_all)
    return selected_feature_indices, mean_scores

  def evaluate(self, learning_config, support_dataset, query_dataset,
               fs_dataset=None):
    """Performs evaluation on an episode.

    Args:
      learning_config: a `ConfigDict` specifying the learning configuration.
      support_dataset: a `tf.data.Dataset` for the support set.
      query_dataset: a `tf.data.Dataset` for the query set.
      fs_dataset: dataset or None. If given, features are
        selected using the datasets given.

    Returns:
      metrics: dict mapping metric names to metrics.
    """
    # Maybe select features.
    if fs_dataset:
      selected_feature_indices, mean_scores = self._select_features(
          fs_dataset, learning_config)
    else:
      selected_feature_indices, mean_scores = self._select_features(
          support_dataset, learning_config)
    metrics = self._optimize_finetune(
        learning_config, support_dataset, query_dataset,
        selected_feature_indices=selected_feature_indices)
    return_dict = self._process_metrics(metrics)

    if selected_feature_indices:
      for backbone_name, sfi, mean_score in zip(
          self.backbone_names, selected_feature_indices, mean_scores):
        return_dict[f'fs_count_{backbone_name}/'] = tf.size(sfi).numpy()
        return_dict[f'fs_meanscore_{backbone_name}/'] = mean_score.numpy()
        return_dict[f'pickle_sfi_{backbone_name}'] = sfi.numpy()
    return return_dict


text:
package org.apache.hadoop.hbase.replication.regionserver;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.SmallTests;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
import org.apache.hadoop.hbase.replication.ReplicationPeers;
import org.apache.hadoop.hbase.replication.regionserver.ReplicationSinkManager.SinkPeer;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.google.common.collect.Lists;

@Category(SmallTests.class)
public class TestReplicationSinkManager {

  private static final String PEER_CLUSTER_ID = "PEER_CLUSTER_ID";

  private ReplicationPeers replicationPeers;
  private ReplicationSinkManager sinkManager;

  @Before
  public void setUp() {
    replicationPeers = mock(ReplicationPeers.class);
    sinkManager = new ReplicationSinkManager(mock(HConnection.class),
                      PEER_CLUSTER_ID, replicationPeers, new Configuration());
  }

  @Test
  public void testChooseSinks() {
    List<ServerName> serverNames = Lists.newArrayList();
    for (int i = 0; i < 20; i++) {
      serverNames.add(mock(ServerName.class));
    }

    when(replicationPeers.getRegionServersOfConnectedPeer(PEER_CLUSTER_ID))
          .thenReturn(serverNames);

    sinkManager.chooseSinks();

    assertEquals(2, sinkManager.getSinks().size());

  }

  @Test
  public void testChooseSinks_LessThanRatioAvailable() {
    List<ServerName> serverNames = Lists.newArrayList(mock(ServerName.class),
      mock(ServerName.class));

    when(replicationPeers.getRegionServersOfConnectedPeer(PEER_CLUSTER_ID))
          .thenReturn(serverNames);

    sinkManager.chooseSinks();

    assertEquals(1, sinkManager.getSinks().size());
  }

  @Test
  public void testReportBadSink() {
    ServerName serverNameA = mock(ServerName.class);
    ServerName serverNameB = mock(ServerName.class);
    when(replicationPeers.getRegionServersOfConnectedPeer(PEER_CLUSTER_ID)).thenReturn(
      Lists.newArrayList(serverNameA, serverNameB));

    sinkManager.chooseSinks();
    // Sanity check
    assertEquals(1, sinkManager.getSinks().size());

    SinkPeer sinkPeer = new SinkPeer(serverNameA, mock(AdminService.BlockingInterface.class));

    sinkManager.reportBadSink(sinkPeer);

    // Just reporting a bad sink once shouldn't have an effect
    assertEquals(1, sinkManager.getSinks().size());

  }

  /**
   * Once a SinkPeer has been reported as bad more than BAD_SINK_THRESHOLD times, it should not
   * be replicated to anymore.
   */
  @Test
  public void testReportBadSink_PastThreshold() {
    List<ServerName> serverNames = Lists.newArrayList();
    for (int i = 0; i < 20; i++) {
      serverNames.add(mock(ServerName.class));
    }
    when(replicationPeers.getRegionServersOfConnectedPeer(PEER_CLUSTER_ID))
          .thenReturn(serverNames);

    sinkManager.chooseSinks();
    // Sanity check
    assertEquals(2, sinkManager.getSinks().size());

    ServerName serverName = sinkManager.getSinks().get(0);

    SinkPeer sinkPeer = new SinkPeer(serverName, mock(AdminService.BlockingInterface.class));

    for (int i = 0; i <= ReplicationSinkManager.DEFAULT_BAD_SINK_THRESHOLD; i++) {
      sinkManager.reportBadSink(sinkPeer);
    }

    // Reporting a bad sink more than the threshold count should remove it
    // from the list of potential sinks
    assertEquals(1, sinkManager.getSinks().size());
  }

  @Test
  public void testReportBadSink_DownToZeroSinks() {
    List<ServerName> serverNames = Lists.newArrayList();
    for (int i = 0; i < 20; i++) {
      serverNames.add(mock(ServerName.class));
    }
    when(replicationPeers.getRegionServersOfConnectedPeer(PEER_CLUSTER_ID))
          .thenReturn(serverNames);

    sinkManager.chooseSinks();
    // Sanity check

    List<ServerName> sinkList = sinkManager.getSinks();
    assertEquals(2, sinkList.size());

    ServerName serverNameA = sinkList.get(0);
    ServerName serverNameB = sinkList.get(1);

    SinkPeer sinkPeerA = new SinkPeer(serverNameA, mock(AdminService.BlockingInterface.class));
    SinkPeer sinkPeerB = new SinkPeer(serverNameB, mock(AdminService.BlockingInterface.class));

    for (int i = 0; i <= ReplicationSinkManager.DEFAULT_BAD_SINK_THRESHOLD; i++) {
      sinkManager.reportBadSink(sinkPeerA);
      sinkManager.reportBadSink(sinkPeerB);
    }

    // We've gone down to 0 good sinks, so the replication sinks
    // should have been refreshed now
    assertEquals(2, sinkManager.getSinks().size());
  }

}


text:
namespace WomanNS
{
	const int   WIDTH = 70;
	const int   HEIGHT = 70;
	const int   X = GAME_WIDTH / 2 - WIDTH / 2;
	const int   Y = GAME_HEIGHT - HEIGHT+23;
	const float ROTATION_RATE = (float)PI;
	const float SPEED = 100;
	const float MASS = 300.0f;
	enum DIRECTION { NONE, LEFT, RIGHT, UP };
	const int   TEXTURE_COLS = 4;
	const int   WOMAN_FRONT_FRAME = 7;
	const int	WOMAN_BACK_FRAM = 6;
	const int	WOMAN_RIGHT_START_FRAME = 0;
	const int	WOMAN_RIGHT_END_FRAME = 2;
	const int	WOMAN_LEFT_START_FRAME = 3;
	const int	WOMAN_LEFT_END_FRAME = 5;
	const float WOMAN_ANIMATION_DELAY = 0.2f;
	const float TORPEDO_DAMAGE = 46;
	const float WOMAN_SCALE = 0.7f;
	const int MAX_BULLET_NUMBER = 30;
	const float DELAY_BULLET_TIME = 0.5f;
	const COLOR_ARGB WOMAN_SCOLE_COLOR = graphicsNS::ORANGE;
	const int SCORE_PANEL_Y = 10;
	const int SCORE_PANEL_X = 20;
}

class Woman : public Entity
{
private:
	float   oldX, oldY, oldAngle;
	float   rotation;
	WomanNS::DIRECTION direction;
	float   explosionTimer;
	bool    explosionOn;
	bool    engineOn;
	bool    shieldOn;
	Image   engine;
	Image   shield;
	Image   explosion;

public:
	Woman();

	virtual void draw();
	virtual bool initialize(Game *gamePtr, int width, int height, int ncols,
		TextureManager *textureM);
e
	void update(float frameTime);

	void setDirection(WomanNS::DIRECTION dr)
	{
		this->direction = dr;
	}

	WomanNS::DIRECTION getDirection()
	{
		return this->direction;
	}

};
#endif


text:
title: Ribbon UI
page_title: Ribbon UI - WinForms RichTextEditor Control
description: WinForms RichTextEditorRibbonUI is a ribbon control that has been wired to work with the API that RichTextEditor exposes.
slug: winforms/richtexteditor-/ui-for-applying-rich-text-formatting/ribbon-ui
tags: ribbon,ui
published: True
position: 0
previous_url: richtexteditor-ui-for-applying-rich-text-formatting-ribbon-ui
---

# Ribbon UI

This topic explains how the predefined UI of __RadRichTextEditor - RadRichTextEditorRibbonUI__ - can be used.

__RadRichTextEditorRibbonUI__ is a ribbon control that has been wired to work with the API that **RadRichTextEditor** exposes.

![richtexteditor-ui-for-applying-rich-text-formatting-ribbon-ui 001](images/richtexteditor-ui-for-applying-rich-text-formatting-ribbon-ui001.png)

## Using RadRichTextEditorRibbonUI

__RadRichTextEditorRibbonUI__ can be found in the Toolbox of Visual Studio, if you have installed the controls automatically. In order to use it, drag an instance of the __RadRichTextEditorRibbonUI__ in the designer area and drop it. After this you can set the associated **RadRichTextEditor** by using the smart tag.

>caption RichTextEditorRibbonBar's smart tag

![richtexteditor-ui-for-applying-rich-text-formatting-ribbon-ui 002](images/richtexteditor-ui-for-applying-rich-text-formatting-ribbon-ui002.png)

You can automatically add a **RadRichTextEditorRibbonUI** by using the __RadRichTextEditor__ smart tag as well.

>caption RadRichTextEditor's smart tag

![richtexteditor-ui-for-applying-rich-text-formatting-ribbon-ui 003](images/richtexteditor-ui-for-applying-rich-text-formatting-ribbon-ui003.png)

# See Also

* [Localization]({%slug winforms/richtexteditor/localization%})
* [Custom Save Button in RichTextEditorRibbonBar]({%slug richtext-ribbon-ui-custom-save%})


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Me20.Contracts.Events
{
    public interface IContentAddedByUserEvent : IHaveUserName, IHaveContentUri
    {
    }
}


text:
package org.apache.shardingsphere.infra.database.metadata.dialect;

import org.apache.shardingsphere.infra.database.metadata.UnrecognizedDatabaseURLException;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public final class OpenGaussDataSourceMetaDataTest {

    @Test
    public void assertNewConstructorWithSimpleJdbcUrl() {
        PostgreSQLDataSourceMetaData actual = new PostgreSQLDataSourceMetaData("jdbc:openGauss://127.0.0.1/foo_ds");
        assertThat(actual.getHostname(), is("127.0.0.1"));
        assertThat(actual.getPort(), is(5432));
        assertThat(actual.getCatalog(), is("foo_ds"));
        assertNull(actual.getSchema());
        assertTrue(actual.getQueryProperties().isEmpty());
    }

    @Test
    public void assertNewConstructorWithComplexJdbcUrl() {
        PostgreSQLDataSourceMetaData actual = new PostgreSQLDataSourceMetaData("jdbc:openGauss://127.0.0.1:9999,127.0.0.2:9999,127.0.0.3:9999/foo_ds?targetServerType=master");
        assertThat(actual.getHostname(), is("127.0.0.1"));
        assertThat(actual.getPort(), is(9999));
        assertThat(actual.getCatalog(), is("foo_ds"));
        assertNull(actual.getSchema());
        assertThat(actual.getQueryProperties().size(), is(1));
        assertThat(actual.getQueryProperties().getProperty("targetServerType"), is("master"));
    }

    @Test(expected = UnrecognizedDatabaseURLException.class)
    public void assertNewConstructorFailure() {
        new PostgreSQLDataSourceMetaData("jdbc:openGauss:xxxxxxxx");
    }
}


text: from .dnlcb import DynamicNegativeLowerConfidenceBound


text:
PORTNAME=	Microsoft.Extensions.Localization.Abstractions
PORTVERSION=	1.0.0.0

GH_PROJECT=	Localization

.include <../../dotnet/aspnet/Makefile.common>


text:
class Foswipe::CommentsPolicy < Foswipe::ApplicationPolicy
  attr_reader :user, :comment
  def initialize(user, comment)
    @user = user
    @comment = comment
  end

  def index?
    @user.admin_or_agent?
  end

  def show?
    true
  end

  def new?
    true
  end

  def edit?
    true
  end

  def create?
    true
  end

  def update?
    true
  end

  def destroy?
    true
  end
end


text:
package com.craftthatblock.ctbapi;

/**
 * @author CraftThatBlock
 */
public class NumberUtils {
	/**
	 * Check if string is integer
	 *
	 * @param s Input
	 * @return boolean
	 */
	public static boolean isInteger(String s) {
		try {
			Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return false;
		}
		return true;
	}

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>vue-map</title>


text:
namespace Jal.Factory
{
    public class NullObjectFactoryInterceptor : AbstractObjectFactoryInterceptor
    {

    }
}


text:
'''
Created on Jan 10, 2011

@author: Mark V Systems Limited
(c) Copyright 2011 Mark V Systems Limited, All rights reserved.
'''
from arelle import ViewFile, XbrlConst, XmlUtil
from collections import defaultdict

def viewFacts(modelXbrl, outfile, lang=None, labelrole=None, cols=None):
    modelXbrl.modelManager.showStatus(_("viewing facts"))
    view = ViewFacts(modelXbrl, outfile, labelrole, lang, cols)
    view.view(modelXbrl.modelDocument)
    view.close()

class ViewFacts(ViewFile.View):
    def __init__(self, modelXbrl, outfile, labelrole, lang, cols):
        super(ViewFacts, self).__init__(modelXbrl, outfile, "Fact List", lang)
        self.labelrole = labelrole
        self.cols = cols

    def view(self, modelDocument):
        if self.cols:
            if isinstance(self.cols,str): self.cols = self.cols.replace(',',' ').split()
            unrecognizedCols = []
            for col in self.cols:
                if col not in ("Label","Name","contextRef","unitRef","Dec","Prec","Lang","Value","EntityScheme","EntityIdentifier","Period","Dimensions"):
                    unrecognizedCols.append(col)
            if unrecognizedCols:
                self.modelXbrl.error("arelle:unrecognizedFactListColumn",
                                     _("Unrecognized columns: %(cols)s"),
                                     modelXbrl=self.modelXbrl, cols=','.join(unrecognizedCols))
            if "Period" in self.cols:
                i = self.cols.index("Period")
                self.cols[i:i+1] = ["Start", "End/Instant"]
        else:
            self.cols = ["Label","contextRef","unitRef","Dec","Prec","Lang","Value"]
        col0 = self.cols[0]
        if col0 not in ("Label", "Name"):
            self.modelXbrl.error("arelle:firstFactListColumn",
                                 _("First column must be Label or Name: %(col1)s"),
                                 modelXbrl=self.modelXbrl, col1=col0)
        self.isCol0Label = col0 == "Label"
        self.maxNumDims = 1
        self.tupleDepth(self.modelXbrl.facts, 0)
        if "Dimensions" == self.cols[-1]:
            lastColSpan = self.maxNumDims
        else:
            lastColSpan = None
        self.addRow(self.cols, asHeader=True, lastColSpan=lastColSpan)
        self.viewFacts(self.modelXbrl.facts, 0)

    def tupleDepth(self, modelFacts, indentedCol):
        if indentedCol > self.treeCols: self.treeCols = indentedCol
        for modelFact in modelFacts:
            if modelFact.context is not None:
                numDims = len(modelFact.context.qnameDims) * 2
                if numDims > self.maxNumDims: self.maxNumDims = numDims
            self.tupleDepth(modelFact.modelTupleFacts, indentedCol + 1)

    def viewFacts(self, modelFacts, indent):
        for modelFact in modelFacts:
            concept = modelFact.concept
            xmlRowElementName = 'item'
            attr = {"name": str(modelFact.qname)}
            if concept is not None and self.isCol0Label:
                lbl = concept.label(preferredLabel=self.labelrole, lang=self.lang, linkroleHint=XbrlConst.defaultLinkRole)
                xmlCol0skipElt = False # provide label as a row element
            else:
                lbl = (modelFact.qname or modelFact.prefixedName) # defective inline facts may have no qname
                xmlCol0skipElt = True # name is an attribute, don't do it also as an element
            cols = [lbl]
            if concept is not None:
                if modelFact.isItem:
                    for col in self.cols[1:]:
                        if col == "Label": # label or name may be 2nd to nth col if name or label is 1st col
                            cols.append( concept.label(preferredLabel=self.labelrole, lang=self.lang) )
                        elif col == "Name":
                            cols.append( modelFact.qname )
                        elif col == "contextRef":
                            cols.append( modelFact.contextID )
                        elif col == "unitRef":
                            cols.append( modelFact.unitID )
                        elif col == "Dec":
                            cols.append( modelFact.decimals )
                        elif col == "Prec":
                            cols.append( modelFact.precision )
                        elif col == "Lang":
                            cols.append( modelFact.xmlLang )
                        elif col == "Value":
                            cols.append( "(nil)" if modelFact.xsiNil == "true" else modelFact.effectiveValue.strip() )
                        elif col == "EntityScheme":
                            cols.append( modelFact.context.entityIdentifier[0] )
                        elif col == "EntityIdentifier":
                            cols.append( modelFact.context.entityIdentifier[1] )
                        elif col == "Start":
                            cols.append( XmlUtil.text(XmlUtil.child(modelFact.context.period, XbrlConst.xbrli, "startDate")) )
                        elif col == "End/Instant":
                            cols.append( XmlUtil.text(XmlUtil.child(modelFact.context.period, XbrlConst.xbrli, ("endDate","instant"))) )
                        elif col == "Dimensions":
                            for dimQname in sorted(modelFact.context.qnameDims.keys()):
                                cols.append( str(dimQname) )
                                cols.append( str(modelFact.context.dimMemberQname(dimQname)) )
                elif modelFact.isTuple:
                    xmlRowElementName = 'tuple'
            self.addRow(cols, treeIndent=indent, xmlRowElementName=xmlRowElementName, xmlRowEltAttr=attr, xmlCol0skipElt=xmlCol0skipElt)
            self.viewFacts(modelFact.modelTupleFacts, indent + 1)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Inches_to__Centimeters
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("a = ");
            var inches = double.Parse(Console.ReadLine());
            var centimeters = inches * 2.54;
            Console.Write("Centimeters = ");
            Console.WriteLine(centimeters);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 321911 $ -->

<refentry xml:id="quickhashintstringhash.delete" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>QuickHashIntStringHash::delete</refname>
  <refpurpose>This method deletes am entry from the hash</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <type>bool</type><methodname>QuickHashIntStringHash::delete</methodname>
   <methodparam><type>int</type><parameter>key</parameter></methodparam>
  </methodsynopsis>
  <para>
   This method deletes an entry from the hash, and returns whether the entry was
   deleted or not. Associated memory structures will not be freed immediately,
   but rather when the hash itself is freed.
  </para>
  <para>
   Elements can not be deleted when the hash is used in an iterator. The
   method will not throw an exception, but simply return &false; like would
   happen with any other deletion failure.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>key</parameter></term>
     <listitem>
      <para>
       The key of the entry to delete.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   &true; when the entry was deleted, and &false; if the entry was not deleted.
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title><function>QuickHashIntStringHash::delete</function> example</title>
    <programlisting role="php">
<![CDATA[<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "five" ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>]]>
    </programlisting>
    &example.outputs.similar;
    <screen>
<![CDATA[
bool(false)
bool(true)
bool(true)
bool(false)
bool(false)
]]>
    </screen>
   </example>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package org.fest.assertions.api;

import static org.fest.test.ExpectedException.none;
import static org.junit.Assert.assertSame;

import org.fest.test.ExpectedException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

/**
 * Tests for {@link CharacterAssert#isNotEqualTo(char)}.
 *
 * @author Alex Ruiz
 */
public class CharacterAssert_isNotEqualTo_char_Test {
  @Rule
  public ExpectedException thrown = none();
  private CharacterAssert assertions;
  private Character actual = new Character('a');
  private char expected = 'b';

  @Before
  public void setUp() {
    assertions = new CharacterAssert(actual);
  }

  @Test
  public void should_pass_if_actual_is_equal_to_expected() {
    assertions.isNotEqualTo(expected);
  }

  @Test
  public void should_return_this() {
    CharacterAssert returned = assertions.isNotEqualTo(expected);
    assertSame(assertions, returned);
  }

  @Test
  public void should_throw_error_if_actual_is_null() {
    thrown.expect(AssertionError.class);
    actual = null;
    assertions = new CharacterAssert(actual);
    assertions.isNotEqualTo(expected);
  }

  @Test
  public void should_fail_if_actual_is_not_equal_to_expected() {
    thrown.expect(AssertionError.class);
    expected = 'a';
    assertions.isNotEqualTo(expected);
  }
}


text:
id="<?php echo $view->escape($id) ?>"
name="<?php echo $view->escape($full_name) ?>"
<?php if ($read_only): ?>readonly="readonly" <?php endif ?>
<?php if ($disabled): ?>disabled="disabled" <?php endif ?>
<?php if ($required): ?>required="required" <?php endif ?>
<?php if ($max_length): ?>maxlength="<?php echo $view->escape($max_length) ?>" <?php endif ?>
<?php if ($pattern): ?>pattern="<?php echo $view->escape($pattern) ?>" <?php endif ?>
<?php foreach ($attr as $k => $v): ?>
    <?php printf('%s="%s" ', $view->escape($k), $view->escape(in_array($k, array('placeholder', 'title')) ? $view['translator']->trans($v, array(), $translation_domain) : $v)) ?>
<?php endforeach; ?>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!-- BEGIN PAGE LEVEL PLUGINS -->
        <link href="/assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
        <link href="/assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
        <!-- END PAGE LEVEL PLUGINS -->
        <!-- BEGIN THEME GLOBAL STYLES -->
        <link href="/assets/global/css/components.min.css" rel="stylesheet" id="style_components" type="text/css" />
        <link href="/assets/global/css/plugins.min.css" rel="stylesheet" type="text/css" />
        <!-- END THEME GLOBAL STYLES -->
        <!-- BEGIN PAGE LEVEL STYLES -->
        <!-- END PAGE LEVEL STYLES -->
        <!-- BEGIN THEME LAYOUT STYLES -->
        <link href="/assets/layouts/layout/css/layout.min.css" rel="stylesheet" type="text/css" />
        <link href="/assets/layouts/layout/css/themes/<?php echo $this->session->tci->system['theme'] ?>.min.css" rel="stylesheet" type="text/css" id="style_color" />
        <link href="/assets/layouts/layout/css/custom.min.css" rel="stylesheet" type="text/css" />
        <!-- END THEME LAYOUT STYLES -->
        <link rel="shortcut icon" href="favicon.ico" /> </head>
    <!-- END HEAD -->


text:
#ifdef _WINDOWS

#include "VoronoiFractureDemo.h"

///The 'createDemo' function is called from Bullet/Demos/OpenGL/Win32AppMain.cpp to instantiate this particular demo
DemoApplication*	createDemo()
{
	return new VoronoiFractureDemo();
}

#endif


text:
ig.module(
	'impact.animation'
)
.requires(
	'impact.timer',
	'impact.image'
)
.defines(function(){

ig.AnimationSheet = ig.Class.extend({
	width: 8,
	height: 8,
	image: null,

	init: function( path, width, height ) {
		this.width = width;
		this.height = height;

		this.image = new ig.Image( path );
	}
});

ig.Animation = ig.Class.extend({
	sheet: null,
	timer: null,

	sequence: [],
	flip: {x: false, y: false},
	pivot: {x: 0, y: 0},

	frame: 0,
	tile: 0,
	loopCount: 0,
	alpha: 1,
	angle: 0,

	init: function( sheet, frameTime, sequence, stop ) {
		this.sheet = sheet;
		this.pivot = {x: sheet.width/2, y: sheet.height/2 };
		this.timer = new ig.Timer();

		this.frameTime = frameTime;
		this.sequence = sequence;
		this.stop = !!stop;
		this.tile = this.sequence[0];
	},

	rewind: function() {
		this.timer.reset();
		this.loopCount = 0;
		this.tile = this.sequence[0];
		return this;
	},

	gotoFrame: function( f ) {
		this.timer.set( this.frameTime * -f );
		this.update();
	},

	gotoRandomFrame: function() {
		this.gotoFrame( Math.floor(Math.random() * this.sequence.length) )
	},

	update: function() {
		var frameTotal = Math.floor(this.timer.delta() / this.frameTime);
		this.loopCount = Math.floor(frameTotal / this.sequence.length);
		if( this.stop && this.loopCount > 0 ) {
			this.frame = this.sequence.length - 1;
		}
		else {
			this.frame = frameTotal % this.sequence.length;
		}
		this.tile = this.sequence[ this.frame ];
	},

	draw: function( targetX, targetY ) {
		var bbsize = Math.max(this.sheet.width, this.sheet.height);

		// On screen?
		if(
		   targetX > ig.system.width || targetY > ig.system.height ||
		   targetX + bbsize < 0 || targetY + bbsize < 0
		) {
			return;
		}

		if( this.alpha != 1) {
			ig.system.context.globalAlpha = this.alpha;
		}

		if( this.angle == 0 ) {
			this.sheet.image.drawTile(
				targetX, targetY,
				this.tile, this.sheet.width, this.sheet.height,
				this.flip.x, this.flip.y
			);
		}
		else {
			ig.system.context.save();
			ig.system.context.translate(
				ig.system.getDrawPos(targetX + this.pivot.x),
				ig.system.getDrawPos(targetY + this.pivot.y)
			);
			ig.system.context.rotate( this.angle );
			this.sheet.image.drawTile(
				-this.pivot.x, -this.pivot.y,
				this.tile, this.sheet.width, this.sheet.height,
				this.flip.x, this.flip.y
			);
			ig.system.context.restore();
		}

		if( this.alpha != 1) {
			ig.system.context.globalAlpha = 1;
		}
	}
});

});


text:
import json
import base64
import binascii
import re
import abc

try:
    from functools import singledispatch
except ImportError:  # pragma: nocover
    # future: remove when dropping support for Python 3.3
    # compat: backport of singledispatch module introduced in Python 3.4
    from singledispatch import singledispatch

from falcon import HTTPMissingHeader, HTTPBadRequest

class BaseUserStorage(metaclass=abc.ABCMeta):
    """Base user storage class that defines required API for user storages.

    All built-in graceful authentication middleware classes expect user storage
    to have compatible API. Custom authentication middlewares do not need
    to use storages.

    .. versionadded:: 0.4.0
    """

    @abc.abstractmethod
    def get_user(
        self, identified_with, identifier, req, resp, resource, uri_kwargs
    ):
        """Get user from the storage.

        Args:
            identified_with (str): instance of the authentication middleware
                that provided the ``identifier`` value.
            identifier (str): string that identifies the user (it is specific
                for every authentication middleware implementation).
            req (falcon.Request): the request object.
            resp (falcon.Response): the response object.
            resource (object): the resource object.
            uri_kwargs (dict): keyword arguments from the URI template.

        Returns:
            the deserialized user object. Preferably a ``dict`` but it is
            application-specific.
        """
        raise NotImplementedError  # pragma: nocover

    @classmethod
    def __subclasshook__(cls, klass):
        """Verify implicit class interface."""
        if cls is BaseUserStorage:
            if any("get_user" in B.__dict__ for B in klass.__mro__):
                return True
        return NotImplemented

class DummyUserStorage(BaseUserStorage):
    """A dummy storage that never returns users or returns specified default.

    This storage is part of :any:`Anonymous` authentication middleware.
    It may also be useful for testing purposes or to disable specific
    authentication middlewares through app configuration.

    Args:
        user: User object to return. Defaults to ``None`` (will never
        authenticate).

    .. versionadded:: 0.4.0
    """

    def __init__(self, user=None):
        """Initialize dummy storage."""
        self.user = user

    def get_user(
        self, identified_with, identifier, req, resp, resource, uri_kwargs
    ):
        """Return default user object."""
        return self.user

class IPRangeWhitelistStorage(BaseUserStorage):
    """Simple storage dedicated for :any:`XForwardedFor` authentication.

    This storage expects that authentication middleware return client address
    from its ``identify()`` method. For example usage see :any:`XForwardedFor`.
    Because it is IP range whitelist this storage it cannot distinguish
    different users' IP and always returns default user object. If you want to
    identify different users by their IP see :any:`KeyValueUserStorage`.

    Args:
        ip_range: Any object that supports ``in`` operator (i.e. implements the
            ``__cointains__`` method). The ``__contains__`` method should
            return ``True`` if identifier falls into specified whitelist.
            Tip: use ``iptools``.
        user: Default user object to return on successful authentication.

    .. versionadded:: 0.4.0
    """

    def __init__(self, ip_range, user):
        """Initialize IP whitelist storage."""
        self.ip_range = ip_range
        self.user = user

    def get_user(
        self, identified_with, identifier, req, resp, resource, uri_kwargs
    ):
        """Return default user object.

        .. note::
            This implementation expects that ``identifier`` is an user address.
        """
        if identifier in self.ip_range:
            return self.user

class KeyValueUserStorage(BaseUserStorage):
    """Basic user storage using any key-value store as authentication backend.

    Client identities are stored as string under keys matching following
    template::

        <key_prefix>:<identified_with>:<identifier>

    Where:

    * ``<key_prefix>`` is the configured key prefix (same as the initialization
      argument),
    * ``<identified_with>`` is the name of authentication middleware that
      provided user identifier,
    * ``<identifier>`` is the identifier object that identifies the user.

    Note that this key scheme will work only for middlewares that return
    identifiers as single string objects. Also the ``<identifier>`` part
    of key template is a plain text value of without any hashing algorithm
    applied. It may not be secure enough to store user secrets that way.

    If you want to use this storage with middleware that uses more complex
    identifier format/objects (e.g. the :any:`Basic` class) you will have
    to register own identifier format in the :any:`hash_identifier` method.
    For details see the :any:`hash_identifier` method docstring or the
    :ref:`practical example <auth-practical-example>` section of the
    documentation.

    Args:
        kv_store: Key-value store client instance (e.g. Redis client object).
            The ``kv_store`` must provide at least two methods: ``get(key)``
            and ``set(key, value)``. The arguments and return values of these
            methods must be strings.
        key_prefix: key prefix used to store client identities.
        serialization: serialization object/module that uses the
            ``dumps()``/``loads()`` protocol. Defaults to ``json``.

    .. versionadded:: 0.4.0
    """

    def __init__(self, kv_store, key_prefix='users', serialization=None):
        """Initialize kv_store user storage."""
        self.kv_store = kv_store
        self.key_prefix = key_prefix
        self.serialization = serialization or json

    def _get_storage_key(self, identified_with, identifier):
        """Get key string for given user identifier in consistent manner."""
        return ':'.join((
            self.key_prefix, identified_with.name,
            self.hash_identifier(identified_with, identifier),
        ))

    @staticmethod
    @singledispatch
    def hash_identifier(identified_with, identifier):
        """Create hash from identifier to be used as a part of user lookup.

        This method is a ``singledispatch`` function. It allows to register
        new implementations for specific authentication middleware classes:

        .. code-block:: python

            from hashlib import sha1

            from graceful.authentication import KeyValueUserStorage, Basic

            @KeyValueUserStorage.hash_identifier.register(Basic)
            def _(identified_with, identifier):
                return ":".join((
                    identifier[0],
                    sha1(identifier[1].encode()).hexdigest(),
                ))

        Args:
            identified_with (str): name of the authentication middleware used
                to identify the user.
            identifier (str): user identifier string

        Return:
            str: hashed identifier string
        """
        if isinstance(identifier, str):
            return identifier
        else:
            raise TypeError(
                "User storage does not support this kind of identifier"
            )

    def get_user(
        self, identified_with, identifier, req, resp, resource, uri_kwargs
    ):
        """Get user object for given identifier.

        Args:
            identified_with (object): authentication middleware used
                to identify the user.
            identifier: middleware specifix user identifier (string or tuple
                in case of all built in authentication middleware classes).

        Returns:
            dict: user object stored in Redis if it exists, otherwise ``None``
        """
        stored_value = self.kv_store.get(
            self._get_storage_key(identified_with, identifier)
        )
        if stored_value is not None:
            user = self.serialization.loads(stored_value.decode())
        else:
            user = None

        return user

    def register(self, identified_with, identifier, user):
        """Register new key for given client identifier.

        This is only a helper method that allows to register new
        user objects for client identities (keys, tokens, addresses etc.).

        Args:
            identified_with (object): authentication middleware used
                to identify the user.
            identifier (str): user identifier.
            user (str): user object to be stored in the backend.
        """
        self.kv_store.set(
            self._get_storage_key(identified_with, identifier),
            self.serialization.dumps(user).encode(),
        )

class BaseAuthenticationMiddleware:
    """Base class for all authentication middleware classes.

    Args:
        user_storage (BaseUserStorage): a storage object used to retrieve
            user object using their identifier lookup.
        name (str): custom name of the authentication middleware useful
            for handling custom user storage backends. Defaults to middleware
            class name.

    .. versionadded:: 0.4.0
    """

    #: challenge returned in WWW-Authenticate header on non authorized
    #: requests.
    challenge = None

    #: defines if Authentication middleware requires valid storage
    #: object to identify users
    only_with_storage = False

    def __init__(self, user_storage=None, name=None):
        """Initialize authentication middleware."""
        self.user_storage = user_storage
        self.name = (
            name if name else self.__class__.__name__
        )

        if (
            self.only_with_storage and
            not isinstance(self.user_storage, BaseUserStorage)
        ):
            raise ValueError(
                "{} authentication middleware requires valid storage. Got {}."
                "".format(self.__class__.__name__, self.user_storage)
            )

    def process_resource(self, req, resp, resource, uri_kwargs=None):
        """Process resource after routing to it.

        This is basic falcon middleware handler.

        Args:
            req (falcon.Request): request object
            resp (falcon.Response): response object
            resource (object): resource object matched by falcon router
            uri_kwargs (dict): additional keyword argument from uri template.
                For ``falcon<1.0.0`` this is always ``None``
        """
        if 'user' in req.context:
            return

        identifier = self.identify(req, resp, resource, uri_kwargs)
        user = self.try_storage(identifier, req, resp, resource, uri_kwargs)

        if user is not None:
            req.context['user'] = user

        # if did not succeed then we need to add this to list of available
        # challenges.
        elif self.challenge is not None:
            req.context.setdefault(
                'challenges', list()
            ).append(self.challenge)

    def identify(self, req, resp, resource, uri_kwargs):
        """Identify the user that made the request.

        Args:
            req (falcon.Request): request object
            resp (falcon.Response): response object
            resource (object): resource object matched by falcon router
            uri_kwargs (dict): additional keyword argument from uri template.
                For ``falcon<1.0.0`` this is always ``None``

        Returns:
            object: a user object (preferably a dictionary).
        """
        raise NotImplementedError  # pragma: nocover

    def try_storage(self, identifier, req, resp, resource, uri_kwargs):
        """Try to find user in configured user storage object.

        Args:
            identifier: User identifier.

        Returns:
            user object.
        """
        if identifier is None:
            user = None

        # note: if user_storage is defined, always use it in order to
        #       authenticate user.
        elif self.user_storage is not None:
            user = self.user_storage.get_user(
                self, identifier, req, resp, resource, uri_kwargs
            )

        # note: some authentication middleware classes may not require
        #       to be initialized with their own user_storage. In such
        #       case this will always authenticate with "syntetic user"
        #       if there is a valid indentity.
        elif self.user_storage is None and not self.only_with_storage:
            user = {
                'identified_with': self,
                'identifier': identifier
            }

        else:  # pragma: nocover
            # note: this should not happen if the base class is properly
            #       initialized. Still, user can skip super().__init__() call.
            user = None

        return user

class Basic(BaseAuthenticationMiddleware):
    """Authenticate user with Basic auth as specified by `RFC 7617`_.

    Token authentication takes form of ``Authorization`` header in the
    following form::

        Authorization: Basic <credentials>

    Whre `<credentials>` is base64 encoded username and password separated by
    single colon charactes (refer to official RFC). Usernames must not contain
    colon characters!

    If client fails to authenticate on protected endpoint the response will
    include following challenge::

        WWW-Authenticate: Basic realm="<realm>"

    Where ``<realm>`` is the value of configured authentication realm.

    This middleware **must** be configured with ``user_storage`` that provides
    access to database of client API keys and their identities. Additionally.
    the ``identifier`` received by user storage in the ``get_user()`` method
    is a decoded ``<username>:<password>`` string. If you need to apply any
    hash function before hitting database in your user storage handler, you
    should split it using followitg code::

        username, _, password = identifier.partition(":")

    Args:
        realm (str): name of the protected realm. This can be only alphanumeric
            string with spaces (see: the ``REALM_RE`` pattern).
        user_storage (BaseUserStorage): a storage object used to retrieve
            user object using their identifier lookup.
        name (str): custom name of the authentication middleware useful
            for handling custom user storage backends. Defaults to middleware
            class name.

    .. versionadded:: 0.4.0

    .. _RFC 7617: https://tools.ietf.org/html/rfc7616
    """

    only_with_storage = True

    #: regular expression used to validate configured realm
    REALM_RE = re.compile(r"^[\w ]+$")

    def __init__(self, user_storage=None, name=None, realm="api"):
        """Initialize middleware and validate realm string."""
        if not self.REALM_RE.match(realm):
            raise ValueError(
                "realm argument should match '{}' regular expression"
                "".format(self.REALM_RE.pattern)
            )

        self.challenge = "Basic realm={}".format(realm)
        super(Basic, self).__init__(user_storage, name)

    def identify(self, req, resp, resource, uri_kwargs):
        """Identify user using Authenticate header with Basic auth."""
        header = req.get_header("Authorization", False)
        auth = header.split(" ") if header else None

        if auth is None or auth[0].lower() != 'basic':
            return None

        if len(auth) != 2:
            raise HTTPBadRequest(
                "Invalid Authorization header",
                "The Authorization header for Basic auth should be in form:\n"
                "Authorization: Basic <base64-user-pass>"
            )

        user_pass = auth[1]

        try:
            decoded = base64.b64decode(user_pass).decode()

        except (TypeError, UnicodeDecodeError, binascii.Error):
            raise HTTPBadRequest(
                "Invalid Authorization header",
                "Credentials for Basic auth not correctly base64 encoded."
            )

        username, _, password = decoded.partition(":")
        return username, password

class XAPIKey(BaseAuthenticationMiddleware):
    """Authenticate user with ``X-Api-Key`` header.

    The X-Api-Key authentication takes a form of ``X-Api-Key`` header in the
    following form::

        X-Api-Key: <key_value>

    Where ``<key_value>`` is a secret string known to both client and server.
    Example of valid header::

        X-Api-Key: 6fa459ea-ee8a-3ca4-894e-db77e160355e

    If client fails to authenticate on protected endpoint the response will
    include following challenge::

        WWW-Authenticate: X-Api-Key

    .. note::
        This method functionally equivalent to :any:`Token` and is included
        only to ease migration of old applications that could use such
        authentication method in past. If you're building new API and require
        only simple token-based authentication you should prefere
        :any:`Token` middleware.

    This middleware **must** be configured with ``user_storage`` that provides
    access to database of client API keys and their identities.

    .. versionadded:: 0.4.0
    """

    challenge = 'X-Api-Key'
    only_with_storage = True

    def identify(self, req, resp, resource, uri_kwargs):
        """Initialize X-Api-Key authentication middleware."""
        try:
            return req.get_header('X-Api-Key', True)
        except (KeyError, HTTPMissingHeader):
            pass

class Token(BaseAuthenticationMiddleware):
    """Authenticate user using Token authentication.

    Token authentication takes form of ``Authorization`` header::

        Authorization: Token <token_value>

    Where ``<token_value>`` is a secret string known to both client and server.
    Example of valid header::

        Authorization: Token 6fa459ea-ee8a-3ca4-894e-db77e160355e

    If client fails to authenticate on protected endpoint the response will
    include following challenge::

        WWW-Authenticate: Token

    This middleware **must** be configured with ``user_storage`` that provides
    access to database of client tokens and their identities.

    .. versionadded:: 0.4.0
    """

    challenge = 'Token'
    only_with_storage = True

    def identify(self, req, resp, resource, uri_kwargs):
        """Identify user using Authenticate header with Token auth."""
        header = req.get_header('Authorization', False)
        auth = header.split(' ') if header else None

        if auth is None or auth[0].lower() != 'token':
            return None

        if len(auth) != 2:
            raise HTTPBadRequest(
                "Invalid Authorization header",
                "The Authorization header for Token auth should be in form:\n"
                "Authorization: Token <token_value>"
            )

        return auth[1]

class XForwardedFor(BaseAuthenticationMiddleware):
    """Authenticate user with ``X-Forwarded-For`` header or remote address.

    Args:
        remote_address_fallback (bool): Use fallback to ``REMOTE_ADDR`` value
            from WSGI environment dictionary if ``X-Forwarded-For`` header is
            not available. Defaults to ``False``.

    This authentication middleware is usually used with the
    :any:`IPRangeWhitelistStorage` e.g:

    .. code-block:: python

        from iptools import IPRangeList
        import falcon

        from graceful import authentication

        IP_WHITELIST = IpRangeList(
            '127.0.0.1',
            # ...
        )

        auth_middleware = authentication.XForwardedFor(
            user_storage=authentication.IPWRangehitelistStorage(
                IP_WHITELIST, user={"username": "internal"}
            )
        )

        api = application = falcon.API(middleware=[auth_middleware])

    .. note::
        Using this middleware class is **highly unrecommended** if you
        are not able to ensure that contents of ``X-Forwarded-For`` header
        can be trusted. This requires proper reverse proxy and network
        configuration. It is also recommended to at least use the static
        :any:`IPRangeWhitelistStorage` as the user storage.

    .. versionadded:: 0.4.0
    """

    challenge = None
    only_with_storage = False

    def __init__(
        self, user_storage=None, name=None, remote_address_fallback=False
    ):
        """Initialize middleware and set default arguments."""
        super().__init__(user_storage, name)
        self.remote_address_fallback = remote_address_fallback

    def _get_client_address(self, req):
        """Get address from ``X-Forwarded-For`` header or use remote address.

        Remote address is used if the ``X-Forwarded-For`` header is not
        available. Note that this may not be safe to depend on both without
        proper authorization backend.

        Args:
            req (falcon.Request): falcon.Request object.

        Returns:
            str: client address.
        """
        try:
            forwarded_for = req.get_header('X-Forwarded-For', True)
            return forwarded_for.split(',')[0].strip()
        except (KeyError, HTTPMissingHeader):
            return (
                req.env.get('REMOTE_ADDR') if self.remote_address_fallback
                else None
            )

    def identify(self, req, resp, resource, uri_kwargs):
        """Identify client using his address."""
        return self._get_client_address(req)

class Anonymous(BaseAuthenticationMiddleware):
    """Dummy authentication middleware that authenticates every request.

    It makes every every request authenticated with default value of
    anonymous user. This authentication middleware may be used in order
    to simplify custom authorization code since it will ensure that
    every request context will have the ``'user'`` variable defined.

    .. note::
        This middleware will always add the default user to the request
        context if no other previous authentication middleware resolved.
        So if this middleware is used it makes no sense to:

        * Use the :any:`authentication_required` decorator.
        * Define any other authentication middleware after this one.

    Args:
        user: Default anonymous user object.

    .. versionadded:: 0.4.0
    """

    challenge = None
    only_with_storage = True

    def __init__(self, user):
        """Initialize anonymous authentication middleware."""
        # note: DummyUserStorage allows to always return the same user
        #       object that was passed as initialization value
        super().__init__(user_storage=DummyUserStorage(user))

    def identify(self, req, resp, resource, uri_kwargs):
        """Identify user with a dummy sentinel value."""
        # note: this is just a sentinel value to trigger successful
        #       lookup in the dummy user storage
        return ...


text:
typedef struct Pair Pair, *PairPointer;

struct Pair {
    void *fst, *snd;
};

// The Pair of the specified pointers.
Pair Pair_initialize(void *fst, void *snd);

// The pointer to the pair of the specified pointer.
PairPointer Pair_create(void *fst, void *snd);

#endif