text:
package org.littlewings.javaee7.beanvalidation

import scala.collection.JavaConverters._

import javax.validation.{ConstraintViolation, Validation}

import org.scalatest.FunSpec
import org.scalatest.Matchers._

class InterrelationConstraintSpec extends FunSpec {
  describe("InterrelationConstraint Spec") {
    it("invalid manager") {
      val employee = new Employee
      employee.name = "次郎"
      employee.post = "課長"
      employee.salary = 30000

      val factory = Validation.buildDefaultValidatorFactory
      val validator = factory.getValidator

      val constraintViolations =
        validator
          .validate(employee)
          .toArray(Array.empty[ConstraintViolation[Any]])
          .sortWith(_.getPropertyPath.toString < _.getPropertyPath.toString)

      constraintViolations should have size (1)
      constraintViolations(0).getPropertyPath.toString should be("salary")
      constraintViolations(0).getMessage should be("課長の給料は、50000以上でなければなりません")
    }

    it("valid manager") {
      val employee = new Employee
      employee.name = "次郎"
      employee.post = "課長"
      employee.salary = 50000

      val factory = Validation.buildDefaultValidatorFactory
      val validator = factory.getValidator

      val constraintViolations =
        validator
          .validate(employee)
          .toArray(Array.empty[ConstraintViolation[Any]])
          .sortWith(_.getPropertyPath.toString < _.getPropertyPath.toString)

      constraintViolations should be(empty)
    }

    it("invalid general manager") {
      val employee = new Employee
      employee.name = "次郎"
      employee.post = "部長"
      employee.salary = 90000

      val factory = Validation.buildDefaultValidatorFactory
      val validator = factory.getValidator

      val constraintViolations =
        validator
          .validate(employee)
          .toArray(Array.empty[ConstraintViolation[Any]])
          .sortWith(_.getPropertyPath.toString < _.getPropertyPath.toString)

      constraintViolations should have size (1)
      constraintViolations(0)
        .getPropertyPath
        .iterator
        .asScala
        .map(_.toString)
        .toArray should contain only("post", "salary")
      constraintViolations(0).getMessage should be("部長の給料は、100000以上でなければなりません")
    }

    it("valid general manager") {
      val employee = new Employee
      employee.name = "次郎"
      employee.post = "部長"
      employee.salary = 100000

      val factory = Validation.buildDefaultValidatorFactory
      val validator = factory.getValidator

      val constraintViolations =
        validator
          .validate(employee)
          .toArray(Array.empty[ConstraintViolation[Any]])
          .sortWith(_.getPropertyPath.toString < _.getPropertyPath.toString)

      constraintViolations should be(empty)
    }

    it("invalid staff") {
      val employee = new Employee
      employee.name = "次郎"
      employee.post = "平社員"
      employee.salary = 50000

      val factory = Validation.buildDefaultValidatorFactory
      val validator = factory.getValidator

      val constraintViolations =
        validator
          .validate(employee)
          .toArray(Array.empty[ConstraintViolation[Any]])
          .sortWith(_.getPropertyPath.toString < _.getPropertyPath.toString)

      constraintViolations should have size (1)
      constraintViolations(0).getPropertyPath.toString should be("salary")
      constraintViolations(0).getMessage should be("平社員の給料は、50000より低くなければなりません")
    }

    it("valid staff") {
      val employee = new Employee
      employee.name = "次郎"
      employee.post = "平社員"
      employee.salary = 30000

      val factory = Validation.buildDefaultValidatorFactory
      val validator = factory.getValidator

      val constraintViolations =
        validator
          .validate(employee)
          .toArray(Array.empty[ConstraintViolation[Any]])
          .sortWith(_.getPropertyPath.toString < _.getPropertyPath.toString)

      constraintViolations should be(empty)
    }
  }
}


text:
package com.joy.app.activity.sample;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;

import com.android.library.ui.activity.BaseTabActivity;
import com.android.library.ui.fragment.BaseUiFragment;
import com.android.library.utils.CollectionUtil;
import com.android.library.view.fresco.FrescoIv;
import com.joy.app.BuildConfig;
import com.joy.app.JoyApplication;
import com.joy.app.R;
import com.joy.app.activity.hotel.CityHotelListActivity;
import com.tbruyelle.rxpermissions.RxPermissions;

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

/**
 * Created by KEVIN.DAI on 15/11/10.
 */
public class TabTestActivity extends BaseTabActivity {

    public static void startActivity(Activity act) {

        if (act != null)
            act.startActivity(new Intent(act, TabTestActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

//        if (savedInstanceState != null) {
//
//            final FragmentManager fm = getSupportFragmentManager();
//            final Fragment f1 = fm.getFragment(savedInstanceState, MvpTestFragment.TAG);
//            final Fragment f2 = fm.getFragment(savedInstanceState, MvpTestRvFragment.TAG);
//            final Fragment f3 = fm.getFragment(savedInstanceState, RvTestFragment.TAG);
//
//            LogMgr.d("daisw", "onCreate\n" +
//                    f1 + "\n" +
//                    f2 + "\n" +
//                    f3);
//
//            initActComponent(f1, f2);
//        } else {

        initActComponent(getFragment(1), getFragment(2));
//        }

        RxPermissions.getInstance(this)
                .request(Manifest.permission.READ_PHONE_STATE)
                .subscribe(granted -> {
                    if (granted) {// Always true pre-M

                        showToast("granted");
                    } else {

                        showToast("not granted");
                    }
                });
    }

//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//
//        super.onSaveInstanceState(outState);
//
//        final FragmentManager fm = getSupportFragmentManager();
//        final BaseUiFragment f1 = getFragment(0);
//        final BaseUiFragment f2 = getFragment(1);
//        final BaseUiFragment f3 = getFragment(2);
//
//        LogMgr.i("daisw", "onSaveInstanceState\n" +
//                f1.isAdded() + " - " + f1 + "\n" +
//                f2.isAdded() + " - " + f2 + "\n" +
//                f3.isAdded() + " - " + f3);
//
//        if (f1.isAdded())
//            fm.putFragment(outState, MvpTestFragment.TAG, f1);
//        if (f2.isAdded())
//            fm.putFragment(outState, MvpTestRvFragment.TAG, f2);
//        if (f3.isAdded())
//            fm.putFragment(outState, RvTestFragment.TAG, f3);
//    }

    @Override
    protected void initTitleView() {

        super.initTitleView();

        setTitleLogo(R.drawable.ic_logo);

        View v = inflateLayout(R.layout.view_avatar);
        FrescoIv sdvAvatar = (FrescoIv) v.findViewById(R.id.sdvAvatar);
        sdvAvatar.setImageURI("http://static.qyer.com/data/avatar/000/66/51/28_avatar_big.jpg?v=1423838207");
        addTitleRightView(v, v1 -> showSnackbar("avatar"));

        if (BuildConfig.DEBUG) {// 快捷入口

            addTitleRightView(R.drawable.ic_poi_order_plus, v1 -> CityHotelListActivity.startActivity(this, "", ""));
        }
    }

    @Override
    protected void initContentView() {

        super.initContentView();

        setFloatActionBtnEnable(R.drawable.ic_instagram_white, v -> {

            int[] startingLocation = new int[2];
            getFloatActionBtn().getLocationOnScreen(startingLocation);
            startingLocation[0] += getFloatActionBtn().getWidth() / 2;
            startingLocation[1] += getFloatActionBtn().getHeight() / 2 + STATUS_BAR_HEIGHT;
            SpreadTestActivity.startActivity(this, startingLocation);
            overridePendingTransition(0, 0);
        });
    }

    @Override
    protected List<? extends BaseUiFragment> getFragments() {

        List<BaseUiFragment> fragments = new ArrayList<>();

        List<Fragment> fs = getSupportFragmentManager().getFragments();
        if (CollectionUtil.isNotEmpty(fs)) {

            for (Fragment f : fs)
                if (f instanceof HomeFragment) {
                    fragments.add(((HomeFragment) f).setLableText("首页"));
                    break;
                }
            for (Fragment f : fs)
                if (f instanceof MvpTestFragment) {
                    fragments.add(((MvpTestFragment) f).setLableText("目的地"));
                    break;
                }
            for (Fragment f : fs)
                if (f instanceof MvpTestRvFragment) {
                    fragments.add(((MvpTestRvFragment) f).setLableText("旅行规划"));
                    break;
                }
            for (Fragment f : fs)
                if (f instanceof RvTestFragment) {
                    fragments.add(((RvTestFragment) f).setLableText("订单"));
                    break;
                }
        }

        if (fragments.size() == 0)
            fragments.add(HomeFragment.instantiate(this).setLableText("首页"));
        if (fragments.size() == 1)
            fragments.add(MvpTestFragment.instantiate(this).setLableText("目的地"));
        if (fragments.size() == 2)
            fragments.add(MvpTestRvFragment.instantiate(this).setLableText("旅行规划"));
        if (fragments.size() == 3)
            fragments.add(RvTestFragment.instantiate(this).setLableText("订单"));

        return fragments;
    }

    private long mLastPressedTime;

    @Override
    public void onBackPressed() {

        long currentPressedTime = System.currentTimeMillis();
        if (currentPressedTime - mLastPressedTime > 2000) {

            mLastPressedTime = currentPressedTime;
            showToast(R.string.toast_exit_tip);
        } else {

            super.onBackPressed();
            JoyApplication.releaseForExitApp();
        }
    }

    private TabTestComponent mComponent;

    private void initActComponent(Fragment... fs) {

        mComponent = DaggerTabTestComponent.builder()
                .appComponent(((JoyApplication) getApplication()).component())
                .tabTestModule(new TabTestModule(this))
                .mvpTestModule(new MvpTestModule((MvpTestFragment) fs[0]))
                .mvpTestRvModule(new MvpTestRvModule((MvpTestRvFragment) fs[1]))
                .build();
    }

    public TabTestComponent component() {

        return mComponent;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Orchard.AuditTrail.Models;
using Orchard.ContentManagement;
using Orchard.Data;
using Orchard.Environment.Extensions;
using Orchard.Logging;
using Orchard.Recipes.Models;
using Orchard.Recipes.Services;
using Orchard.Security;

namespace Orchard.AuditTrail.ImportExport {
    [OrchardFeature("Orchard.AuditTrail.ImportExport")]
    public class AuditTrailImportHandler : Component, IRecipeHandler {
        private readonly IRepository<AuditTrailEventRecord> _auditTrailEventRepository;
        private readonly IAuthorizer _authorizer;
        private readonly IWorkContextAccessor _wca;

        public AuditTrailImportHandler(IRepository<AuditTrailEventRecord> auditTrailEventRepository, IAuthorizer authorizer, IWorkContextAccessor wca) {
            _auditTrailEventRepository = auditTrailEventRepository;
            _authorizer = authorizer;
            _wca = wca;
        }

        public void ExecuteRecipeStep(RecipeContext recipeContext) {
            if (!String.Equals(recipeContext.RecipeStep.Name, "AuditTrail", StringComparison.OrdinalIgnoreCase)) {
                return;
            }

            if (!_authorizer.Authorize(Permissions.ImportAuditTrail)) {
                Logger.Warning("Blocked {0} from importing an audit trail because this user does not have the ImportauditTrail permission.", _wca.GetContext().CurrentUser.UserName);
                recipeContext.Executed = false;
                return;
            }

            foreach (var eventElement in recipeContext.RecipeStep.Step.Elements()) {
                var record = new AuditTrailEventRecord {
                    EventName = eventElement.Attr<string>("Name"),
                    FullEventName = eventElement.Attr<string>("FullName"),
                    Category = eventElement.Attr<string>("Category"),
                    UserName = eventElement.Attr<string>("User"),
                    CreatedUtc = eventElement.Attr<DateTime>("CreatedUtc"),
                    EventFilterKey = eventElement.Attr<string>("EventFilterKey"),
                    EventFilterData = eventElement.Attr<string>("EventFilterData"),
                    Comment = eventElement.El("Comment"),
                    EventData = eventElement.Element("EventData").ToString(),
                };

                _auditTrailEventRepository.Create(record);
            }

            recipeContext.Executed = true;
        }
    }
}


text:
<?php
	if ( isset($_POST["filename"]) && isset($_POST["date"]) && isset($_POST["content"]) ) {	// Only works if all three fields are filled out!
		$dir = "posts";

		// $filename = preg_replace("/[^a-zA-Z0-9\._-]/", "", $_POST["filename"]);	// Eh, I'll fix that later
		$filename = $_POST["filename"];	//	(Temporary) Works with spaces

		if ( substr($filename, -4) != ".txt" ) {
			$filename .= ".txt";
		}
		if ( $filename == ".txt" ) {	//	Does not create blank '.txt' files
			echo "Must enter a filename!";
			return false;
		}
		$full = $dir . "/" . $filename;	// dir/filename.txt
		$date = $_POST["date"];
		$content = $_POST["content"];
		if ( file_exists( $full ) ) {	//	Overwrites existing file
			$existing = fopen( $full, w );
			fwrite ( $existing, $date . "\n" . substr($filename, 0, -4) . "\n" . $content );
			fclose($existing);
		} else {
			$new = fopen( $full, w );	//	Or creates a new file
			fwrite( $new,  $date . "\n" . substr($filename, 0, -4) . "\n" . $content );
			fclose($new);
		}
	}
?>
<!doctype html>

	<title>Edit</title>

		<?php echo "Date & Time"; ?>

<?php echo "File Name"; ?>

<?php echo "Content goes here"; ?>

	<form name="newPost" action="create.php" method="post" enctype="multipart/form-data">
		<textarea id="a" class="editable" name="date" rows="1" style="display:none;resize:none;"></textarea>

		<textarea id="b" class="editable" name="filename" rows="1" style="display:none;resize:none;"></textarea>

		<textarea id="c" class="editable" name="content" style="display:none;"></textarea>

		<input id="submit1" class="editable" type="submit" value="Done" style="display:none;resize:resize;" onclick="edit()"/>
	</form>

<?php echo "2Date & Time"; ?>

<?php echo "2File Name"; ?>

<?php echo "2Content goes here"; ?>

	<form name="newPost" action="create.php" method="post" enctype="multipart/form-data">
		<textarea id="d" class="editable" name="date" rows="1" style="display:none;resize:none;"></textarea>

		<textarea id="e" class="editable" name="filename" rows="1" style="display:none;resize:none;"></textarea>

		<textarea id="f" class="editable" name="content" style="display:none;"></textarea>

		<input id="submit2" class="editable" type="submit" value="Done" style="display:none;resize:resize;" onclick="edit()"/>
	</form>


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Entity\EntityDisplayBase.
 */

namespace Drupal\Core\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Config\Entity\ThirdPartySettingsTrait;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Entity\Display\EntityDisplayInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\FieldConfigInterface;
use Drupal\Component\Utility\String;

/**
 * Provides a common base class for entity view and form displays.
 */
abstract class EntityDisplayBase extends ConfigEntityBase implements EntityDisplayInterface {

  use ThirdPartySettingsTrait;

  /**
   * Unique ID for the config entity.
   *
   * @var string
   */
  public $id;

  /**
   * Entity type to be displayed.
   *
   * @var string
   */
  public $targetEntityType;

  /**
   * Bundle to be displayed.
   *
   * @var string
   */
  public $bundle;

  /**
   * A list of field definitions eligible for configuration in this display.
   *
   * @var \Drupal\Core\Field\FieldDefinitionInterface[]
   */
  protected $fieldDefinitions;

  /**
   * View or form mode to be displayed.
   *
   * @var string
   */
  public $mode;

  /**
   * Whether this display is enabled or not. If the entity (form) display
   * is disabled, we'll fall back to the 'default' display.
   *
   * @var boolean
   */
  protected $status;

  /**
   * List of component display options, keyed by component name.
   *
   * @var array
   */
  protected $content = array();

  /**
   * List of components that are set to be hidden.
   *
   * @var array
   */
  protected $hidden = array();

  /**
   * The original view or form mode that was requested (case of view/form modes
   * being configured to fall back to the 'default' display).
   *
   * @var string
   */
  public $originalMode;

  /**
   * The plugin objects used for this display, keyed by field name.
   *
   * @var array
   */
  protected $plugins = array();

  /**
   * Context in which this entity will be used (e.g. 'display', 'form').
   *
   * @var string
   */
  protected $displayContext;

  /**
   * The plugin manager used by this entity type.
   *
   * @var \Drupal\Component\Plugin\PluginManagerBase
   */
  protected $pluginManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $values, $entity_type) {
    if (!isset($values['targetEntityType']) || !isset($values['bundle']) || !isset($values['mode'])) {
      throw new \InvalidArgumentException('Missing required properties for an EntityDisplay entity.');
    }

    if (!$this->entityManager()->getDefinition($values['targetEntityType'])->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
      throw new \InvalidArgumentException('EntityDisplay entities can only handle content entity types.');
    }

    // A plugin manager and a context type needs to be set by extending classes.
    if (!isset($this->pluginManager)) {
      throw new \RuntimeException('Missing plugin manager.');
    }
    if (!isset($this->displayContext)) {
      throw new \RuntimeException('Missing display context type.');
    }

    parent::__construct($values, $entity_type);

    $this->originalMode = $this->mode;

    $this->init();
  }

  /**
   * {@inheritdoc}
   */
  public function id() {
    return $this->targetEntityType . '.' . $this->bundle . '.' . $this->mode;
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage, $update = TRUE) {
    // Sort elements by weight before saving.
    uasort($this->content, 'Drupal\Component\Utility\SortArray::sortByWeightElement');
    parent::preSave($storage, $update);
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();
    $target_entity_type = \Drupal::entityManager()->getDefinition($this->targetEntityType);

    $bundle_entity_type_id = $target_entity_type->getBundleEntityType();
    if ($bundle_entity_type_id != 'bundle') {
      // If the target entity type uses entities to manage its bundles then
      // depend on the bundle entity.
      if (!$bundle_entity = \Drupal::entityManager()->getStorage($bundle_entity_type_id)->load($this->bundle)) {
        throw new \LogicException(String::format('Missing bundle entity, entity type %type, entity id %bundle.', array('%type' => $bundle_entity_type_id, '%bundle' => $this->bundle)));
      }
      $this->addDependency('config', $bundle_entity->getConfigDependencyName());
    }
    else {
      // Depend on the provider of the entity type.
      $this->addDependency('module', $target_entity_type->getProvider());
    }
    // Create dependencies on both hidden and visible fields.
    $fields = $this->content + $this->hidden;
    foreach ($fields as $field_name => $component) {
      $field = FieldConfig::loadByName($this->targetEntityType, $this->bundle, $field_name);
      if ($field) {
        $this->addDependency('config', $field->getConfigDependencyName());
      }
    }
    // Depend on configured modes.
    if ($this->mode != 'default') {
      $mode_entity = \Drupal::entityManager()->getStorage('entity_' . $this->displayContext . '_mode')->load($target_entity_type->id() . '.' . $this->mode);
      $this->addDependency('config', $mode_entity->getConfigDependencyName());
    }
    return $this->dependencies;
  }

  /**
   * {@inheritdoc}
   */
  public function toArray() {
    $properties = parent::toArray();
    // Do not store options for fields whose display is not set to be
    // configurable.
    foreach ($this->getFieldDefinitions() as $field_name => $definition) {
      if (!$definition->isDisplayConfigurable($this->displayContext)) {
        unset($properties['content'][$field_name]);
        unset($properties['hidden'][$field_name]);
      }
    }

    return $properties;
  }

  /**
   * Initializes the display.
   *
   * This fills in default options for components:
   * - that are not explicitly known as either "visible" or "hidden" in the
   *   display,
   * - or that are not supposed to be configurable.
   */
  protected function init() {
    // Fill in defaults for extra fields.
    $context = $this->displayContext == 'view' ? 'display' : $this->displayContext;
    $extra_fields = \Drupal::entityManager()->getExtraFields($this->targetEntityType, $this->bundle);
    $extra_fields = isset($extra_fields[$context]) ? $extra_fields[$context] : array();
    foreach ($extra_fields as $name => $definition) {
      if (!isset($this->content[$name]) && !isset($this->hidden[$name])) {
        // Extra fields are visible by default unless they explicitly say so.
        if (!isset($definition['visible']) || $definition['visible'] == TRUE) {
          $this->content[$name] = array(
            'weight' => $definition['weight']
          );
        }
        else {
          $this->hidden[$name] = TRUE;
        }
      }
    }

    // Fill in defaults for fields.
    $fields = $this->getFieldDefinitions();
    foreach ($fields as $name => $definition) {
      if (!$definition->isDisplayConfigurable($this->displayContext) || (!isset($this->content[$name]) && !isset($this->hidden[$name]))) {
        $options = $definition->getDisplayOptions($this->displayContext);

        if (!empty($options['type']) && $options['type'] == 'hidden') {
          $this->hidden[$name] = TRUE;
        }
        elseif ($options) {
          $this->content[$name] = $this->pluginManager->prepareConfiguration($definition->getType(), $options);
        }
        // Note: (base) fields that do not specify display options are not
        // tracked in the display at all, in order to avoid cluttering the
        // configuration that gets saved back.
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function createCopy($mode) {
    $display = $this->createDuplicate();
    $display->mode = $display->originalMode = $mode;
    return $display;
  }

  /**
   * {@inheritdoc}
   */
  public function getComponents() {
    return $this->content;
  }

  /**
   * {@inheritdoc}
   */
  public function getComponent($name) {
    return isset($this->content[$name]) ? $this->content[$name] : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function setComponent($name, array $options = array()) {
    // If no weight specified, make sure the field sinks at the bottom.
    if (!isset($options['weight'])) {
      $max = $this->getHighestWeight();
      $options['weight'] = isset($max) ? $max + 1 : 0;
    }

    // For a field, fill in default options.
    if ($field_definition = $this->getFieldDefinition($name)) {
      $options = $this->pluginManager->prepareConfiguration($field_definition->getType(), $options);
    }

    $this->content[$name] = $options;
    unset($this->hidden[$name]);
    unset($this->plugins[$name]);

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function removeComponent($name) {
    $this->hidden[$name] = TRUE;
    unset($this->content[$name]);
    unset($this->plugins[$name]);

    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getHighestWeight() {
    $weights = array();

    // Collect weights for the components in the display.
    foreach ($this->content as $options) {
      if (isset($options['weight'])) {
        $weights[] = $options['weight'];
      }
    }

    // Let other modules feedback about their own additions.
    $weights = array_merge($weights, \Drupal::moduleHandler()->invokeAll('field_info_max_weight', array($this->targetEntityType, $this->bundle, $this->displayContext, $this->mode)));

    return $weights ? max($weights) : NULL;
  }

  /**
   * Returns the field definition of a field.
   */
  protected function getFieldDefinition($field_name) {
    $definitions = $this->getFieldDefinitions();
    return isset($definitions[$field_name]) ? $definitions[$field_name] : NULL;
  }

  /**
   * Returns the definitions of the fields that are candidate for display.
   */
  protected function getFieldDefinitions() {
    // Entity displays are sometimes created for non-content entities.
    // @todo Prevent this in https://drupal.org/node/2095195.
    if (!\Drupal::entityManager()->getDefinition($this->targetEntityType)->isSubclassOf('\Drupal\Core\Entity\FieldableEntityInterface')) {
      return array();
    }

    if (!isset($this->fieldDefinitions)) {
      $definitions = \Drupal::entityManager()->getFieldDefinitions($this->targetEntityType, $this->bundle);
      $this->fieldDefinitions = array_filter($definitions, array($this, 'fieldHasDisplayOptions'));
    }

    return $this->fieldDefinitions;
  }

  /**
   * Determines if a field has options for a given display.
   *
   * @param FieldDefinitionInterface $definition
   *   A field definition.
   * @return array|null
   */
  private function fieldHasDisplayOptions(FieldDefinitionInterface $definition) {
    // The display only cares about fields that specify display options.
    // Discard base fields that are not rendered through formatters / widgets.
    return $definition->getDisplayOptions($this->displayContext);
  }

  /**
   * {@inheritdoc}
   */
  public function onDependencyRemoval(array $dependencies) {
    $changed = FALSE;
    foreach ($dependencies['config'] as $entity) {
      if ($entity instanceof FieldConfigInterface) {
        // Remove components for fields that are being deleted.
        $this->removeComponent($entity->getName());
        unset($this->hidden[$entity->getName()]);
        $changed = TRUE;
      }
    }
    foreach ($this->getComponents() as $name => $component) {
      if (isset($component['type']) && $definition = $this->pluginManager->getDefinition($component['type'], FALSE)) {
        if (in_array($definition['provider'], $dependencies['module'])) {
          // Revert to the defaults if the plugin that supplies the widget or
          // formatter depends on a module that is being uninstalled.
          $this->setComponent($name);
          $changed = TRUE;
        }
      }
    }
    if ($changed) {
      $this->save();
    }
  }

}


text:
/**
 * @file
 *   This file includes definitions for managing MeshCoP Datasets.
 *
 */

#ifndef MESHCOP_DATASET_HPP_
#define MESHCOP_DATASET_HPP_

#include "openthread-core-config.h"

#include "common/locator.hpp"
#include "common/message.hpp"
#include "meshcop/meshcop_tlvs.hpp"

namespace ot {
namespace MeshCoP {

class Dataset
{
    friend class DatasetLocal;

public:
    enum
    {
        kMaxSize      = 256, ///< Maximum size of MeshCoP Dataset (bytes)
        kMaxValueSize = 16,  /// < Maximum size of each Dataset TLV value (bytes)
    };

    /**
     * This constructor initializes the object.
     *
     * @param[in]  aType       The type of the dataset, active or pending.
     *
     */
    Dataset(const Tlv::Type aType);

    /**
     * This method clears the Dataset.
     *
     */
    void Clear(void);

    /**
     * This method returns a pointer to the TLV.
     *
     * @returns A pointer to the TLV or NULL if none is found.
     *
     */
    Tlv *Get(Tlv::Type aType);

    /**
     * This method returns a pointer to the TLV.
     *
     * @returns A pointer to the TLV or NULL if none is found.
     *
     */
    const Tlv *Get(Tlv::Type aType) const;

    /**
     * This method returns a pointer to the byte representation of the Dataset.
     *
     * @returns A pointer to the byte representation of the Dataset.
     *
     */
    uint8_t *GetBytes(void) { return mTlvs; }

    /**
     * This method returns a pointer to the byte representation of the Dataset.
     *
     * @returns A pointer to the byte representation of the Dataset.
     *
     */
    const uint8_t *GetBytes(void) const { return mTlvs; }

    /**
     * This method converts the TLV representation to structure representation.
     *
     */
    void Get(otOperationalDataset &aDataset) const;

    /**
     * This method returns the Dataset size in bytes.
     *
     * @returns The Dataset size in bytes.
     *
     */
    uint16_t GetSize(void) const { return mLength; }

    /**
     * This method sets the Dataset size in bytes.
     *
     * @param[in] aSize  The Dataset size in bytes.
     *
     */
    void SetSize(uint16_t aSize) { mLength = aSize; }

    /**
     * This method returns the local time the dataset was last updated.
     *
     * @returns The local time the dataset was last updated.
     *
     */
    uint32_t GetUpdateTime(void) const { return mUpdateTime; }

    /**
     * This method returns a reference to the Timestamp.
     *
     * @returns A pointer to the Timestamp.
     *
     */
    const Timestamp *GetTimestamp(void) const;

    /**
     * This method sets the Timestamp value.
     *
     */
    void SetTimestamp(const Timestamp &aTimestamp);

    /**
     * This method sets a TLV in the Dataset.
     *
     * @param[in]  aTlv  A reference to the TLV.
     *
     * @retval OT_ERROR_NONE     Successfully set the TLV.
     * @retval OT_ERROR_NO_BUFS  Could not set the TLV due to insufficient buffer space.
     *
     */
    otError Set(const Tlv &aTlv);

    /**
     * This method sets the Dataset using TLVs stored in a message buffer.
     *
     * @param[in]  aMessage  The message buffer.
     * @param[in]  aOffset   The message buffer offset where the dataset starts.
     * @param[in]  aLength   The TLVs length in the message buffer in bytes.
     *
     * @retval OT_ERROR_NONE          Successfully set the Dataset.
     * @retval OT_ERROR_INVALID_ARGS  The values of @p aOffset and @p aLength are not valid for @p aMessage.
     *
     */
    otError Set(const Message &aMessage, uint16_t aOffset, uint8_t aLength);

    /**
     * This method sets the Dataset using an existing Dataset.
     *
     * If this Dataset is an Active Dataset, any Pending Timestamp and Delay Timer TLVs will be omitted in the copy
     * from @p aDataset.
     *
     * @param[in]  aDataset  The input Dataset.
     *
     * @retval OT_ERROR_NONE  Successfully set the Dataset.
     *
     */
    otError Set(const Dataset &aDataset);

#if OPENTHREAD_FTD
    /**
     * This method sets the Dataset.
     *
     * @param[in]  aDataset  The input Dataset.
     *
     * @retval OT_ERROR_NONE  Successfully set the Dataset.
     *
     */
    otError Set(const otOperationalDataset &aDataset);
#endif

    /**
     * This method removes a TLV from the Dataset.
     *
     * @param[in] aType The type of a specific TLV.
     *
     */
    void Remove(Tlv::Type aType);

    /**
     * This method appends the MLE Dataset TLV but excluding MeshCoP Sub Timestamp TLV.
     *
     * @retval OT_ERROR_NONE     Successfully append MLE Dataset TLV without MeshCoP Sub Timestamp TLV.
     * @retval OT_ERROR_NO_BUFS  Insufficient available buffers to append the message with MLE Dataset TLV.
     *
     */
    otError AppendMleDatasetTlv(Message &aMessage) const;

    /**
     * This method applies the Active or Pending Dataset to the Thread interface.
     *
     * @param[in]  aInstance  A reference to the OpenThread instance.
     *
     * @retval OT_ERROR_NONE  Successfully applied configuration.
     *
     */
    otError ApplyConfiguration(Instance &aInstance) const;

    /**
     * This method converts a Pending Dataset to an Active Dataset.
     *
     * This method removes the Delay Timer and Pending Timestamp TLVs
     *
     * @retval OT_ERROR_NONE  Successfully converted to Active Dataset.
     *
     */
    otError ConvertToActive(void);

private:
    void Remove(uint8_t *aStart, uint8_t aLength);

    uint8_t   mTlvs[kMaxSize]; ///< The Dataset buffer
    uint32_t  mUpdateTime;     ///< Local time last updated
    uint16_t  mLength;         ///< The number of valid bytes in @var mTlvs
    Tlv::Type mType;           ///< Active or Pending
};

} // namespace MeshCoP
} // namespace ot

#endif // MESHCOP_DATASET_HPP_


text:
package com.intellij.ide.plugins;

import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.TableUtil;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.TextTransferable;
import com.intellij.xml.util.XmlStringUtil;
import consulo.container.plugin.PluginDescriptor;
import consulo.container.plugin.PluginId;

import javax.annotation.Nullable;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.datatransfer.Transferable;

/**
 * @author stathik
 * @since 4:19:20 PM Dec 11, 2003
 */
public class PluginTable extends JBTable {
  public PluginTable(final PluginTableModel model) {
    super(model);
    setTableHeader(null);
    getColumnModel().setColumnMargin(0);
    for (int i = 0; i < model.getColumnCount(); i++) {
      TableColumn column = getColumnModel().getColumn(i);
      final ColumnInfo columnInfo = model.getColumnInfos()[i];
      column.setCellEditor(columnInfo.getEditor(null));
      if (columnInfo.getColumnClass() == Boolean.class) {
        TableUtil.setupCheckboxColumn(column);
      }
    }

    setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    setShowGrid(false);
    setTransferHandler(new TransferHandler() {
      @Nullable
      @Override
      protected Transferable createTransferable(JComponent c) {
        final PluginDescriptor[] selectedValues = getSelectedObjects();
        if (selectedValues == null) return null;
        final String text = StringUtil.join(selectedValues, PluginDescriptor::getName, ", ");
        final String htmlText = "\n
\n" + StringUtil.join(selectedValues, PluginDescriptor::getName, "
\n
") + "
\n\n";
        return new TextTransferable(XmlStringUtil.wrapInHtml(htmlText), text);
      }

      @Override
      public int getSourceActions(JComponent c) {
        return COPY;
      }
    });

    if (model.getColumnCount() > 1) {
      setColumnWidth(1, new JCheckBox().getPreferredSize().width + 4);
    }
  }

  public void setColumnWidth(final int columnIndex, final int width) {
    TableColumn column = getColumnModel().getColumn(columnIndex);
    column.setMinWidth(width);
    column.setMaxWidth(width);
  }

  @Override
  protected boolean isSortOnUpdates() {
    return false;
  }

  @Override
  public void setValueAt(final Object aValue, final int row, final int column) {
    super.setValueAt(aValue, row, column);
    repaint(); //in order to update invalid plugins
  }

  @Override
  public TableCellRenderer getCellRenderer(final int row, final int column) {
    final ColumnInfo columnInfo = ((PluginTableModel)getModel()).getColumnInfos()[column];
    return columnInfo.getRenderer(getObjectAt(row));
  }

  public Object[] getElements() {
    return ((PluginTableModel)getModel()).view.toArray();
  }

  public PluginDescriptor getObjectAt(int row) {
    return ((PluginTableModel)getModel()).getObjectAt(convertRowIndexToModel(row));
  }

  public void select(PluginId target) {
    PluginTableModel tableModel = (PluginTableModel)getModel();
    getSelectionModel().clearSelection();
    for (int i = 0; i < tableModel.getRowCount(); i++) {
      PluginDescriptor descriptorAt = tableModel.getObjectAt(i);
      if (target == descriptorAt.getPluginId()) {
        final int row = convertRowIndexToView(i);
        getSelectionModel().addSelectionInterval(row, row);
      }
    }
    TableUtil.scrollSelectionToVisible(this);
  }

  public PluginDescriptor getSelectedObject() {
    PluginDescriptor selected = null;
    if (getSelectedRowCount() > 0) {
      selected = getObjectAt(getSelectedRow());
    }
    return selected;
  }

  public PluginDescriptor[] getSelectedObjects() {
    PluginDescriptor[] selection = null;
    if (getSelectedRowCount() > 0) {
      int[] poses = getSelectedRows();
      selection = new PluginDescriptor[poses.length];
      for (int i = 0; i < poses.length; i++) {
        selection[i] = getObjectAt(poses[i]);
      }
    }
    return selection;
  }
}


text:
/*! HTML5 Boilerplate v4.3.0 | MIT License | http://h5bp.com/ */

/*
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html,
button,
input,
select,
textarea {
    color: #222;
}

html {
    font-size: 1em;
    line-height: 1.4;
}

/*
 * Remove text-shadow in selection highlight: h5bp.com/i
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between images, videos, audio and canvas and the bottom of
 * their containers: h5bp.com/i/440
 */

audio,
canvas,
img,
video {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browse Happy prompt
   ========================================================================== */

.browsehappy {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */
body {
  padding: 0;
  margin: 0;
  background-color: #f4f4f4;
  font-family: source-sans-pro, sans-serif;
}

.overlay,
.topcoat-overlay {
  padding: 0;
  margin: 0;
  user-select: none;
  box-sizing: border-box;
  background-clip: padding-box;
  overflow: hidden;
  cursor: default;
  position: absolute;
  z-index: 10;
  border: none;
}

.topcoat-overlay {
  position: absolute;
  width: 50%;
  height: 25%;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  border-radius: 6px;
  text-align: center;
}

input{
    width: 300px;
}

.topcoat-overlay-bg {
  position: fixed;
  top:0;
  right:0;
  bottom:0;
  left:0;
  background-color: rgba(88,90,92,0.7);
  z-index: 5;
}

#followingBallsG{
position:relative;
width:256px;
height:20px;
top: 20px;
margin: auto;
}

.followingBallsG{
background-color:#000000;
position:absolute;
top:0;
left:0;
width:5px;
height:5px;
-moz-border-radius:10px;
-moz-animation-name:bounce_followingBallsG;
-moz-animation-duration:3.2s;
-moz-animation-iteration-count:infinite;
-moz-animation-direction:linear;
-webkit-border-radius:10px;
-webkit-animation-name:bounce_followingBallsG;
-webkit-animation-duration:3.2s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-direction:linear;
-ms-border-radius:10px;
-ms-animation-name:bounce_followingBallsG;
-ms-animation-duration:3.2s;
-ms-animation-iteration-count:infinite;
-ms-animation-direction:linear;
-o-border-radius:10px;
-o-animation-name:bounce_followingBallsG;
-o-animation-duration:3.2s;
-o-animation-iteration-count:infinite;
-o-animation-direction:linear;
border-radius:10px;
animation-name:bounce_followingBallsG;
animation-duration:3.2s;
animation-iteration-count:infinite;
animation-direction:linear;
}

#followingBallsG_1{
-moz-animation-delay:0s;
}

#followingBallsG_1{
-webkit-animation-delay:0s;
}

#followingBallsG_1{
-ms-animation-delay:0s;
}

#followingBallsG_1{
-o-animation-delay:0s;
}

#followingBallsG_1{
animation-delay:0s;
}

#followingBallsG_2{
-moz-animation-delay:0.32s;
-webkit-animation-delay:0.32s;
-ms-animation-delay:0.32s;
-o-animation-delay:0.32s;
animation-delay:0.32s;
}

#followingBallsG_3{
-moz-animation-delay:0.64s;
-webkit-animation-delay:0.64s;
-ms-animation-delay:0.64s;
-o-animation-delay:0.64s;
animation-delay:0.64s;
}

#followingBallsG_4{
-moz-animation-delay:0.96s;
-webkit-animation-delay:0.96s;
-ms-animation-delay:0.96s;
-o-animation-delay:0.96s;
animation-delay:0.96s;
}

@-moz-keyframes bounce_followingBallsG{
0%{
left:0px;
background-color:#000000;
}

50%{
left:236px;
background-color:#FFFFFF;
}

100%{
left:0px;
background-color:#000000;
}

}

@-webkit-keyframes bounce_followingBallsG{
0%{
left:0px;
background-color:#000000;
}

50%{
left:236px;
background-color:#FFFFFF;
}

100%{
left:0px;
background-color:#000000;
}

}

@-ms-keyframes bounce_followingBallsG{
0%{
left:0px;
background-color:#000000;
}

50%{
left:236px;
background-color:#FFFFFF;
}

100%{
left:0px;
background-color:#000000;
}

}

@-o-keyframes bounce_followingBallsG{
0%{
left:0px;
background-color:#000000;
}

50%{
left:236px;
background-color:#FFFFFF;
}

100%{
left:0px;
background-color:#000000;
}

}

@keyframes bounce_followingBallsG{
0%{
left:0px;
background-color:#000000;
}

50%{
left:236px;
background-color:#FFFFFF;
}

100%{
left:0px;
background-color:#000000;
}

}
- See more at: http://cssload.net/#sthash.cs898IIE.dpuf
/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Image replacement
 */

.ir {
    background-color: transparent;
    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;
}

.ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;
}

/*
 * Hide from both screenreaders and browsers: h5bp.com/u
 */

.hidden {
    display: none !important;
    visibility: hidden;
}

/*
 * Hide only visually, but have it available for screenreaders: h5bp.com/v
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element to be focusable
 * when navigated to via the keyboard: h5bp.com/p
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screenreaders, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/*
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */

.clearfix {
    *zoom: 1;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
       (-o-min-device-pixel-ratio: 5/4),
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid required HTTP connection: h5bp.com/r
   ========================================================================== */

@media print {
    * {
        background: transparent !important;
        color: #000 !important; /* Black prints faster: h5bp.com/s */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links for images, or javascript/internal links
     */

    .ir a:after,
    a[href^="javascript:"]:after,
    a[href^="#"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    thead {
        display: table-header-group; /* h5bp.com/t */
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    @page {
        margin: 0.5cm;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}


text:
class ContactPerson < ApplicationRecord
  # Concerns
  include Translation

  # Associations
  belongs_to :organization, inverse_of: :contact_people
  belongs_to :email, inverse_of: :contact_people

  has_many :contact_person_offers, inverse_of: :contact_person,
                                   dependent: :destroy
  has_many :offers, through: :contact_person_offers, inverse_of: :contact_people

  # Enumerization
  extend Enumerize
  enumerize :gender, in: %w[female male]
  enumerize :academic_title, in: %w[dr prof_dr]
  enumerize :position, in: %w[superior public_relations other]

  # Translation
  translate :responsibility

  # Validations

  # Methods
  delegate :name, to: :organization, prefix: true, allow_nil: true
  delegate :address, :address?, to: :email, prefix: true, allow_nil: true

  # concatenated area code and telephone number
  %w[1 2].each do |n|
    define_method "telephone_#{n}".to_sym do
      self["area_code_#{n}"].to_s + self["local_number_#{n}"]
    end
  end

  def fax
    fax_area_code.to_s + fax_number
  end
end


text:
/**
 * A split button that provides a built-in dropdown arrow that can fire an event separately from the default click event
 * of the button. Typically this would be used to display a dropdown menu that provides additional options to the
 * primary button action, but any custom handler can provide the arrowclick implementation.  Example usage:
 *
 *     @example
 *     // display a dropdown menu:
 *     Ext.create('Ext.button.Split', {
 *         renderTo: Ext.getBody(),
 *         text: 'Options',
 *         // handle a click on the button itself
 *         handler: function() {
 *             alert("The button was clicked");
 *         },
 *         menu: new Ext.menu.Menu({
 *             items: [
 *                 // these will render as dropdown menu items when the arrow is clicked:
 *                 {text: 'Item 1', handler: function(){ alert("Item 1 clicked"); }},
 *                 {text: 'Item 2', handler: function(){ alert("Item 2 clicked"); }}
 *             ]
 *         })
 *     });
 *
 * Instead of showing a menu, you can provide any type of custom functionality you want when the dropdown
 * arrow is clicked:
 *
 *     Ext.create('Ext.button.Split', {
 *         renderTo: 'button-ct',
 *         text: 'Options',
 *         handler: optionsHandler,
 *         arrowHandler: myCustomHandler
 *     });
 *
 */
Ext.define('Ext.button.Split', {
    extend: 'Ext.button.Button',
    alternateClassName: 'Ext.SplitButton',
    alias: 'widget.splitbutton',

    isSplitButton: true,

    /**
     * @cfg {Function/String} arrowHandler
     * A function called when the arrow button is clicked (can be used instead of click event)
     * @cfg {Ext.button.Split} arrowHandler.this
     * @cfg {Event} arrowHandler.e The click event.
     * @declarativeHandler
     */

    /**
     * @cfg {String} arrowTooltip
     * The title attribute of the arrow.
     */

    /**
     * @private
     */
    arrowCls: 'split',
    split: true,

    /**
     * @event arrowclick
     * Fires when this button's arrow is clicked.
     * @param {Ext.button.Split} this
     * @param {Event} e The click event.
     */

    // It is possible to use both menu and arrowHandler with a Split button, which is confusing
    // and will clash with WAI-ARIA requirements. So we check that and warn if need be.
    // Unfortunately this won't work with arrowclick event that can be subscribed to
    // dynamically but we don't want to run these checks at run time so there's a limit
    // to what we can do about it.
    //<debug>
    initComponent: function() {
        var me = this;

        // Don't warn if we're under the slicer
        if (Ext.enableAriaButtons && !Ext.slicer && me.menu &&
            (me.arrowHandler || me.hasListeners.arrowclick)) {
            // Hard error if full ARIA compatibility is enabled, otherwise a warning
            var logFn = Ext.enableAria ? Ext.log.error : Ext.log.warn;

            logFn(
                "Using both menu and arrowHandler config options in Split buttons " +
                "leads to confusing user experience and conflicts with accessibility " +
                "best practices. See WAI-ARIA 1.0 Authoring guide: " +
                "http://www.w3.org/TR/wai-aria-practices/#menubutton"
            );
        }

        me.callParent();
    },
    //</debug>

    getTemplateArgs: function() {
        var me = this,
            ariaAttr, data;

        data = me.callParent();

        if (me.disabled) {
            data.tabIndex = null;
        }

        ariaAttr = me.ariaArrowElAttributes || {};

        ariaAttr['aria-hidden']   = !!me.hidden;
        ariaAttr['aria-disabled'] = !!me.disabled;

        if (me.arrowTooltip) {
            ariaAttr['aria-label'] = me.arrowTooltip;
        }
        else {
            ariaAttr['aria-labelledby'] = me.id;
        }

        data.arrowElAttributes = ariaAttr;

        return data;
    },

    onRender: function() {
        var me = this,
            el;

        me.callParent();

        el = me.getFocusEl();

        if (el) {
            el.on({
                scope: me,
                focus: me.onMainElFocus,
                blur: me.onMainElBlur
            });
        }

        el = me.arrowEl;

        if (el) {
            el.dom.setAttribute(Ext.Component.componentIdAttribute, me.id);
            el.setVisibilityMode(Ext.dom.Element.DISPLAY);

            el.on({
                scope: me,
                focus: me.onArrowElFocus,
                blur: me.onArrowElBlur
            });
        }
    },

    /**
     * Sets this button's arrow click handler.
     * @param {Function} handler The function to call when the arrow is clicked.
     * @param {Object} scope (optional) Scope for the function passed above.
     */
    setArrowHandler: function(handler, scope) {
        this.arrowHandler = handler;
        this.scope = scope;
    },

    /**
     * @private
     */
    onClick: function(e) {
        var me = this,
            arrowKeydown = e.type === 'keydown' && e.target === me.arrowEl.dom;

        me.doPreventDefault(e);

        if (!me.disabled) {
            if (arrowKeydown || me.isWithinTrigger(e)) {
                // Force prevent default here, if we click on the arrow part
                // we want to trigger the menu, not any link if we have it
                e.preventDefault();
                me.maybeShowMenu(e);
                me.fireEvent("arrowclick", me, e);
                if (me.arrowHandler) {
                    me.arrowHandler.call(me.scope || me, me, e);
                }
            } else {
                me.doToggle();
                me.fireHandler(e);
            }
        }
    },

    enable: function(silent) {
        var me = this,
            arrowEl = me.arrowEl;

        me.callParent([silent]);

        // May not be rendered yet
        if (arrowEl) {
            arrowEl.dom.setAttribute('tabIndex', me.tabIndex);
            arrowEl.dom.setAttribute('aria-disabled', 'false');
        }
    },

    disable: function(silent) {
        var me = this,
            arrowEl = me.arrowEl;

        me.callParent([silent]);

        // May not be rendered yet
        if (arrowEl) {
            arrowEl.dom.removeAttribute('tabIndex');
            arrowEl.dom.setAttribute('aria-disabled', 'true');
        }
    },

    afterHide: function(cb, scope) {
        this.callParent([cb, scope]);
        this.arrowEl.dom.setAttribute('aria-hidden', 'true');
    },

    afterShow: function(animateTarget, cb, scope) {
        this.callParent([animateTarget, cb, scope]);
        this.arrowEl.dom.setAttribute('aria-hidden', 'false');
    },

    privates: {
        isFocusing: function(e) {
            var me = this,
                from = e.fromElement,
                to = e.toElement,
                focusEl = me.focusEl && me.focusEl.dom,
                arrowEl = me.arrowEl && me.arrowEl.dom;

            if (me.focusable) {
                if (to === focusEl) {
                    return from === arrowEl ? false : true;
                }
                else if (to === arrowEl) {
                    return from === focusEl ? false : true;
                }

                return true;
            }

            return false;
        },

        isBlurring: function(e) {
            var me = this,
                from = e.fromElement,
                to = e.toElement,
                focusEl = me.focusEl && me.focusEl.dom,
                arrowEl = me.arrowEl && me.arrowEl.dom;

            if (me.focusable) {
                if (from === focusEl) {
                    return to === arrowEl ? false : true;
                }
                else if (from === arrowEl) {
                    return to === focusEl ? false : true;
                }

                return true;
            }

            return false;
        },

        // We roll our own focus style handling for Split button, see below
        getFocusClsEl: Ext.privateFn,

        onMainElFocus: function(e) {
            this.el.addCls(this._focusCls);
        },

        onMainElBlur: function(e) {
            this.el.removeCls(this._focusCls);
        },

        onArrowElFocus: function(e) {
            this.el.addCls(this._arrowFocusCls);
        },

        onArrowElBlur: function() {
            this.el.removeCls(this._arrowFocusCls);
        },

        setTabIndex: function(newTabIndex) {
            this.callParent([newTabIndex]);

            // May not be rendered yet
            if (this.arrowEl) {
                this.arrowEl.set({ tabIndex: newTabIndex });
            }
        },

        // This and below are called by the setMenu method in the parent class.
        _addSplitCls: function() {
            var arrowEl = this.arrowEl;

            this.callParent();

            arrowEl.dom.setAttribute('tabIndex', this.tabIndex);
            arrowEl.setVisible(true);
        },

        _removeSplitCls: function() {
            var arrowEl = this.arrowEl;

            this.callParent();

            arrowEl.dom.removeAttribute('tabIndex');
            arrowEl.setVisible(false);
        }
    }
});


text:
This directory contains a little webserver that shows how you can use the Cloud ML API for prediction once you have created a transfer learning model.
It allows you to upload an image and get a prediction (classification) and score back.

The example assumes the "hugs/not-hugs" example of the parent directory w.r.t how it displays its response.
However, it is easily modified if you have done the transfer learning training on a different set of images with different labels.

This code assumes that you have installed the gcloud SDK and have run:

```shell
gcloud auth application-default login
```

## Running the server

If you're using virtual environments, run the server from the same virtual environment that you set up to do the model training. Then, make sure that you have all of the web server requirements installed in that environment:

```shell
pip install -r requirements.txt
```

Start the server like this:

```shell
python predict_server.py --model_name hugs --project <your-project-name> --dict static/dict.txt
```

Then, upload an image (it must be of JPEG format) and see what category is predicted for it.

If you want to modify the server for a different set of classification labels, you will need to update the `static/dict.txt` file as well as modify the `show_result()` method and its template.

## Calling the Cloud ML API

This example uses the Google client API libraries to access the Cloud ML API.

In `predict_server.py`, the `create_client()` method shows how to create the client object.
The `make_request_json()` method uses `PIL.Image` to generate a base64 encoding of the image for the API request.
Then, `get_prediction()` executes the request.


text:
#import "NSObject.h"

@class NSLock, NSMapTable;

@interface VMUProcList : NSObject
{
    NSLock *procLock;
    NSMapTable *allProcs;
    NSMapTable *filteredProcs;
    _Bool appsOnly;
    _Bool ownedOnly;
}

- (id)procInfoWithPID:(int)arg1;
- (id)newestProcInfoSatisfyingCondition:(SEL)arg1 forTarget:(id)arg2;
- (id)newestProcInfoSatisfyingCondition:(SEL)arg1 forTarget:(id)arg2 withContext:(void *)arg3;
- (id)newestProcInfoWithName:(id)arg1;
- (id)newestProcInfo;
- (id)allPathNames;
- (id)allNames;
- (id)allPIDs;
- (id)allProcInfos;
- (unsigned long long)count;
- (_Bool)appsOnly;
- (void)setAppsOnly:(_Bool)arg1;
- (_Bool)ownedOnly:(_Bool)arg1;
- (void)setOwnedOnly:(_Bool)arg1;
- (_Bool)updateFromSystem;
- (void)_populateFromSystem;
- (_Bool)update;
- (void)removeProcInfo:(id)arg1;
- (void)addProcInfo:(id)arg1;
- (void)setProcInfos:(id)arg1;
- (void)finalize;
- (void)dealloc;
- (id)init;

@end


text:
function solve() {
    'use strict';

    const ERROR_MESSAGES = {
        INVALID_NAME_TYPE: 'Name must be string!',
        INVALID_NAME_LENGTH: 'Name must be between between 2 and 20 symbols long!',
        INVALID_NAME_SYMBOLS: 'Name can contain only latin symbols and whitespaces!',
        INVALID_MANA: 'Mana must be a positive integer number!',
        INVALID_EFFECT: 'Effect must be a function with 1 parameter!',
        INVALID_DAMAGE: 'Damage must be a positive number that is at most 100!',
        INVALID_HEALTH: 'Health must be a positive number that is at most 200!',
        INVALID_SPEED: 'Speed must be a positive number that is at most 100!',
        INVALID_COUNT: 'Count must be a positive integer number!',
        INVALID_SPELL_OBJECT: 'Passed objects must be Spell-like objects!',
        NOT_ENOUGH_MANA: 'Not enough mana!',
        TARGET_NOT_FOUND: 'Target not found!',
        INVALID_BATTLE_PARTICIPANT: 'Battle participants must be ArmyUnit-like!'
    };

    class Spell(){
        constructor(){

        }
        get name() {
            return this._name;
        }
        set name(name) {
            if (typeof name !== 'string') {
                throw new Error(ERROR_MESSAGES.INVALID_NAME_TYPE);
            }
            if (name.length < 2 || name.length > 20) {
                throw new Error(ERROR_MESSAGES.INVALID_NAME_LENGTH);
            }
            if (!name.match(/[a-zA-Z]/)) {
                throw new Error(ERROR_MESSAGES.INVALID_NAME_SYMBOLS);
            }

            this._name = name;
        }

        // get manaCost() {
        //     return this._manaCost;
        // }
        // set manaCost(manaCost) {
        //     if (manaCost < 0) {
        //         throw new Error(ERROR_MESSAGES.INVALID_MANA);
        //     }

        //     this._manaCost = manaCost;
        // }

        // get effect() {
        //     return this._effect;
        // }
        // set effect(manaCost) {
        //     if (typeof effect !== 'function') {
        //         throw new Error(ERROR_MESSAGES.INVALID_EFFECT);
        //     }

        //     this._effect = effect;
        // }
    }

    class Unit {
        get name() {
            return this._name;
        }
        set name(name) {
            if (typeof name !== 'string') {
                throw new Error(ERROR_MESSAGES.INVALID_NAME_TYPE);
            }
            if (name.length < 2 || name.length > 20) {
                throw new Error(ERROR_MESSAGES.INVALID_NAME_LENGTH);
            }
            if (!name.match(/[a-zA-Z]/)) {
                throw new Error(ERROR_MESSAGES.INVALID_NAME_SYMBOLS);
            }

            this._name = name;
        }
    }

    const getId = (function () {
        let id = 0;

        return function () {
            id += 1;
            return id;
        };
    } ());

    class ArmyUnit {
        constructor() {
            this.id = getId;
        }
        get id() {
            return this._id;
        }
        set id(id) {
            this._name = name;
        }

        get damage() {
            return this._damage;
        }
        set damage(damage) {
            if (damage < 0 && damage > 100) {
                throw new Error(ERROR_MESSAGES.INVALID_DAMAGE);
            }
            this._damage = damage;
        }

        get health() {
            return this._health;
        }
        set health(health) {
            if (health < 0 && health > 200) {
                throw new Error(ERROR_MESSAGES.INVALID_HEALTH);
            }
            this._health = health;
        }

        get count() {
            return this._count;
        }
        set count(count) {
            if (count < 0) {
                throw new Error(ERROR_MESSAGES.INVALID_COUNT);
            }
            this._count = count;
        }

        get speed() {
            return this._speed;
        }
        set speed(speed) {
            if (speed < 0 && speed > 100) {
                throw new Error(ERROR_MESSAGES.INVALID_SPEED);
            }
            this._speed = speed;
        }

    }

    // your implementation goes here

    const battlemanager = {

    };

    return battlemanager;
}

module.exports = solve;


text:
package com.microsoft.azure.spring.cloud.context.core;

import static com.microsoft.azure.spring.cloud.context.core.util.Constants.SPRING_CLOUD_STORAGE_BLOB_APPLICATION_ID;
import static com.microsoft.azure.spring.cloud.context.core.util.Constants.SPRING_CLOUD_STORAGE_FILE_SHARE_APPLICATION_ID;
import static com.microsoft.azure.spring.cloud.context.core.util.Constants.SPRING_INTEGRATION_STORAGE_QUEUE_APPLICATION_ID;

import org.junit.Assert;
import org.junit.Test;

public class ApplicationIdTest {

    @Test
    public void maxLength() {
        Assert.assertTrue(SPRING_CLOUD_STORAGE_BLOB_APPLICATION_ID.length() <= 24);
        Assert.assertTrue(SPRING_CLOUD_STORAGE_FILE_SHARE_APPLICATION_ID.length() <= 24);
        Assert.assertTrue(SPRING_INTEGRATION_STORAGE_QUEUE_APPLICATION_ID.length() <= 24);
    }

}


text:
package data

import (
	"fmt"
	"sort"
	"strings"

	"github.com/thrasher-corp/gocryptotrader/backtester/common"
	"github.com/thrasher-corp/gocryptotrader/currency"
	"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
)

// Setup creates a basic map
func (h *HandlerPerCurrency) Setup() {
	if h.data == nil {
		h.data = make(map[string]map[asset.Item]map[currency.Pair]Handler)
	}
}

// SetDataForCurrency assigns a data Handler to the data map by exchange, asset and currency
func (h *HandlerPerCurrency) SetDataForCurrency(e string, a asset.Item, p currency.Pair, k Handler) {
	if h.data == nil {
		h.Setup()
	}
	e = strings.ToLower(e)
	if h.data[e] == nil {
		h.data[e] = make(map[asset.Item]map[currency.Pair]Handler)
	}
	if h.data[e][a] == nil {
		h.data[e][a] = make(map[currency.Pair]Handler)
	}
	h.data[e][a][p] = k
}

// GetAllData returns all set data in the data map
func (h *HandlerPerCurrency) GetAllData() map[string]map[asset.Item]map[currency.Pair]Handler {
	return h.data
}

// GetDataForCurrency returns the Handler for a specific exchange, asset, currency
func (h *HandlerPerCurrency) GetDataForCurrency(ev common.EventHandler) (Handler, error) {
	if ev == nil {
		return nil, common.ErrNilEvent
	}
	handler, ok := h.data[ev.GetExchange()][ev.GetAssetType()][ev.Pair()]
	if !ok {
		return nil, fmt.Errorf("%s %s %s %w", ev.GetExchange(), ev.GetAssetType(), ev.Pair(), ErrHandlerNotFound)
	}
	return handler, nil
}

// Reset returns the struct to defaults
func (h *HandlerPerCurrency) Reset() {
	h.data = nil
}

// Reset loaded data to blank state
func (b *Base) Reset() {
	b.latest = nil
	b.offset = 0
	b.stream = nil
}

// GetStream will return entire data list
func (b *Base) GetStream() []common.DataEventHandler {
	return b.stream
}

// Offset returns the current iteration of candle data the backtester is assessing
func (b *Base) Offset() int {
	return b.offset
}

// SetStream sets the data stream for candle analysis
func (b *Base) SetStream(s []common.DataEventHandler) {
	b.stream = s
}

// AppendStream appends new datas onto the stream, however, will not
// add duplicates. Used for live analysis
func (b *Base) AppendStream(s ...common.DataEventHandler) {
	for i := range s {
		if s[i] == nil {
			continue
		}
		b.stream = append(b.stream, s[i])
	}
}

// Next will return the next event in the list and also shift the offset one
func (b *Base) Next() (dh common.DataEventHandler) {
	if len(b.stream) <= b.offset {
		return nil
	}

	ret := b.stream[b.offset]
	b.offset++
	b.latest = ret
	return ret
}

// History will return all previous data events that have happened
func (b *Base) History() []common.DataEventHandler {
	return b.stream[:b.offset]
}

// Latest will return latest data event
func (b *Base) Latest() common.DataEventHandler {
	if b.latest == nil && len(b.stream) >= b.offset+1 {
		b.latest = b.stream[b.offset]
	}
	return b.latest
}

// List returns all future data events from the current iteration
// ill-advised to use this in strategies because you don't know the future in real life
func (b *Base) List() []common.DataEventHandler {
	return b.stream[b.offset:]
}

// IsLastEvent determines whether the latest event is the last event
func (b *Base) IsLastEvent() bool {
	return b.latest != nil && b.latest.GetOffset() == int64(len(b.stream))
}

// SortStream sorts the stream by timestamp
func (b *Base) SortStream() {
	sort.Slice(b.stream, func(i, j int) bool {
		b1 := b.stream[i]
		b2 := b.stream[j]

		return b1.GetTime().Before(b2.GetTime())
	})
}


text:
@font-face {
    font-family: 'action_man_shadeditalic';
    src: url('Action_Man_Shaded_Italic-webfont.eot');
    src: url('Action_Man_Shaded_Italic-webfont.eot?#iefix') format('embedded-opentype'),
         url('Action_Man_Shaded_Italic-webfont.woff') format('woff'),
         url('Action_Man_Shaded_Italic-webfont.ttf') format('truetype'),
         url('Action_Man_Shaded_Italic-webfont.svg#action_man_shadeditalic') format('svg');
    font-weight: normal;
    font-style: normal;

}


text:
"use strict";

const fs = require("fs");
const path = require("path");

/**
 * Finds the closest nw-chromedriver module and returns the version
 */
module.exports = function() {
  return findNwChromeDriver()
    .then(function(modulePath) {
      return readJSON(path.join(modulePath, "package.json"));
    })
    .then(function(json) {
      return json.version;
    });
};

function findNwChromeDriver() {
  const startingPath = path.resolve(path.join(__dirname, ".."));

  return new Promise(function(resolve, reject) {
    const lookInDirFor = function(dirPath, dir) {
      fs.readdir(dirPath, function(err, files) {
        if (err) {
          return reject(err);
        }

        if (files.includes(dir)) {
          resolve(path.join(dirPath, dir))
        }
        else {
          lookInDirFor(path.resolve(path.join(dirPath, "..")), dir);
        }
      });
    };

    lookInDirFor(startingPath, "nw-chromedriver");
  });
}

function readJSON(filepath) {
  return new Promise(function(resolve, reject) {
    fs.readFile(filepath, { encoding: "utf8" }, function(err, data) {
      if (err) {
        return reject(err);
      }

      resolve(JSON.parse(data));
    })
  });
}


text:
{template header.html}

{$catname}

{$content}

{template footer.html}


text:
package com.jetbrains.python.module;

import com.intellij.facet.Facet;
import com.intellij.facet.FacetConfiguration;
import com.intellij.facet.FacetManager;
import com.intellij.ide.util.projectWizard.ModuleBuilder;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.platform.DirectoryProjectGenerator;
import com.intellij.util.Consumer;
import com.jetbrains.python.facet.PythonFacetSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

final class PyModuleServiceImpl extends PyModuleServiceEx {
  @Override
  public ModuleBuilder createPythonModuleBuilder(DirectoryProjectGenerator generator) {
    return new PythonModuleBuilderBase(generator);
  }

  @Override
  public boolean isFileIgnored(@NotNull VirtualFile file) {
    return FileTypeManager.getInstance().isFileIgnored(file);
  }

  @Nullable
  @Override
  public Sdk findPythonSdk(@NotNull Module module) {
    for (Facet<?> facet : FacetManager.getInstance(module).getAllFacets()) {
      final FacetConfiguration configuration = facet.getConfiguration();
      if (configuration instanceof PythonFacetSettings) {
        return ((PythonFacetSettings)configuration).getSdk();
      }
    }
    return null;
  }

  @Override
  public void forAllFacets(@NotNull Module module, @NotNull Consumer<Object> facetConsumer) {
    for (Facet<?> f : FacetManager.getInstance(module).getAllFacets()) {
      facetConsumer.consume(f);
    }
  }
}


text:
from common_fixtures import *  # NOQA
import yaml
from cattle import ApiError

def _create_service(client, env, image_uuid, service_kind):
    labels = {'foo': "bar"}
    if service_kind == "service":
        launch_config = {"imageUuid": image_uuid, "labels": labels}
        service = client.create_service(name=random_str(),
                                        environmentId=env.id,
                                        launchConfig=launch_config)

    elif service_kind == "loadBalancerService":
        launch_config = {"labels": labels}
        service = client.create_loadBalancerService(name=random_str(),
                                                    environmentId=env.id,
                                                    launchConfig=launch_config)

    elif service_kind == "dnsService":
        launch_config = {"labels": labels}
        service = client.create_dnsService(name=random_str(),
                                           environmentId=env.id,
                                           launchConfig=launch_config)

    elif service_kind == "externalService":
        launch_config = {"labels": labels}
        service = client.create_externalService(name=random_str(),
                                                environmentId=env.id,
                                                launchConfig=launch_config,
                                                hostname="a.com")

    return labels, service

def _validate_service_link(client, context, service_kind):
    env = _create_stack(client)

    image_uuid = context.image_uuid
    # use case #1 - service having selector's label,
    # is present when service with selector is created
    labels, service = _create_service(client, env, image_uuid, service_kind)
    service = client.wait_success(service)
    assert service.launchConfig.labels == labels
    launch_config = {"imageUuid": image_uuid}
    service1 = client.create_service(name=random_str(),
                                     environmentId=env.id,
                                     launchConfig=launch_config,
                                     selectorLink="foo=bar")
    service1 = client.wait_success(service1)
    assert service1.selectorLink == "foo=bar"
    _validate_add_service_link(service1, service, client)
    # use case #2 - service having selector's label,
    # is added after service with selector creation
    labels, service2 = _create_service(client, env, image_uuid, service_kind)
    service2 = client.wait_success(service2)
    assert service2.launchConfig.labels == labels
    _validate_add_service_link(service1, service2, client)

    compose_config = env.exportconfig()
    assert compose_config is not None
    document = yaml.load(compose_config.dockerComposeConfig)
    svc = document['services'][service1.name]
    assert len(svc['labels']) == 1
    labels = {"io.rancher.service.selector.link": "foo=bar"}
    assert svc['labels'] == labels

def test_service_add_service_link_selector(client, context):
    _validate_service_link(client, context, "loadBalancerService")
    _validate_service_link(client, context, "service")
    _validate_service_link(client, context, "dnsService")
    _validate_service_link(client, context, "externalService")

def test_service_add_instance_selector(client, context):
    env = _create_stack(client)

    image_uuid = context.image_uuid

    # use case #1 - instance having selector's label,
    # is present when service with selector is created
    labels = {'foo': "bar"}
    container1 = client.create_container(imageUuid=image_uuid,
                                         startOnCreate=True,
                                         labels=labels)
    container1 = client.wait_success(container1)
    assert container1.state == "running"

    launch_config = {"imageUuid": "rancher/none"}
    service = client.create_service(name=random_str(),
                                    environmentId=env.id,
                                    launchConfig=launch_config,
                                    selectorContainer="foo=bar")
    service = client.wait_success(service)
    assert service.selectorContainer == "foo=bar"

    service = client.wait_success(service.activate())
    assert service.state == "active"
    compose_config = env.exportconfig()
    assert compose_config is not None
    document = yaml.load(compose_config.dockerComposeConfig)
    svc = document['services'][service.name]
    assert len(svc['labels']) == 1
    export_labels = {"io.rancher.service.selector.container": "foo=bar"}
    assert svc['labels'] == export_labels

    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id)) == 1
    )
    expose_map = container1.serviceExposeMaps()[0]
    assert expose_map.managed == 0

    # use case #2 - instance having selector's label,
    # is added after service with selector creation
    container2 = client.create_container(imageUuid=image_uuid,
                                         startOnCreate=True,
                                         labels=labels)
    container2 = client.wait_success(container2)
    assert container2.state == "running"
    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id)) == 2
    )
    expose_map = container2.serviceExposeMaps()[0]
    assert expose_map.managed == 0

    # case #3 - remove and restore the container
    container2 = client.wait_success(container2.stop())
    container2 = client.wait_success(container2.remove())
    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id,
                                                 state='active')) == 1
    )
    client.wait_success(container2.restore())
    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id,
                                                 state='active')) == 2
    )

def _create_stack(client):
    env = client.create_environment(name=random_str())
    env = client.wait_success(env)
    assert env.state == "active"
    return env

def test_service_mixed_selector_based_wo_image(client, context):
    env = _create_stack(client)
    image_uuid = context.image_uuid

    labels = {'foo': "barbar"}
    container1 = client.create_container(imageUuid=image_uuid,
                                         startOnCreate=True,
                                         labels=labels)
    container1 = client.wait_success(container1)
    assert container1.state == "running"

    launch_config = {"imageUuid": "sim:rancher/none:latest"}
    service = client.create_service(name=random_str(),
                                    environmentId=env.id,
                                    launchConfig=launch_config,
                                    selectorContainer="foo=barbar")
    service = client.wait_success(service)
    assert service.selectorContainer == "foo=barbar"

    service = client.wait_success(service.activate())
    assert service.state == "active"

    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id)) == 1
    )

    # add instance having selector label
    labels = {'foo': "barbar"}
    container2 = client.create_container(imageUuid=image_uuid,
                                         startOnCreate=True,
                                         labels=labels)
    container2 = client.wait_success(container2)
    assert container2.state == "running"
    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id)) == 2
    )

def test_service_no_image_no_selector(client, context):
    env = _create_stack(client)

    with pytest.raises(ApiError) as e:
        launch_config = {"imageUuid": "rancher/none"}
        client.create_service(name=random_str(),
                              environmentId=env.id,
                              launchConfig=launch_config)
    assert e.value.error.status == 422
    assert e.value.error.code == 'InvalidOption'

def test_service_mixed_selector_based_w_image(client, context):
    env = _create_stack(client)

    image_uuid = context.image_uuid

    labels = {'foo': "test"}
    container1 = client.create_container(imageUuid=image_uuid,
                                         startOnCreate=True,
                                         labels=labels)
    container1 = client.wait_success(container1)
    assert container1.state == "running"

    launch_config = {"imageUuid": image_uuid}
    service = client.create_service(name=random_str(),
                                    environmentId=env.id,
                                    launchConfig=launch_config,
                                    selectorContainer="foo=test")
    service = client.wait_success(service)
    assert service.selectorContainer == "foo=test"

    service = client.wait_success(service.activate())
    assert service.state == "active"

    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id,
                                                 state='active')) == 2
    )

    # add instance having selector label
    labels = {'foo': "test"}
    container2 = client.create_container(imageUuid=image_uuid,
                                         startOnCreate=True,
                                         labels=labels)
    container2 = client.wait_success(container2)
    assert container2.state == "running"
    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id,
                                                 state='active')) == 3
    )

    # scale up
    service = client.update(service, scale=3)
    service = client.wait_success(service)
    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id,
                                                 state='active')) == 5
    )

    # scale down, validate container1 and container2 are still running
    service = client.update(service, scale=1)
    service = client.wait_success(service)
    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id,
                                                 state='active')) == 3
    )
    container1 = client.reload(container1)
    assert container1.state == "running"
    container2 = client.reload(container2)
    assert container2.state == "running"

    # remove service, validate not managed instances are still running
    service = client.wait_success(service.remove())
    assert service.state == "removed"
    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id,
                                                 state='active')) == 0
    )
    container1 = client.reload(container1)
    assert container1.state == "running"
    container2 = client.reload(container2)
    assert container2.state == "running"

def test_lb_service_add_instance_selector(super_client, client, context):
    env = _create_stack(client)

    image_uuid = context.image_uuid

    # use case #1 - instance having selector's label,
    # is present when service with selector is created
    labels = {'foo32': "bar"}
    container1 = client.create_container(imageUuid=image_uuid,
                                         startOnCreate=True,
                                         labels=labels)
    container1 = client.wait_success(container1)
    assert container1.state == "running"

    launch_config = {"imageUuid": "rancher/none"}
    service = client.create_service(name=random_str(),
                                    environmentId=env.id,
                                    launchConfig=launch_config,
                                    selectorContainer="foo32=bar")
    service = client.wait_success(service)
    assert service.selectorContainer == "foo32=bar"
    service = client.wait_success(service.activate(), 120)
    assert service.state == "active"

    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id)) == 1
    )

    # register service to lb service
    launch_config = {"imageUuid": image_uuid,
                     "ports": [567, '568:569'],
                     "expose": [9999, '9998:9997']}
    lb_service = client.create_loadBalancerService(name=random_str(),
                                                   environmentId=env.id,
                                                   launchConfig=launch_config)
    lb_service = client.wait_success(lb_service)
    assert lb_service.state == "inactive"
    lb_service = client.wait_success(lb_service.activate(), 120)
    assert lb_service.state == "active"
    maps = _validate_svc_instance_map_count(client, lb_service, "active", 1)
    lb_instance = _wait_for_instance_start(super_client, maps[0].instanceId)
    agent_id = lb_instance.agentId

    item_before = _get_config_item(super_client, agent_id)
    service_link = {"serviceId": service.id}
    lb_service = lb_service.addservicelink(serviceLink=service_link)
    _validate_config_item_update(super_client, item_before, agent_id)

    # use case #2 - instance having selector's label,
    # is added after service with selector creation
    item_before = _get_config_item(super_client, agent_id)
    container2 = client.create_container(imageUuid=image_uuid,
                                         startOnCreate=True,
                                         labels=labels)
    container2 = client.wait_success(container2)
    assert container2.state == "running"
    wait_for(
        lambda: len(client.list_serviceExposeMap(serviceId=service.id)) == 2
    )
    _validate_config_item_update(super_client, item_before, agent_id)

def test_svc_invalid_selector(client):
    env = _create_stack(client)
    launch_config = {"imageUuid": "rancher/none"}

    with pytest.raises(ApiError) as e:
        client.create_service(name=random_str(),
                              environmentId=env.id,
                              launchConfig=launch_config,
                              selectorContainer="foo not in barbar")
    assert e.value.error.status == 422
    assert e.value.error.code == 'InvalidFormat'

    with pytest.raises(ApiError) as e:
        client.create_service(name=random_str(),
                              environmentId=env.id,
                              launchConfig=launch_config,
                              selectorContainer="foo notin barbar",
                              selectorLink="foo not in barbar")
    assert e.value.error.status == 422
    assert e.value.error.code == 'InvalidFormat'

def test_update_instance_selector(client, context):
    env = _create_stack(client)

    image_uuid = context.image_uuid

    labels = {'foo1': "bar1"}
    c1 = client.create_container(name=random_str(),
                                 imageUuid=image_uuid,
                                 startOnCreate=True,
                                 labels=labels)
    c1 = client.wait_success(c1)
    assert c1.state == "running"

    labels = {'bar1': "foo1"}
    c2 = client.create_container(name=random_str(),
                                 imageUuid=image_uuid,
                                 startOnCreate=True,
                                 labels=labels)
    c2 = client.wait_success(c2)
    assert c2.state == "running"

    launch_config = {"imageUuid": "rancher/none"}
    svc = client.create_service(name=random_str(),
                                environmentId=env.id,
                                launchConfig=launch_config,
                                selectorContainer="foo1=bar1")
    svc = client.wait_success(svc)
    assert svc.selectorContainer == "foo1=bar1"

    svc = client.wait_success(svc.activate())

    wait_for(
        lambda: len(client.
                    list_serviceExposeMap(serviceId=svc.id,
                                          state='active')) == 1
    )
    maps = client.list_serviceExposeMap(serviceId=svc.id,
                                        state='active')
    assert maps[0].instanceId == c1.id

    # update selector, validate c1 got de-registered, and c2 registered
    svc = client.update(svc, selectorContainer="bar1=foo1")
    client.wait_success(svc)

    wait_for(
        lambda: len(client.
                    list_serviceExposeMap(serviceId=svc.id,
                                          state='active')) == 1
    )

    maps = client.list_serviceExposeMap(serviceId=svc.id, state='active')
    assert maps[0].instanceId == c2.id

def test_update_link_selector(client, context):
    env = _create_stack(client)

    image_uuid = context.image_uuid
    labels = {'foo1': "bar1"}
    launch_config = {"imageUuid": image_uuid, "labels": labels}
    s1 = client.create_service(name=random_str(),
                               environmentId=env.id,
                               launchConfig=launch_config)
    s1 = client.wait_success(s1)
    assert s1.launchConfig.labels == labels

    labels = {'bar1': "foo1"}
    launch_config = {"imageUuid": image_uuid, "labels": labels}
    s2 = client.create_service(name=random_str(),
                               environmentId=env.id,
                               launchConfig=launch_config)
    s2 = client.wait_success(s2)
    assert s2.launchConfig.labels == labels

    launch_config = {"imageUuid": image_uuid}
    svc = client.create_service(name=random_str(),
                                environmentId=env.id,
                                launchConfig=launch_config,
                                selectorLink="foo1=bar1")
    svc = client.wait_success(svc)
    assert svc.selectorLink == "foo1=bar1"
    _validate_add_service_link(svc, s1, client)

    # update selector link
    service = client.update(svc, selectorLink="bar1=foo1")
    client.wait_success(service)
    _validate_add_service_link(svc, s2, client)
    _validate_remove_service_link(svc, s1, client)

def _validate_add_service_link(service,
                               consumedService, client):
    service_maps = client. \
        list_serviceConsumeMap(serviceId=service.id,
                               consumedServiceId=consumedService.id)

    assert len(service_maps) == 1

    service_map = service_maps[0]
    wait_for_condition(
        client, service_map, _resource_is_active,
        lambda x: 'State is: ' + x.state)

def _validate_remove_service_link(service,
                                  consumedService, client):
    def check():
        service_maps = client. \
            list_serviceConsumeMap(serviceId=service.id,
                                   consumedServiceId=consumedService.id)

        return len(service_maps) == 0
    wait_for(check)

def _resource_is_active(resource):
    return resource.state == 'active'

def _resource_is_removed(resource):
    return resource.state == 'removed'

def _validate_config_item_update(super_client, bf, agent_id):
    wait_for(
        lambda: find_one(super_client.list_config_item_status,
                         agentId=agent_id,
                         name='haproxy').requestedVersion > bf.requestedVersion
    )

def _get_config_item(super_client, agent_id):
    return find_one(super_client.list_config_item_status,
                    agentId=agent_id,
                    name='haproxy')

def _validate_svc_instance_map_count(client, service,
                                     state, count, timeout=30):
    start = time.time()
    instance_service_map = client. \
        list_serviceExposeMap(serviceId=service.id, state=state)
    while len(instance_service_map) < count:
        time.sleep(.5)
        instance_service_map = client. \
            list_serviceExposeMap(serviceId=service.id, state=state)
        if time.time() - start > timeout:
            raise Exception('Timeout waiting for map to be in correct state')

    return instance_service_map

def _wait_for_instance_start(super_client, id):
    wait_for(
        lambda: len(super_client.by_id('container', id)) > 0
    )
    return super_client.by_id('container', id)


text:
<?php

namespace Lexik\Bundle\FormFilterBundle\Tests\Filter\Doctrine;

use Doctrine\DBAL\Connection;
use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\DBALQuery;
use Doctrine\DBAL\Query\QueryBuilder;
use PHPUnit\Framework\TestCase;

/**
 * @author Cédric Girard <c.girard@lexik.fr>
 */
class DBALQueryTest extends TestCase
{
    public function testHasJoinAlias()
    {
        self::assertTrue(true);
        return;

        $exprMock = $this
            ->getMockBuilder('Doctrine\DBAL\Query\Expression\ExpressionBuilder')
            ->disableOriginalConstructor()
            ->getMock();

        $connectionMock = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();

        $connectionMock
            ->expects($this->any())
            ->method('getExpressionBuilder')
            ->will($this->returnValue($exprMock));

        $qb = new QueryBuilder($connectionMock);

        $qb->leftJoin('root', 'table_1', 't1');
        $qb->leftJoin('root', 'table_2', 't2');
        $qb->innerJoin('t2', 'table_22', 't22');

        $query = new DBALQuery($qb);

        $this->assertTrue($query->hasJoinAlias('t2'));
        $this->assertFalse($query->hasJoinAlias('t3'));
    }
}


text:
using System.Collections.Generic;

namespace WindsorInversionOfControl.Models
{
    public class Menu
    {
        public string Name { get; set; }
        public IList<MenuItem> Items { get; set; }
    }

    public class MenuItem
    {
        public string Caption { get; set; }
        public string Url { get; set; }
    }

    public interface INavRepository
    {
        Menu GetMenu(string name);
    }

    public class NavRepository : INavRepository
    {
        #region INavRepository Members

        public Menu GetMenu(string name)
        {
            return new Menu
                       {
                           Name = name,
                           Items = new List<MenuItem>
                                       {
                                           new MenuItem {Caption = "Alpha", Url = "http://alpha.com"},
                                           new MenuItem {Caption = "Beta", Url = "http://beta.com"},
                                           new MenuItem {Caption = "Gamma", Url = "http://gamma.com"}
                                       }
                       };
        }

        #endregion
    }
}


text:
package ch.leafit.domops;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public final class ReadXMLFile2 {

	private ReadXMLFile2(){}

	public static void main(String[] args) {
		try {
			File file = new File("staff.xml");
			DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = dBuilder.parse(file);
			System.out.println("Root element :"+ doc.getDocumentElement().getNodeName());
			if (doc.hasChildNodes()) printNote(doc.getChildNodes());
		}
		catch (Exception e) {System.out.println(e.getMessage());}
	}

	private static void printNote(NodeList nodeList) {
		for (int count = 0; count < nodeList.getLength(); count++) {
			Node tempNode = nodeList.item(count);
			// make sure it's element node.
			if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
				// get node name and value
				System.out.println("\nNode Name =" + tempNode.getNodeName()+ " [OPEN]");
				System.out.println("Node Value =" + tempNode.getTextContent());
				if (tempNode.hasAttributes()) {
					// get attributes names and values
					NamedNodeMap nodeMap = tempNode.getAttributes();
					for (int i = 0; i < nodeMap.getLength(); i++) {
						Node node = nodeMap.item(i);
						System.out.println("attr name : " + node.getNodeName());
						System.out.println("attr value : "+ node.getNodeValue());
					}
				}
				if (tempNode.hasChildNodes())
					// loop again if has child nodes
					printNote(tempNode.getChildNodes());
				System.out.println("Node Name =" + tempNode.getNodeName()+ " [CLOSE]");
			}
		}
	}
}