text:
namespace ray {
namespace gcs {

/// GcsActor just wraps `ActorTableData` and provides some convenient interfaces to access
/// the fields inside `ActorTableData`.
/// This class is not thread-safe.
class GcsActor {
 public:
  /// Create a GcsActor by actor_table_data.
  ///
  /// \param actor_table_data Data of the actor (see gcs.proto).
  explicit GcsActor(rpc::ActorTableData actor_table_data)
      : actor_table_data_(std::move(actor_table_data)) {}

  /// Create a GcsActor by TaskSpec.
  ///
  /// \param task_spec Contains the actor creation task specification.
  explicit GcsActor(const ray::rpc::TaskSpec &task_spec, std::string ray_namespace) {
    RAY_CHECK(task_spec.type() == TaskType::ACTOR_CREATION_TASK);
    const auto &actor_creation_task_spec = task_spec.actor_creation_task_spec();
    actor_table_data_.set_actor_id(actor_creation_task_spec.actor_id());
    actor_table_data_.set_job_id(task_spec.job_id());
    actor_table_data_.set_max_restarts(actor_creation_task_spec.max_actor_restarts());
    actor_table_data_.set_num_restarts(0);

    auto dummy_object = TaskSpecification(task_spec).ActorDummyObject().Binary();
    actor_table_data_.set_actor_creation_dummy_object_id(dummy_object);

    actor_table_data_.set_is_detached(actor_creation_task_spec.is_detached());
    actor_table_data_.set_name(actor_creation_task_spec.name());
    actor_table_data_.mutable_owner_address()->CopyFrom(task_spec.caller_address());

    actor_table_data_.set_state(rpc::ActorTableData::DEPENDENCIES_UNREADY);
    actor_table_data_.mutable_task_spec()->CopyFrom(task_spec);

    actor_table_data_.mutable_address()->set_raylet_id(NodeID::Nil().Binary());
    actor_table_data_.mutable_address()->set_worker_id(WorkerID::Nil().Binary());

    actor_table_data_.set_ray_namespace(ray_namespace);

    const auto &function_descriptor = task_spec.function_descriptor();
    switch (function_descriptor.function_descriptor_case()) {
    case rpc::FunctionDescriptor::FunctionDescriptorCase::kJavaFunctionDescriptor:
      actor_table_data_.set_class_name(
          function_descriptor.java_function_descriptor().class_name());
      break;
    case rpc::FunctionDescriptor::FunctionDescriptorCase::kPythonFunctionDescriptor:
      actor_table_data_.set_class_name(
          function_descriptor.python_function_descriptor().class_name());
      break;
    default:
      // TODO (Alex): Handle the C++ case, which we currently don't have an
      // easy equivalent to class_name for.
      break;
    }

    actor_table_data_.set_serialized_runtime_env(task_spec.serialized_runtime_env());
  }

  /// Get the node id on which this actor is created.
  NodeID GetNodeID() const;
  /// Get the id of the worker on which this actor is created.
  WorkerID GetWorkerID() const;
  /// Get the actor's owner ID.
  WorkerID GetOwnerID() const;
  /// Get the node ID of the actor's owner.
  NodeID GetOwnerNodeID() const;
  /// Get the address of the actor's owner.
  const rpc::Address &GetOwnerAddress() const;

  /// Update the `Address` of this actor (see gcs.proto).
  void UpdateAddress(const rpc::Address &address);
  /// Get the `Address` of this actor.
  const rpc::Address &GetAddress() const;

  /// Update the state of this actor.
  void UpdateState(rpc::ActorTableData::ActorState state);
  /// Get the state of this gcs actor.
  rpc::ActorTableData::ActorState GetState() const;

  /// Get the id of this actor.
  ActorID GetActorID() const;
  /// Returns whether or not this is a detached actor.
  bool IsDetached() const;
  /// Get the name of this actor.
  std::string GetName() const;
  /// Get the namespace of this actor.
  std::string GetRayNamespace() const;
  /// Get the task specification of this actor.
  TaskSpecification GetCreationTaskSpecification() const;

  /// Get the immutable ActorTableData of this actor.
  const rpc::ActorTableData &GetActorTableData() const;
  /// Get the mutable ActorTableData of this actor.
  rpc::ActorTableData *GetMutableActorTableData();

 private:
  /// The actor meta data which contains the task specification as well as the state of
  /// the gcs actor and so on (see gcs.proto).
  rpc::ActorTableData actor_table_data_;
};

using RegisterActorCallback = std::function<void(std::shared_ptr<GcsActor>)>;
using CreateActorCallback = std::function<void(std::shared_ptr<GcsActor>)>;

/// GcsActorManager is responsible for managing the lifecycle of all actors.
/// This class is not thread-safe.
/// Actor State Transition Diagram:
///                                                        3
///  0                       1                   2        --->
/// --->DEPENDENCIES_UNREADY--->PENDING_CREATION--->ALIVE      RESTARTING
///             |                      |              |   <---      |
///           8 |                    7 |            6 |     4       | 5
///             |                      v              |             |
///              ------------------> DEAD <-------------------------
///
/// 0: When GCS receives a `RegisterActor` request from core worker, it will add an actor
/// to `registered_actors_` and `unresolved_actors_`.
/// 1: When GCS receives a `CreateActor` request from core worker, it will remove the
/// actor from `unresolved_actors_` and schedule the actor.
/// 2: GCS selects a node to lease worker. If the worker is successfully leased,
/// GCS will push actor creation task to the core worker, else GCS will select another
/// node to lease worker. If the actor is created successfully, GCS will add the actor to
/// `created_actors_`.
/// 3: When GCS detects that the worker/node of an actor is dead, it
/// will get actor from `registered_actors_` by actor id. If the actor's remaining
/// restarts number is greater than 0, it will reconstruct the actor.
/// 4: When the actor is successfully reconstructed, GCS will update its state to `ALIVE`.
/// 5: If the actor is restarting, GCS detects that its worker or node is dead and its
/// remaining restarts number is 0, it will update its state to `DEAD`. If the actor is
/// detached, GCS will remove it from `registered_actors_` and `created_actors_`. If the
/// actor is non-detached, when GCS detects that its owner is dead, GCS will remove it
/// from `registered_actors_`.
/// 6: When GCS detected that an actor is dead, GCS will
/// reconstruct it. If its remaining restarts number is 0, it will update its state to
/// `DEAD`. If the actor is detached, GCS will remove it from `registered_actors_` and
/// `created_actors_`. If the actor is non-detached, when GCS detects that its owner is
/// dead, it will destroy the actor and remove it from `registered_actors_` and
/// `created_actors_`.
/// 7: If the actor is non-detached, when GCS detects that its owner is
/// dead, it will destroy the actor and remove it from `registered_actors_` and
/// `created_actors_`.
/// 8: For both detached and non-detached actors, when GCS detects that
/// an actor's creator is dead, it will update its state to `DEAD` and remove it from
/// `registered_actors_` and `created_actors_`. Because in this case, the actor can never
/// be created. If the actor is non-detached, when GCS detects that its owner is dead, it
/// will update its state to `DEAD` and remove it from `registered_actors_` and
/// `created_actors_`.
class GcsActorManager : public rpc::ActorInfoHandler {
 public:
  /// Create a GcsActorManager
  ///
  /// \param scheduler Used to schedule actor creation tasks.
  /// \param gcs_table_storage Used to flush actor data to storage.
  /// \param gcs_pub_sub Used to publish gcs message.
  GcsActorManager(
      std::shared_ptr<GcsActorSchedulerInterface> scheduler,
      std::shared_ptr<gcs::GcsTableStorage> gcs_table_storage,
      std::shared_ptr<gcs::GcsPubSub> gcs_pub_sub, RuntimeEnvManager &runtime_env_manager,
      std::function<void(const ActorID &)> destroy_ownded_placement_group_if_needed,
      std::function<std::string(const JobID &)> get_ray_namespace,
      std::function<void(std::function<void(void)>, boost::posix_time::milliseconds)>
          run_delayed,
      const rpc::ClientFactoryFn &worker_client_factory = nullptr);

  ~GcsActorManager() = default;

  void HandleRegisterActor(const rpc::RegisterActorRequest &request,
                           rpc::RegisterActorReply *reply,
                           rpc::SendReplyCallback send_reply_callback) override;

  void HandleCreateActor(const rpc::CreateActorRequest &request,
                         rpc::CreateActorReply *reply,
                         rpc::SendReplyCallback send_reply_callback) override;

  void HandleGetActorInfo(const rpc::GetActorInfoRequest &request,
                          rpc::GetActorInfoReply *reply,
                          rpc::SendReplyCallback send_reply_callback) override;

  void HandleGetNamedActorInfo(const rpc::GetNamedActorInfoRequest &request,
                               rpc::GetNamedActorInfoReply *reply,
                               rpc::SendReplyCallback send_reply_callback) override;

  void HandleGetAllActorInfo(const rpc::GetAllActorInfoRequest &request,
                             rpc::GetAllActorInfoReply *reply,
                             rpc::SendReplyCallback send_reply_callback) override;

  void HandleKillActorViaGcs(const rpc::KillActorViaGcsRequest &request,
                             rpc::KillActorViaGcsReply *reply,
                             rpc::SendReplyCallback send_reply_callback) override;

  /// Register actor asynchronously.
  ///
  /// \param request Contains the meta info to create the actor.
  /// \param success_callback Will be invoked after the actor is created successfully or
  /// be invoked immediately if the actor is already registered to `registered_actors_`
  /// and its state is `ALIVE`.
  /// \return Status::Invalid if this is a named actor and an
  /// actor with the specified name already exists. The callback will not be called in
  /// this case.
  Status RegisterActor(const rpc::RegisterActorRequest &request,
                       RegisterActorCallback success_callback);

  /// Create actor asynchronously.
  ///
  /// \param request Contains the meta info to create the actor.
  /// \param callback Will be invoked after the actor is created successfully or be
  /// invoked immediately if the actor is already registered to `registered_actors_` and
  /// its state is `ALIVE`.
  /// \return Status::Invalid if this is a named actor and an actor with the specified
  /// name already exists. The callback will not be called in this case.
  Status CreateActor(const rpc::CreateActorRequest &request,
                     CreateActorCallback callback);

  /// Get the actor ID for the named actor. Returns nil if the actor was not found.
  /// \param name The name of the detached actor to look up.
  /// \returns ActorID The ID of the actor. Nil if the actor was not found.
  ActorID GetActorIDByName(const std::string &name,
                           const std::string &ray_namespace) const;

  /// Schedule actors in the `pending_actors_` queue.
  /// This method should be called when new nodes are registered or resources
  /// change.
  void SchedulePendingActors();

  /// Handle a node death. This will restart all actors associated with the
  /// specified node id, including actors which are scheduled or have been
  /// created on this node. Actors whose owners have died (possibly due to this
  /// node being removed) will not be restarted. If any workers on this node
  /// owned an actor, those actors will be destroyed.
  ///
  /// \param node_id The specified node id.
  void OnNodeDead(const NodeID &node_id);

  /// Handle a worker failure. This will restart the associated actor, if any,
  /// which may be pending or already created. If the worker owned other
  /// actors, those actors will be destroyed.
  ///
  /// \param node_id ID of the node where the dead worker was located.
  /// \param worker_id ID of the dead worker.
  /// \param exit_type exit reason of the dead worker.
  /// \param creation_task_exception if this arg is set, this worker is died because of an
  /// exception thrown in actor's creation task.
  void OnWorkerDead(
      const NodeID &node_id, const WorkerID &worker_id,
      const rpc::WorkerExitType disconnect_type,
      const std::shared_ptr<rpc::RayException> &creation_task_exception = nullptr);

  void OnWorkerDead(const NodeID &node_id, const WorkerID &worker_id);

  /// Handle actor creation task failure. This should be called when scheduling
  /// an actor creation task is infeasible.
  ///
  /// \param actor The actor whose creation task is infeasible.
  void OnActorCreationFailed(std::shared_ptr<GcsActor> actor);

  /// Handle actor creation task success. This should be called when the actor
  /// creation task has been scheduled successfully.
  ///
  /// \param actor The actor that has been created.
  void OnActorCreationSuccess(const std::shared_ptr<GcsActor> &actor);

  /// Initialize with the gcs tables data synchronously.
  /// This should be called when GCS server restarts after a failure.
  ///
  /// \param gcs_init_data.
  void Initialize(const GcsInitData &gcs_init_data);

  /// Delete non-detached actor information from durable storage once the associated job
  /// finishes.
  ///
  /// \param job_id The id of finished job.
  void OnJobFinished(const JobID &job_id);

  /// Get the created actors.
  ///
  /// \return The created actors.
  const absl::flat_hash_map<NodeID, absl::flat_hash_map<WorkerID, ActorID>>
      &GetCreatedActors() const;

  const absl::flat_hash_map<ActorID, std::shared_ptr<GcsActor>> &GetRegisteredActors()
      const;

  const absl::flat_hash_map<ActorID, std::vector<RegisterActorCallback>>
      &GetActorRegisterCallbacks() const;

  /// Collect stats from gcs actor manager in-memory data structures.
  void CollectStats() const;

  std::string DebugString() const;

 private:
  /// A data structure representing an actor's owner.
  struct Owner {
    Owner(std::shared_ptr<rpc::CoreWorkerClientInterface> client)
        : client(std::move(client)) {}
    /// A client that can be used to contact the owner.
    std::shared_ptr<rpc::CoreWorkerClientInterface> client;
    /// The IDs of actors owned by this worker.
    absl::flat_hash_set<ActorID> children_actor_ids;
  };

  /// Poll an actor's owner so that we will receive a notification when the
  /// actor has gone out of scope, or the owner has died. This should not be
  /// called for detached actors.
  void PollOwnerForActorOutOfScope(const std::shared_ptr<GcsActor> &actor);

  /// Destroy an actor that has gone out of scope. This cleans up all local
  /// state associated with the actor and marks the actor as dead. For owned
  /// actors, this should be called when all actor handles have gone out of
  /// scope or the owner has died.
  /// NOTE: This method can be called multiple times in out-of-order and should be
  /// idempotent.
  void DestroyActor(const ActorID &actor_id);

  /// Get unresolved actors that were submitted from the specified node.
  absl::flat_hash_set<ActorID> GetUnresolvedActorsByOwnerNode(
      const NodeID &node_id) const;

  /// Get unresolved actors that were submitted from the specified worker.
  absl::flat_hash_set<ActorID> GetUnresolvedActorsByOwnerWorker(
      const NodeID &node_id, const WorkerID &worker_id) const;

  /// Reconstruct the specified actor.
  ///
  /// \param actor The target actor to be reconstructed.
  /// \param need_reschedule Whether to reschedule the actor creation task, sometimes
  /// users want to kill an actor intentionally and don't want it to be reconstructed
  /// again.
  /// \param creation_task_exception Only applies when need_reschedule=false, decribing
  /// why this actor failed. If this arg is set, it means this actor died because of an
  /// exception thrown in creation task.
  void ReconstructActor(
      const ActorID &actor_id, bool need_reschedule,
      const std::shared_ptr<rpc::RayException> &creation_task_exception = nullptr);

  /// Reconstruct the specified actor and reschedule it.
  void ReconstructActor(const ActorID &actor_id);

  /// Remove the specified actor from `unresolved_actors_`.
  ///
  /// \param actor The actor to be removed.
  void RemoveUnresolvedActor(const std::shared_ptr<GcsActor> &actor);

  /// Remove the specified actor from owner.
  ///
  /// \param actor The actor to be removed.
  void RemoveActorFromOwner(const std::shared_ptr<GcsActor> &actor);

  /// Kill the specified actor.
  ///
  /// \param actor_id ID of the actor to kill.
  /// \param force_kill Whether to force kill an actor by killing the worker.
  /// \param no_restart If set to true, the killed actor will not be restarted anymore.
  void KillActor(const ActorID &actor_id, bool force_kill, bool no_restart);

  /// Notify CoreWorker to kill the specified actor.
  ///
  /// \param actor The actor to be killed.
  /// \param force_kill Whether to force kill an actor by killing the worker.
  /// \param no_restart If set to true, the killed actor will not be restarted anymore.
  void NotifyCoreWorkerToKillActor(const std::shared_ptr<GcsActor> &actor,
                                   bool force_kill = true, bool no_restart = true);

  /// Add the destroyed actor to the cache. If the cache is full, one actor is randomly
  /// evicted.
  ///
  /// \param actor The actor to be killed.
  void AddDestroyedActorToCache(const std::shared_ptr<GcsActor> &actor);

  std::shared_ptr<rpc::ActorTableData> GenActorDataOnlyWithStates(
      const rpc::ActorTableData &actor) {
    auto actor_delta = std::make_shared<rpc::ActorTableData>();
    actor_delta->set_state(actor.state());
    actor_delta->set_allocated_creation_task_exception(
        new rpc::RayException(actor.creation_task_exception()));
    actor_delta->mutable_address()->CopyFrom(actor.address());
    actor_delta->set_num_restarts(actor.num_restarts());
    actor_delta->set_timestamp(actor.timestamp());
    actor_delta->set_pid(actor.pid());
    return actor_delta;
  }

  /// Cancel actor which is either being scheduled or is pending scheduling.
  ///
  /// \param actor The actor to be cancelled.
  /// \param task_id The id of actor creation task to be cancelled.
  void CancelActorInScheduling(const std::shared_ptr<GcsActor> &actor,
                               const TaskID &task_id);

  /// Callbacks of pending `RegisterActor` requests.
  /// Maps actor ID to actor registration callbacks, which is used to filter duplicated
  /// messages from a driver/worker caused by some network problems.
  absl::flat_hash_map<ActorID, std::vector<RegisterActorCallback>>
      actor_to_register_callbacks_;
  /// Callbacks of actor creation requests.
  /// Maps actor ID to actor creation callbacks, which is used to filter duplicated
  /// messages come from a Driver/Worker caused by some network problems.
  absl::flat_hash_map<ActorID, std::vector<CreateActorCallback>>
      actor_to_create_callbacks_;
  /// All registered actors (unresoved and pending actors are also included).
  /// TODO(swang): Use unique_ptr instead of shared_ptr.
  absl::flat_hash_map<ActorID, std::shared_ptr<GcsActor>> registered_actors_;
  /// All destroyed actors.
  absl::flat_hash_map<ActorID, std::shared_ptr<GcsActor>> destroyed_actors_;
  /// The actors are sorted according to the timestamp, and the oldest is at the head of
  /// the list.
  std::list<std::pair<ActorID, int64_t>> sorted_destroyed_actor_list_;
  /// Maps actor names to their actor ID for lookups by name, first keyed by their
  /// namespace.
  absl::flat_hash_map<std::string, absl::flat_hash_map<std::string, ActorID>>
      named_actors_;
  /// The actors which dependencies have not been resolved.
  /// Maps from worker ID to a client and the IDs of the actors owned by that worker.
  /// The actor whose dependencies are not resolved should be destroyed once it creator
  /// dies.
  absl::flat_hash_map<NodeID, absl::flat_hash_map<WorkerID, absl::flat_hash_set<ActorID>>>
      unresolved_actors_;
  /// The pending actors which will not be scheduled until there's a resource change.
  std::vector<std::shared_ptr<GcsActor>> pending_actors_;
  /// Map contains the relationship of node and created actors. Each node ID
  /// maps to a map from worker ID to the actor created on that worker.
  absl::flat_hash_map<NodeID, absl::flat_hash_map<WorkerID, ActorID>> created_actors_;
  /// Map from worker ID to a client and the IDs of the actors owned by that
  /// worker. An owned actor should be destroyed once it has gone out of scope,
  /// according to its owner, or the owner dies.
  absl::flat_hash_map<NodeID, absl::flat_hash_map<WorkerID, Owner>> owners_;

  /// The scheduler to schedule all registered actors.
  std::shared_ptr<gcs::GcsActorSchedulerInterface> gcs_actor_scheduler_;
  /// Used to update actor information upon creation, deletion, etc.
  std::shared_ptr<gcs::GcsTableStorage> gcs_table_storage_;
  /// A publisher for publishing gcs messages.
  std::shared_ptr<gcs::GcsPubSub> gcs_pub_sub_;
  /// Factory to produce clients to workers. This is used to communicate with
  /// actors and their owners.
  rpc::ClientFactoryFn worker_client_factory_;
  /// A callback that is used to destroy placemenet group owned by the actor.
  /// This method MUST BE IDEMPOTENT because it can be called multiple times during
  /// actor destroy process.
  std::function<void(const ActorID &)> destroy_owned_placement_group_if_needed_;
  /// A callback to get the namespace an actor belongs to based on its job id. This is
  /// necessary for actor creation.
  std::function<std::string(const JobID &)> get_ray_namespace_;
  RuntimeEnvManager &runtime_env_manager_;
  /// Run a function on a delay. This is useful for guaranteeing data will be
  /// accessible for a minimum amount of time.
  std::function<void(std::function<void(void)>, boost::posix_time::milliseconds)>
      run_delayed_;
  const boost::posix_time::milliseconds actor_gc_delay_;

  // Debug info.
  enum CountType {
    REGISTER_ACTOR_REQUEST = 0,
    CREATE_ACTOR_REQUEST = 1,
    GET_ACTOR_INFO_REQUEST = 2,
    GET_NAMED_ACTOR_INFO_REQUEST = 3,
    GET_ALL_ACTOR_INFO_REQUEST = 4,
    KILL_ACTOR_REQUEST = 5,
    CountType_MAX = 6,
  };
  uint64_t counts_[CountType::CountType_MAX] = {0};
};

}  // namespace gcs
}  // namespace ray


text:
There are two forms of testing run on a pull request. Static analysis, run
automatically, and operational testing, run when a maintainer flags a pull
request as being ready. The operational testing is run on Kubernertes test
infrastructure.

### Static Analysis

Static analysis is performed on every pull request and is run by CircleCI. The
configuration is stored in the [`.circleci/config.yml`](../.circleci/config.yml)
file.

The static analysis currently:

* Performs `helm lint` on any changed charts to provide quick feedback

### Operational Testing

#### Procedure

Pull requests testing is run via the [Kuberentes Test Infrastructure](https://github.com/kubernetes/test-infra).

The configuration of the Pull Request trigger is [in the config.json](https://github.com/kubernetes/test-infra/blob/827797c54b48295045698465b437f463ca9276c2/jobs/config.json#L10285).

This snippet tells Test Infra to run the [test/e2e.sh](https://github.com/kubernetes/charts/blob/master/test/e2e.sh)
when testing is triggered on a pull request. The e2e.sh script will use the [Charts test image](https://github.com/kubernetes/charts/blob/master/test/Dockerfile)
to run the [test/changed.sh](https://github.com/kubernetes/charts/blob/master/test/changed.sh) script. This script
is the main logic for validation of a pull request. It intends to only test charts that have changed in this PR.

The logic is as follows:

1. [Get credentials for the Kubernetes cluster used for testing.](https://github.com/kubernetes/charts/blob/master/test/changed.sh#L42)
1. [Install and initialize Helm](https://github.com/kubernetes/charts/blob/master/test/changed.sh#L47)
1. [For any charts that have changed](https://github.com/kubernetes/charts/blob/master/test/changed.sh#L62):
    - Download dependent charts, if any, with `helm dep update`
    - Run `helm install` in a new namespace for this PR+build
    - Use the [test/verify-release.sh](https://github.com/kubernetes/charts/blob/master/test/verify-release.sh) to ensure that if any pods were launched that they get to the `Running` state
    - Run `helm test` on the release
    - Delete the release

#### Triggering

In order for the tests to be kicked off one of the
[Kubernetes member](https://github.com/orgs/kubernetes/people) must add the
"ok-to-test" label. This can also be done by commenting "/ok-to-test" on the pull request.

This check is there to ensure that PRs are spot checked for any nefarious code. There are 2 things to check for:

1. No changes have been made to file in the test folder that unnecessarily alter the testing procedures.
1. The chart is not using images whose provenance is not traceable (usually done via the sources metadata field).

## Repo syncing

The syncing of charts to the stable and incubator repos happens from a Jenkins instance that is polling for changes
to the master branch. On each change it will use the [test/repo-sync.sh](https://github.com/kubernetes/charts/blob/master/test/repo-sync.sh)
to update the public repositories. The procedure is as follows:

1. [Setup Helm](https://github.com/kubernetes/charts/blob/master/test/repo-sync.sh#L16)
1. [Authenticate to Google Cloud so that we can upload to the Cloud Storage bucket that hosts the charts](https://github.com/kubernetes/charts/blob/master/test/repo-sync.sh#L27)
1. For the stable and incubator folders:
   - Download the existing index.yaml from the repository
   - Run `helm dep update` on all the charts in the current repository
   - Run `helm package` on each chart
   - Recreate the index using `helm repo index`
   - Upload the repostory using `gsutil rsync`

redpajama_set_name: RedPajamaGithub


text:
{MESSAGES}

<form method="post" action="{URI|htmlspecialchars}">

	<fieldset class="single">
		<legend>{PRODUCT.name} - {PRODUCT.variety.name}</legend>

			Code (SKU)
			<input type="text" name="product[variety][sku]" value="{PRODUCT.variety.sku}"/>

			Weight Gross [{VARIETY_CONF.weight_units}]
			<input type="text" name="product[variety][weight_gross]" value="{PRODUCT.variety.weight_gross}"/> (used for postage)

			Stock
			<input type="text" name="product[variety][stock]" value="{PRODUCT.variety.stock}"/>

	</fieldset>

		Show Advanced Settings

			Weight Net [{VARIETY_CONF.weight_units}]
			<input type="text" name="product[variety][weight]" value="{PRODUCT.variety.weight}"/>

		<fieldset>
			<legend>Dimensions</legend>

				Width [{VARIETY_CONF.dimension_units}]
				<input type="text" name="product[variety][width]" value="{PRODUCT.variety.width}"/>

				Height [{VARIETY_CONF.dimension_units}]
				<input type="text" name="product[variety][height]" value="{PRODUCT.variety.height}"/>

				Depth [{VARIETY_CONF.dimension_units}]
				<input type="text" name="product[variety][depth]" value="{PRODUCT.variety.depth}"/>

				Diameter [{VARIETY_CONF.dimension_units}]
				<input type="text" name="product[variety][diameter]" value="{PRODUCT.variety.diameter}"/>

		</fieldset>

	<button class="save" type="submit" name="save" value="save">Save</button>

	<input type="hidden" name="product[variety][id]" value="{PRODUCT.variety.id}"/>
	<input type="hidden" name="product[variety][product_id]" value="{PRODUCT.variety.product_id}"/>

<input type="hidden" name="csrf_token" value="{CSRF_TOKEN}" />
</form>


text:
System.register(['angular2/testing', './scroll.service'], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var scroll_service_1;
    return {
        setters:[
            function (_1) {},
            function (scroll_service_1_1) {
                scroll_service_1 = scroll_service_1_1;
            }],
        execute: function() {
            describe('ScrollService', function () {
                var scroll;
                beforeEach(function () {
                    scroll = new scroll_service_1.ScrollService;
                });
                describe('#scrollTop', function () {
                    it('should scroll up', function () {
                        document.body.scrollTop = 10;
                        scroll.scrollTop();
                        expect(document.body.scrollTop).toEqual(0);
                    });
                });
            });
        }
    }
});
//# sourceMappingURL=scroll.service.spec.js.map


text:
{% macro render_field(field, providers=[], class='') -%}
 0 %} q_unique {% endif -%}
  {%- for provider in providers %} q_{{provider}}{% endfor -%}
  ">

  {{ field.label.text }}

  {{ field(class="field_input", **kwargs) }}

{% endmacro %}

{% macro render_check(field, providers=[], class='') -%}

 0 %} q_unique {% endif -%}
  {%- for provider in providers %} q_{{provider}}{% endfor -%}
  ">

  {{ field.label.text }}

  {{ field(class="field_input", **kwargs) }}

{% endmacro %}

{% macro render_multifield(multifield_slug, multifield_label, subfields, providers=[], class='', subclass='') -%}

 0 %} q_unique {% endif -%}
  {%- for provider in providers %} q_{{provider}}{% endfor -%}
  ">

    {{ multifield_label }}

  {% for field in subfields %}

        {{ field.label.text }}

      {{ field(class="field_input", **kwargs) }}

  {% endfor %}

{% endmacro %}


text:
A text input bar that is keyboard aware, and resizes its content based on the amount of text

![alt tag](https://raw.githubusercontent.com/aryaxt/TextInputBar/master/textInputBar.png)

Features:
- Text view automatically resizes based on content
- Allows setting max size for text view height
- If the outlet to the scrollView is set, the contentInset is automatically adjusted to ensure that the keyboard isn't cvering the content
- No need to write any setup code

Instruction
- Drag and drop a UIToolbar to IB (or init in code)
- Change its class to TextInputBar
- Pin toolbar to bottom layout guide
- Set the delegate to the viewController (Can be done both in code or IB)
- Set the scrollView outlet if you have one (Can be done both in code or IB)
- Set maximum size of textview (Can be done both in code or IB)


text:
import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col, Form, FormGroup } from 'react-bootstrap';
import { connect } from 'react-redux';
import { Field, reduxForm, formValueSelector } from 'redux-form';
import styles from './loginStyles.css';
import inputField from '../common/form/inputField';
import validate from './loginValidation';

let LoginForm = ({ submissionError, handleSubmit, pristine, submitting, hasUsername, hasPassword }) => {
  return (
    <Row className={styles.loginContainer}>
      <Form onSubmit={handleSubmit} horizontal>
        <legend>Login</legend>
        {
          submissionError ?
            <div className={styles.loginError}>
              There was a problem logging in. Please check your credentials and try again.
            </div> :
            ''
         }
        <FormGroup controlId="formHorizontalUsername">
          <Col sm={2}>
            Username
          </Col>
          <Col sm={10}>
            <Field
              name="username"
              component={inputField}
            />
          </Col>
        </FormGroup>

        <FormGroup controlId="formHorizontalPassword">
          <Col sm={2}>
            Password
          </Col>
          <Col sm={10}>
            <Field
              name="password"
              component={inputField}
              type="password"
            />
          </Col>
        </FormGroup>

        <FormGroup>
          <Col smOffset={2} sm={10}>
            <button type="submit" className="btn btn-default" disabled={!hasUsername || !hasPassword || pristine || submitting}>
              Sign in
            </button>
          </Col>
        </FormGroup>
      </Form>
    </Row>
  );
};

LoginForm.propTypes = {
  onFormChange: PropTypes.func,
  onFormSubmit: PropTypes.func,
  handleSubmit: PropTypes.func,
  submitting: PropTypes.bool,
  pristine: PropTypes.bool,
  hasUsername: PropTypes.string,
  hasPassword: PropTypes.string,
  submissionError: PropTypes.object
};

LoginForm = reduxForm({
  form: 'loginForm',
  validate
})(LoginForm);

const selector = formValueSelector('loginForm');
LoginForm = connect(state => {
  const submissionError = state.userData.error;
  const hasUsername = selector(state, 'username');
  const hasPassword = selector(state, 'password');
  return {
    hasUsername,
    hasPassword,
    submissionError
  };
})(LoginForm);

export default LoginForm;


text:
@interface MCServiceVC ()

@end

@implementation MCServiceVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initMCClientVCUI];
    [self loadData];
}

- (void)initMCClientVCUI
{
    self.navigationItem.title = @"MC-Client";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];

}

- (void)loadData
{
    [self addDataWithTitle:@"各种图表" andDetail:@"数据分布图标"];

}

- (void)clickCellWithTitle:(NSString *)title
{

    if ([title isEqualToString:@"各种图表"])
    {
//        EvaluateStarsVC *vc = [[EvaluateStarsVC alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
        return;
    }

}

- (void)dealloc
{
    [Tools NSLogClassDestroy:self];

}

@end


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

    /* ngInject */
    function Reporting(ReportingOptions) {

        var module = {
            getReportingOptions: getReportingOptions
        };
        return module;

        function getReportingOptions() {
            return ReportingOptions;
        }
    }

    angular.module('nih.routing')
    .factory('Reporting', Reporting);

})();


text:
var Equation = require("./Equation"),
    vec2 = require('../math/vec2');

module.exports = ContactEquation;

/**
 * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive.
 *
 * @class ContactEquation
 * @constructor
 * @extends Equation
 * @param {Body} bodyA
 * @param {Body} bodyB
 */
function ContactEquation(bodyA, bodyB){
    Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE);

    /**
     * Vector from body i center of mass to the contact point.
     * @property contactPointA
     * @type {Array}
     */
    this.contactPointA = vec2.create();
    this.penetrationVec = vec2.create();

    /**
     * World-oriented vector from body A center of mass to the contact point.
     * @property contactPointB
     * @type {Array}
     */
    this.contactPointB = vec2.create();

    /**
     * The normal vector, pointing out of body i
     * @property normalA
     * @type {Array}
     */
    this.normalA = vec2.create();

    /**
     * The restitution to use (0=no bounciness, 1=max bounciness).
     * @property restitution
     * @type {Number}
     */
    this.restitution = 0;

    /**
     * This property is set to true if this is the first impact between the bodies (not persistant contact).
     * @property firstImpact
     * @type {Boolean}
     * @readOnly
     */
    this.firstImpact = false;

    /**
     * The shape in body i that triggered this contact.
     * @property shapeA
     * @type {Shape}
     */
    this.shapeA = null;

    /**
     * The shape in body j that triggered this contact.
     * @property shapeB
     * @type {Shape}
     */
    this.shapeB = null;
}
ContactEquation.prototype = new Equation();
ContactEquation.prototype.constructor = ContactEquation;
ContactEquation.prototype.computeB = function(a,b,h){
    var bi = this.bodyA,
        bj = this.bodyB,
        ri = this.contactPointA,
        rj = this.contactPointB,
        xi = bi.position,
        xj = bj.position;

    var n = this.normalA,
        G = this.G;

    // Caluclate cross products
    var rixn = vec2.crossLength(ri,n),
        rjxn = vec2.crossLength(rj,n);

    // G = [-n -rixn n rjxn]
    G[0] = -n[0];
    G[1] = -n[1];
    G[2] = -rixn;
    G[3] = n[0];
    G[4] = n[1];
    G[5] = rjxn;

    // Compute iteration
    var GW, Gq;
    if(this.firstImpact && this.restitution !== 0){
        Gq = 0;
        GW = (1/b)*(1+this.restitution) * this.computeGW();
    } else {
        // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector
        var penetrationVec = this.penetrationVec;
        addSubSub(penetrationVec,xj,rj,xi,ri);
        Gq = vec2.dot(n,penetrationVec) + this.offset;
        GW = this.computeGW();
    }

    var GiMf = this.computeGiMf();
    var B = - Gq * a - GW * b - h*GiMf;

    return B;
};

function addSubSub(out, a, b, c, d){
    out[0] = a[0] + b[0] - c[0] - d[0];
    out[1] = a[1] + b[1] - c[1] - d[1];
}

var vi = vec2.create();
var vj = vec2.create();
var relVel = vec2.create();

/**
 * Get the relative velocity along the normal vector.
 * @method getVelocityAlongNormal
 * @return {number}
 */
ContactEquation.prototype.getVelocityAlongNormal = function(){

    this.bodyA.getVelocityAtPoint(vi, this.contactPointA);
    this.bodyB.getVelocityAtPoint(vj, this.contactPointB);

    vec2.subtract(relVel, vi, vj);

    return vec2.dot(this.normalA, relVel);
};


text:
<?php
namespace Chamilo\Application\Weblcms\Tool\Implementation\Search\Component;

use Chamilo\Application\Weblcms\Rights\WeblcmsRights;
use Chamilo\Application\Weblcms\Storage\DataClass\ContentObjectPublication;
use Chamilo\Application\Weblcms\Tool\Implementation\Search\Form\SearchForm;
use Chamilo\Application\Weblcms\Tool\Implementation\Search\Manager;
use Chamilo\Core\Repository\ContentObject\Introduction\Storage\DataClass\Introduction;
use Chamilo\Core\Repository\Storage\DataClass\ContentObject;
use Chamilo\Libraries\Format\Structure\BreadcrumbTrail;
use Chamilo\Libraries\Format\Tabs\DynamicContentTab;
use Chamilo\Libraries\Format\Tabs\DynamicTabsRenderer;
use Chamilo\Libraries\Platform\Session\Request;
use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Storage\Parameters\DataClassRetrievesParameters;
use Chamilo\Libraries\Storage\Query\Condition\AndCondition;
use Chamilo\Libraries\Storage\Query\Condition\EqualityCondition;
use Chamilo\Libraries\Storage\Query\Condition\InequalityCondition;
use Chamilo\Libraries\Storage\Query\Condition\NotCondition;
use Chamilo\Libraries\Storage\Query\Condition\OrCondition;
use Chamilo\Libraries\Storage\Query\Condition\PatternMatchCondition;
use Chamilo\Libraries\Storage\Query\Variable\PropertyConditionVariable;
use Chamilo\Libraries\Storage\Query\Variable\StaticConditionVariable;
use Chamilo\Libraries\Utilities\String\Text;

/**
 *
 * @package Chamilo\Application\Weblcms\Tool\Implementation\Search\Component
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 */
class SearcherComponent extends Manager
{
    /**
     * Number of results per page
     */
    const RESULTS_PER_PAGE = 10;

    /**
     *
     * @var \Chamilo\Application\Weblcms\Tool\Implementation\Search\Form\SearchForm
     */
    private $searchForm;

    /**
     *
     * @return \Chamilo\Application\Weblcms\Tool\Implementation\Search\Form\SearchForm
     */
    public function getSearchForm()
    {
        if (! isset($this->searchForm))
        {
            $this->searchForm = new SearchForm(
                $this->get_url(
                    array(\Chamilo\Application\Weblcms\Tool\Manager::PARAM_ACTION => self::ACTION_SEARCH)));
        }

        return $this->searchForm;
    }

    // Inherited
    public function run()
    {
        $html = array();

        $html[] = $this->render_header();

        $html[] = '
';
        $html[] = '
';
        $html[] = $this->getSearchForm()->render();
        $html[] = '
';
        $html[] = '
';

        // If form validates, show results
        $query = $this->get_query();
        if ($query)
        {
            $course_groups = $this->get_course_groups();

            $course_group_ids = array();

            foreach ($course_groups as $course_group)
            {
                $course_group_ids[] = $course_group->get_id();
            }

            $publications = \Chamilo\Application\Weblcms\Storage\DataManager::retrieves(
                ContentObjectPublication::class_name(),
                new DataClassRetrievesParameters($this->get_retrieve_publications_condition()));

            $tools = array();

            while ($publication = $publications->next_result())
            {
                if ($this->is_allowed(WeblcmsRights::VIEW_RIGHT, $publication) &&
                     (! $publication->is_hidden() || $this->is_allowed(WeblcmsRights::EDIT_RIGHT)))
                {
                    $tools[$publication->get_tool()][] = $publication;
                }
            }

            $results = 0;

            $tabs = new DynamicTabsRenderer('search');

            foreach ($tools as $tool => $publications)
            {
                $resultsHtml = array();

                if (strpos($tool, 'feedback') !== false)
                {
                    continue;
                }

                $objects = array();

                foreach ($publications as $publication)
                {
                    $lo = $publication->get_content_object();
                    $lo_title = $lo->get_title();
                    $lo_description = strip_tags($lo->get_description());

                    if (stripos($lo_title, $query) !== false || stripos($lo_description, $query) !== false)
                    {
                        $objects[] = $publication;
                    }
                }

                $count = count($objects);

                if ($count > 0)
                {

                    $toolName = Translation::get(
                        'TypeName',
                        null,
                        \Chamilo\Application\Weblcms\Tool\Manager::get_tool_type_namespace($tool));

                    $results += $count;

                    foreach ($objects as $pub)
                    {
                        $object = $pub->get_content_object();

                        if ($object->get_type() != Introduction::class_name())
                        {
                            $url = $this->get_url(
                                array(
                                    \Chamilo\Application\Weblcms\Manager::PARAM_TOOL => $pub->get_tool(),
                                    \Chamilo\Application\Weblcms\Tool\Manager::PARAM_PUBLICATION_ID => $pub->get_id(),
                                    \Chamilo\Application\Weblcms\Tool\Manager::PARAM_ACTION => \Chamilo\Application\Weblcms\Tool\Manager::ACTION_VIEW));
                        }
                        else
                        {
                            $url = '#';
                        }

                        $resultsHtml[] = '
';

                        $resultsHtml[] = '
';
                        $resultsHtml[] = '
';
                        $resultsHtml[] = '' . $object->get_icon_image() . '' .
                             Text::highlight($object->get_title(), $query) . '';
                        $resultsHtml[] = '
';
                        $resultsHtml[] = '
';

                        $resultsHtml[] = '
';
                        $resultsHtml[] = Text::highlight(strip_tags($object->get_description()), $query);
                        $resultsHtml[] = '
';

                        $resultsHtml[] = '
';
                    }

                    $tabLabel = $toolName . ' ' . $count . '';

                    $tabs->add_tab(new DynamicContentTab($tool, $tabLabel, null, implode(PHP_EOL, $resultsHtml)));
                }
            }

            $variable = ($results > 1 ? 'ResultsFoundFor' : 'ResultFoundFor');

            $html[] = '
';
            $html[] = Translation::get($variable, array('COUNT' => $results, 'QUERY' => $query));
            $html[] = '
';

            if ($results > 0)
            {
                $html[] = $tabs->render();
            }
        }

        $html[] = $this->render_footer();

        return implode(PHP_EOL, $html);
    }

    public function get_condition()
    {
        $query = $this->get_query();
        if (! $query)
        {
            $query = Request::post('query');
        }

        if (isset($query) && $query != '')
        {
            $conditions[] = new PatternMatchCondition(
                new PropertyConditionVariable(ContentObject::class_name(), ContentObject::PROPERTY_TITLE),
                '*' . $query . '*');
            $conditions[] = new PatternMatchCondition(
                new PropertyConditionVariable(ContentObject::class_name(), ContentObject::PROPERTY_DESCRIPTION),
                '*' . $query . '*');
            return new OrCondition($conditions);
        }

        return null;
    }

    public function get_query()
    {
        $query = trim($this->getSearchForm()->getQuery());
        if ($query == '')
        {
            return null;
        }

        return $query;
    }

    /**
     *
     * @return AndCondition
     */
    protected function get_retrieve_publications_condition()
    {
        $conditions = array();

        $conditions[] = new EqualityCondition(
            new PropertyConditionVariable(
                ContentObjectPublication::class_name(),
                ContentObjectPublication::PROPERTY_COURSE_ID),
            new StaticConditionVariable($this->get_course_id()));
        $conditions[] = new NotCondition(
            new EqualityCondition(
                new PropertyConditionVariable(
                    ContentObjectPublication::class_name(),
                    ContentObjectPublication::PROPERTY_TOOL),
                new StaticConditionVariable('home')));

        if (! $this->get_course()->is_course_admin($this->get_user()))
        {
            $from_date_variables = new PropertyConditionVariable(
                ContentObjectPublication::class_name(),
                ContentObjectPublication::PROPERTY_FROM_DATE);

            $to_date_variable = new PropertyConditionVariable(
                ContentObjectPublication::class_name(),
                ContentObjectPublication::PROPERTY_TO_DATE);

            $time_conditions = array();

            $time_conditions[] = new EqualityCondition(
                new PropertyConditionVariable(
                    ContentObjectPublication::class_name(),
                    ContentObjectPublication::PROPERTY_HIDDEN),
                new StaticConditionVariable(0));

            $forever_conditions = array();

            $forever_conditions[] = new EqualityCondition($from_date_variables, new StaticConditionVariable(0));

            $forever_conditions[] = new EqualityCondition($to_date_variable, new StaticConditionVariable(0));

            $forever_condition = new AndCondition($forever_conditions);

            $between_conditions = array();

            $between_conditions[] = new InequalityCondition(
                $from_date_variables,
                InequalityCondition::LESS_THAN_OR_EQUAL,
                new StaticConditionVariable(time()));

            $between_conditions[] = new InequalityCondition(
                $to_date_variable,
                InequalityCondition::GREATER_THAN_OR_EQUAL,
                new StaticConditionVariable(time()));

            $between_condition = new AndCondition($between_conditions);

            $time_conditions[] = new OrCondition(array($forever_condition, $between_condition));

            $conditions[] = new AndCondition($time_conditions);
        }

        $condition = new AndCondition($conditions);

        return $condition;
    }

    /**
     *
     * @param BreadcrumbTrail $breadcrumbtrail
     */
    public function add_additional_breadcrumbs(BreadcrumbTrail $breadcrumbtrail)
    {
    }
}


text:
require "kitchen/terraform/command/workspace_delete"

::RSpec.describe ::Kitchen::Terraform::Command::WorkspaceDelete do
  subject do
    described_class.new config: config
  end

  let :config do
    { workspace_name: "test" }
  end

  describe "#to_s" do
    specify "should return the command" do
      expect(subject.to_s).to eq "workspace delete test"
    end
  end
end


text:
package org.apache.flink.streaming.examples.iterative.kmeans;

public class KMeansMap {

}


text:
/**
 *
  Package: MAG - VistA Imaging
  WARNING: Per VHA Directive 2004-038, this routine should not be modified.
  Date Created: Jun 17, 2011
  Site Name:  Washington OI Field Office, Silver Spring, MD
  Developer:  VHAISWWERFEJ
  Description:

        ;; +--------------------------------------------------------------------+
        ;; Property of the US Government.
        ;; No permission to copy or redistribute this software is given.
        ;; Use of unreleased versions of this software requires the user
        ;;  to execute a written test agreement with the VistA Imaging
        ;;  Development Office of the Department of Veterans Affairs,
        ;;  telephone (301) 734-0100.
        ;;
        ;; The Food and Drug Administration classifies this software as
        ;; a Class II medical device.  As such, it may not be changed
        ;; in any way.  Modifications to this software may result in an
        ;; adulterated medical device under 21CFR820, the use of which
        ;; is considered to be a violation of US Federal Statutes.
        ;; +--------------------------------------------------------------------+

 */
package gov.va.med.imaging;

import gov.va.med.SERIALIZATION_FORMAT;
import gov.va.med.URNFactory;
import gov.va.med.WellKnownOID;
import gov.va.med.imaging.exceptions.URNFormatException;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 * @author VHAISWWERFEJ
 *
 */
public class ImageAnnotationURNTest
{

	@Test
	public void testAnnotationURN()
	throws URNFormatException
	{
		String originatingSiteId = "siteId";
		String annotationId = "annotationId";
		String imageId = "imageId";
		String patientId = "patId";

		ImageAnnotationURN urn =
			ImageAnnotationURN.create(originatingSiteId, annotationId, imageId, patientId);
		System.out.println(urn.toString());
		System.out.println(urn.toStringCDTP());
		//System.out.println(urn.toURI());
		System.out.println(urn.toString(SERIALIZATION_FORMAT.CDTP));
		System.out.println(urn.toString(SERIALIZATION_FORMAT.NATIVE));
		System.out.println(urn.toString(SERIALIZATION_FORMAT.PATCH83_VFTP));
		System.out.println(urn.toString(SERIALIZATION_FORMAT.RAW));
		System.out.println(urn.toString(SERIALIZATION_FORMAT.RFC2141));
		System.out.println(urn.toString(SERIALIZATION_FORMAT.VFTP));

		ImageAnnotationURN urn2 =
			URNFactory.create("urn:vaannotation:siteId-annotationId-imageId-patId");
		System.out.println(urn2.toString());

		assertEquals(urn.toString(), urn2.toString());

		ImageAnnotationURN badUrn =
			URNFactory.create("urn:vaannotation:siteId-annotationId-bad-patId");
		assertNotSame(urn, badUrn);

		assertEquals(originatingSiteId, urn.getOriginatingSiteId());
		assertEquals(originatingSiteId, urn.getRepositoryUniqueId());
		assertEquals(originatingSiteId, urn2.getOriginatingSiteId());
		assertEquals(originatingSiteId, urn2.getRepositoryUniqueId());

		assertEquals(urn.getDocumentUniqueId(), urn2.getDocumentUniqueId());
		assertEquals(annotationId, urn.getAnnotationId());
		assertEquals(annotationId, urn2.getAnnotationId());

		assertEquals(patientId, urn.getPatientId());
		assertEquals(patientId, urn.getPatientIdentifier());
		assertEquals(patientId, urn2.getPatientId());
		assertEquals(patientId, urn2.getPatientIdentifier());

		assertEquals(imageId, urn.getImageId());
		assertEquals(imageId, urn2.getImageId());

		assertEquals(WellKnownOID.VA_RADIOLOGY_IMAGE.getCanonicalValue().toString(),
				urn.getHomeCommunityId());
		assertEquals(WellKnownOID.VA_RADIOLOGY_IMAGE.getCanonicalValue().toString(),
				urn2.getHomeCommunityId());

	}

}


text:
        ColorPicker
        ColorPicker is an input component to select a color.

Inline

Selected Color:  {{color1}}

Overlay

Selected Color: {{color2}}

Import

import {ColorPickerModule} from 'primeng/colorpicker';

Getting Started

ColorPicker uses ngModel directive to bind a value.

<p-colorPicker [(ngModel)]="color"></p-colorPicker>

export class MyComponent {

    color: string;

}

Formats

Default color format to use in value binding is "hex" and other possible values are "rgb" and "hsb".
                Example below has 3 colorpickers having default values with different formats.

<p-colorPicker [(ngModel)]="color1"></p-colorPicker>
<p-colorPicker [(ngModel)]="color2" format="rgb"></p-colorPicker>
<p-colorPicker [(ngModel)]="color3" format="hsb"></p-colorPicker>

export class MyComponent {

    color1: string;

    color2: any = {
        r: 100, g: 130, b: 150
    };

    color3: any = {
        h: 100, s: 50, b: 50
    };

}

Overlay and Inline

ColorPicker can be displayed as inline or as an overlay (default) using the "inline" property.

<p-colorPicker [(ngModel)]="color1" ></p-colorPicker>
<p-colorPicker [(ngModel)]="color2" [inline]="true"></p-colorPicker>

Model Driven Forms

Dropdown can be used in a model driven form as well.

<p-colorPicker formControlName="color"></p-dropdown>

Properties

                            Name
                            Type
                            Default
                            Description

                            style
                            string
                            null
                            Inline style of the component.

                            styleClass
                            string
                            null
                            Style class of the component.

                            inline
                            boolean
                            false
                            Whether to display as an overlay or not.

                            format
                            string
                            hex
                            Format to use in value binding, supported formats are "hex", "rgb" and "hsb".

                            appendTo
                            any
                            null
                            Target element to attach the overlay, valid values are "body" or a local ng-template variable of another element.

                            tabindex
                            number
                            null
                            Index of the element in tabbing order.

                            disabled
                            boolean
                            false
                            When present, it specifies that the component should be disabled.

                            inputId
                            string
                            null
                            Identifier of the focus input to match a label defined for the dropdown.

                            baseZIndex
                            number
                            0
                            Base zIndex value to use in layering.

                            autoZIndex
                            boolean
                            true
                            Whether to automatically manage layering.

Events

                    Name
                    Parameters
                    Description

                        onChange
                        event.originalEvent: Browser event

                            event.value: Selected color

                        Callback to invoke when a color is selected.

Styling

Following is the list of structural style classes, for theming classes visit theming page.

                        Name
                        Element

                        ui-colorpicker
                        Container element.

                        ui-colorpicker-overlay
                        Container element in overlay mode.

                        ui-colorpicker-preview
                        Preview input in overlay mode.

                        ui-colorpicker-panel
                        Panel element of the colorpicker.

                        ui-colorpicker-content
                        Wrapper that contains color and hue sections.

                        ui-colorpicker-color-selector
                        Color selector container.

                        ui-colorpicker-color
                        Color element.

                        ui-colorpicker-color-handle
                        Handle of the color element.

                        ui-colorpicker-hue
                        Hue slider.

                        ui-colorpicker-hue-handle
                        Handle of the hue slider.

Dependencies

None.

                View on GitHub

<h3 class="first">Inline</h3>
<p-colorPicker [(ngModel)]="color1" [inline]="true"></p-colorPicker>

<p style="margin-top:.5em">Selected Color: <span style="display:inline-block;width:32px;height:32px;vertical-align:middle" [style.backgroundColor]="color1"></span> {{color1}} </p>

<h3>Overlay</h3>
<p-colorPicker [(ngModel)]="color2"></p-colorPicker>

<p style="margin-top:.5em">Selected Color: <span [ngStyle]="{'color':color2}">{{color2}}</span></p>

export class ColorPickerDemo {

    color1: string;

    color2: string = '#1976D2';
}


text:
package com.speedment.common.codegen.internal.model;

import com.speedment.common.codegen.internal.util.Copier;
import com.speedment.common.codegen.model.AnnotationUsage;
import com.speedment.common.codegen.model.Constructor;
import com.speedment.common.codegen.model.Field;
import com.speedment.common.codegen.model.Generic;
import com.speedment.common.codegen.model.Import;
import com.speedment.common.codegen.model.Javadoc;
import com.speedment.common.codegen.model.modifier.Modifier;
import com.speedment.common.codegen.model.trait.HasConstructors;

import java.lang.reflect.Type;
import java.util.*;

import static java.util.Objects.requireNonNull;

/**
 * This is the default implementation of the {@link Constructor} interface. This
 * class should not be instantiated directly. Instead you should call the
 * {@link Constructor#of()} method to get an instance. In that way, you can
 * later change the implementing class without modifying the using code.
 *
 * @author Emil Forslund
 * @see Constructor
 */
public final class ConstructorImpl implements Constructor {

    private HasConstructors<?> parent;
    private Javadoc javadoc;
    private final List<Import> imports;
    private final List<AnnotationUsage> annotations;
    private final List<Generic> generics;
    private final List<Field> params;
    private final List<String> code;
    private final Set<Modifier> modifiers;
    private final Set<Type> exceptions;

    /**
     * Initializes this constructor.
     *

     * Warning! This class should not be instantiated directly but using
     * the {@link Constructor#of()} method!
     */
    public ConstructorImpl() {
        javadoc     = null;
        imports     = new ArrayList<>();
        annotations = new ArrayList<>();
        generics    = new ArrayList<>();
        params      = new ArrayList<>();
        code        = new ArrayList<>();
        modifiers   = new HashSet<>();
        exceptions  = new HashSet<>();
    }

    /**
     * Copy constructor.
     *
     * @param prototype the prototype
     */
    private ConstructorImpl(final Constructor prototype) {
        javadoc     = requireNonNull(prototype).getJavadoc().map(Copier::copy).orElse(null);
        imports     = Copier.copy(prototype.getImports());
        annotations = Copier.copy(prototype.getAnnotations());
        generics    = Copier.copy(prototype.getGenerics());
        params      = Copier.copy(prototype.getFields());
        code        = Copier.copy(prototype.getCode(), c -> c);
        modifiers   = Copier.copy(prototype.getModifiers(), Modifier::copy, EnumSet.noneOf(Modifier.class));
        exceptions  = new LinkedHashSet<>(prototype.getExceptions());
    }

    @Override
    public Constructor setParent(HasConstructors<?> parent) {
        this.parent = parent;
        return this;
    }

    @Override
    public Optional<HasConstructors<?>> getParent() {
        return Optional.ofNullable(parent);
    }

    @Override
    public List<Import> getImports() {
        return imports;
    }

    @Override
    public List<Field> getFields() {
        return params;
    }

    @Override
    public List<String> getCode() {
        return code;
    }

    @Override
    public Set<Modifier> getModifiers() {
        return modifiers;
    }

    @Override
    public Constructor set(Javadoc doc) {
        javadoc = doc.setParent(this);
        return this;
    }

    @Override
    public Optional<Javadoc> getJavadoc() {
        return Optional.ofNullable(javadoc);
    }

    @Override
    public List<AnnotationUsage> getAnnotations() {
        return annotations;
    }

    @Override
    public List<Generic> getGenerics() {
        return generics;
    }

    @Override
    public Set<Type> getExceptions() {
        return exceptions;
    }

    @Override
    public ConstructorImpl copy() {
        return new ConstructorImpl(this);
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 43 * hash + HashUtil.identityHashForParent(this); // Avoid stack overflow
        hash = 43 * hash + Objects.hashCode(this.javadoc);
        hash = 43 * hash + Objects.hashCode(this.imports);
        hash = 43 * hash + Objects.hashCode(this.annotations);
        hash = 43 * hash + Objects.hashCode(this.generics);
        hash = 43 * hash + Objects.hashCode(this.params);
        hash = 43 * hash + Objects.hashCode(this.code);
        hash = 43 * hash + Objects.hashCode(this.modifiers);
        hash = 43 * hash + Objects.hashCode(this.exceptions);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final ConstructorImpl other = (ConstructorImpl) obj;
        if (!Objects.equals(this.parent, other.parent)) {
            return false;
        }
        if (!Objects.equals(this.javadoc, other.javadoc)) {
            return false;
        }
        if (!Objects.equals(this.imports, other.imports)) {
            return false;
        }
        if (!Objects.equals(this.annotations, other.annotations)) {
            return false;
        }
        if (!Objects.equals(this.generics, other.generics)) {
            return false;
        }
        if (!Objects.equals(this.params, other.params)) {
            return false;
        }
        if (!Objects.equals(this.code, other.code)) {
            return false;
        }
        if (!Objects.equals(this.modifiers, other.modifiers)) {
            return false;
        }
        return Objects.equals(this.exceptions, other.exceptions);
    }

}


text:
local M = {}
local pex = require "com.ponywolf.pex"

function M.new(instance)
  if not instance then error("ERROR: Expected display object") end
  local parent = instance.parent
  --print("file = " .. instance.filename, instance.filename:gsub(".pex", ".png"))
  local particle = pex.load(instance.filename, instance.filename:gsub(".pex", ".png"))
  local emitter = display.newEmitter(particle)
  emitter.absolutePosition = false
  emitter.x,emitter.y = instance.x, instance.y
  emitter.alpha = instance.alpha
  instance.isVisible = false -- get rid of placeholder
  instance.emitter = emitter
  parent:insert(instance.emitter)
  return instance
end

return M


text:
var Constants = require('jsr-constants')
  , ArrayIndex = require('./array-index')
  , BEFORE = Constants.PIVOT.BEFORE
  , TYPE_NAMES = Constants.TYPE_NAMES;

/**
 *  Represents the list type.
 */
function List(source) {
  this._rtype = TYPE_NAMES.LIST;
  this._data = source || [];
}

/**
 *  Sets the list element at index to value.
 */
function lset(index, value) {
  if(index < 0) index = this._data.length + index;
  // command should validate the index
  if(index < 0 || index >= this._data.length) return null;
  this._data[index] = value;
}

/**
 *  Inserts value in the list either before or after
 *  the reference value pivot.
 */
function linsert(beforeAfter, pivot, value) {
  //console.dir(pivot);
  //console.dir(this._data);
  var ind = this.indexOf(pivot);
  if(ind === -1) return ind;
  // note beforeAfter can be a buffer
  ind = (('' + beforeAfter) === BEFORE) ? ind : ind + 1;
  this._data.splice(ind, 0, value);
  return this._data.length;
}

/**
 *  Returns the element at index `index` in the list.
 */
function lindex(index) {
  if(index < 0) index = this._data.length + index;
  return this._data[index] || null;
}

/**
 *  Insert elements at the head of the list.
 */
function lpush(elements) {
  this._data.unshift.apply(this._data, elements);
  return this._data.length;
}

/**
 *  Insert elements at the tail of the list.
 */
function rpush(elements) {
  this._data.push.apply(this._data, elements);
  return this._data.length;
}

/**
 *  Removes and returns the first element in the list.
 */
function lpop() {
  var val = this._data.shift();
  return val !== undefined ? val : null;
}

/**
 *  Removes and returns the last element in the list.
 */
function rpop() {
  var val = this._data.pop();
  return val !== undefined ? val : null;
}

/**
 *  Removes elements from the list.
 */
function lrem(count, value) {
  var ind, deleted = 0;
  if(count === 0) {
    while((ind = this.indexOf(value)) !== -1) {
      this._data.splice(ind, 1);
      deleted++;
    }
  }else if(count > 0) {
    while((ind = this.indexOf(value)) !== -1 && (deleted < count)) {
      this._data.splice(ind, 1);
      deleted++;
    }
  }else{
    count = Math.abs(count);
    while((ind = this.lastIndexOf(value)) !== -1 && (deleted < count)) {
      this._data.splice(ind, 1);
      deleted++;
    }
  }
  return deleted;
}

/**
 *  Trim an existing list so that it will contain only
 *  the specified range of elements.
 */
function ltrim(start, stop) {
  this._data = this.lrange(start, stop);
}

/**
 *  Returns the specified elements of the list.
 */
function lrange(start, stop) {
  if(start < 0) start = this._data.length + start;
  if(stop < 0) stop = this._data.length + stop;
  stop++;
  return this._data.slice(start, stop);
}

/**
 *  Return the length of the list.
 */
function llen() {
  return this._data.length;
}

function indexOf(value) {
  return ArrayIndex.indexOf(value, this._data);
}

function lastIndexOf(value) {
  return ArrayIndex.lastIndexOf(value, this._data);
}

function getData() {
  return this._data;
}

/**
 *  @private
 *
 *  Consistent internal api for getting length.
 */
function getLength() {
  return this._data.length;
}

Object.defineProperty(List.prototype, 'rtype', {
  get: function getType() {
    return this._rtype;
  }
})

Object.defineProperty(List.prototype, 'data', {
  get: getData
})

List.prototype.lset = lset;
List.prototype.linsert = linsert;
List.prototype.lindex = lindex;
List.prototype.lpush = lpush;
List.prototype.rpush = rpush;
List.prototype.lpop = lpop;
List.prototype.rpop = rpop;
List.prototype.lrem = lrem;
List.prototype.ltrim = ltrim;
List.prototype.lrange = lrange;
List.prototype.llen = llen;

List.prototype.getLength = getLength;
List.prototype.indexOf = indexOf;
List.prototype.lastIndexOf = lastIndexOf;
List.prototype.getData = getData;

module.exports = List;


text:
<?php

namespace Katsana\Sdk\One;

use Katsana\Sdk\Query;
use Laravie\Codex\Contracts\Response;

class Fleets extends Request
{
    /**
     * List all vehicles available for the user.
     *
     * @param \Katsana\Sdk\Query|null $query
     *
     * @return \Katsana\Sdk\Response
     */
    public function all(?Query $query = null): Response
    {
        $this->requiresAccessToken();

        return $this->send(
            'GET', 'fleets', $this->getApiHeaders(), $this->buildHttpQuery($query)
        );
    }

    /**
     * Show single fleet.
     *
     * @param int                     $fleetId
     * @param \Katsana\Sdk\Query|null $query
     *
     * @return \Katsana\Sdk\Response
     */
    public function get(int $fleetId, ?Query $query = null): Response
    {
        $this->requiresAccessToken();

        return $this->send(
            'GET', "fleets/{$fleetId}", $this->getApiHeaders(), $this->buildHttpQuery($query)
        );
    }
}


text:
import uuid

from keystone import notifications
from keystone.openstack.common.fixture import moxstubout
from keystone.openstack.common.notifier import api as notifier_api
from keystone import tests
from keystone.tests import test_v3

EXP_RESOURCE_TYPE = uuid.uuid4().hex

class ArbitraryException(Exception):
    pass

class NotificationsWrapperTestCase(tests.TestCase):
    def setUp(self):
        super(NotificationsWrapperTestCase, self).setUp()

        self.exp_resource_id = None
        self.exp_operation = None
        self.exp_host = None
        self.send_notification_called = False

        def fake_notify(operation, resource_type, resource_id, host=None):
            self.assertEqual(self.exp_operation, operation)
            self.assertEqual(EXP_RESOURCE_TYPE, resource_type)
            self.assertEqual(self.exp_resource_id, resource_id)
            self.assertEqual(self.exp_host, host)
            self.send_notification_called = True

        fixture = self.useFixture(moxstubout.MoxStubout())
        self.stubs = fixture.stubs

        self.stubs.Set(notifications, '_send_notification', fake_notify)

    @notifications.created(EXP_RESOURCE_TYPE)
    def create_resource(self, resource_id, data):
        return data

    def test_resource_created_notification(self):
        self.exp_operation = 'created'
        self.exp_resource_id = uuid.uuid4().hex
        exp_resource_data = {
            'id': self.exp_resource_id,
            'key': uuid.uuid4().hex}
        self.exp_host = None

        self.create_resource(self.exp_resource_id, exp_resource_data)
        self.assertTrue(self.send_notification_called)

    @notifications.updated(EXP_RESOURCE_TYPE)
    def update_resource(self, resource_id, data):
        return data

    def test_resource_updated_notification(self):
        self.exp_operation = 'updated'
        self.exp_resource_id = uuid.uuid4().hex
        exp_resource_data = {
            'id': self.exp_resource_id,
            'key': uuid.uuid4().hex}
        self.exp_host = None

        self.update_resource(self.exp_resource_id, exp_resource_data)
        self.assertTrue(self.send_notification_called)

    @notifications.deleted(EXP_RESOURCE_TYPE)
    def delete_resource(self, resource_id):
        pass

    def test_resource_deleted_notification(self):
        self.exp_operation = 'deleted'
        self.exp_resource_id = uuid.uuid4().hex
        self.exp_host = None

        self.delete_resource(self.exp_resource_id)
        self.assertTrue(self.send_notification_called)

    @notifications.created(EXP_RESOURCE_TYPE)
    def create_exception(self, resource_id):
        raise ArbitraryException()

    def test_create_exception_without_notification(self):
        self.assertRaises(
            ArbitraryException, self.create_exception, uuid.uuid4().hex)
        self.assertFalse(self.send_notification_called)

    @notifications.created(EXP_RESOURCE_TYPE)
    def update_exception(self, resource_id):
        raise ArbitraryException()

    def test_update_exception_without_notification(self):
        self.assertRaises(
            ArbitraryException, self.update_exception, uuid.uuid4().hex)
        self.assertFalse(self.send_notification_called)

    @notifications.deleted(EXP_RESOURCE_TYPE)
    def delete_exception(self, resource_id):
        raise ArbitraryException()

    def test_delete_exception_without_notification(self):
        self.assertRaises(
            ArbitraryException, self.delete_exception, uuid.uuid4().hex)
        self.assertFalse(self.send_notification_called)

class NotificationsTestCase(tests.TestCase):
    def setUp(self):
        super(NotificationsTestCase, self).setUp()
        fixture = self.useFixture(moxstubout.MoxStubout())
        self.stubs = fixture.stubs

    def test_send_notification(self):
        """Test the private method _send_notification to ensure event_type,
           payload, and context are built and passed properly.
        """

        resource = uuid.uuid4().hex
        resource_type = EXP_RESOURCE_TYPE
        operation = 'created'
        host = None

        # NOTE(ldbragst): Even though notifications._send_notification doesn't
        # contain logic that creates cases, this is suppose to test that
        # context is always empty and that we ensure the resource ID of the
        # resource in the notification is contained in the payload. It was
        # agreed that context should be empty in Keystone's case, which is
        # also noted in the /keystone/notifications.py module. This test
        # ensures and maintains these conditions.
        def fake_notify(context, publisher_id, event_type, priority, payload):
            exp_event_type = 'identity.project.created'
            self.assertEqual(exp_event_type, event_type)
            exp_context = {}
            self.assertEqual(exp_context, context)
            exp_payload = {'resource_info': 'some_resource_id'}
            self.assertEqual(exp_payload, payload)

        self.stubs.Set(notifier_api, 'notify', fake_notify)
        notifications._send_notification(resource, resource_type, operation,
                                         host=host)

class NotificationsForEntities(test_v3.RestfulTestCase):
    def setUp(self):
        super(NotificationsForEntities, self).setUp()

        self.exp_resource_id = None
        self.exp_operation = None
        self.exp_resource_type = None
        self.send_notification_called = False

        def fake_notify(operation, resource_type, resource_id, host=None):
            self.exp_resource_id = resource_id
            self.exp_operation = operation
            self.exp_resource_type = resource_type
            self.send_notification_called = True

        fixture = self.useFixture(moxstubout.MoxStubout())
        self.stubs = fixture.stubs

        self.stubs.Set(notifications, '_send_notification', fake_notify)

    def _assertLastNotify(self, resource_id, operation, resource_type):
        self.assertIs(self.exp_operation, operation)
        self.assertIs(self.exp_resource_id, resource_id)
        self.assertIs(self.exp_resource_type, resource_type)
        self.assertTrue(self.send_notification_called)

    def test_create_group(self):
        group_ref = self.new_group_ref(domain_id=self.domain_id)
        self.identity_api.create_group(group_ref['id'], group_ref)
        self._assertLastNotify(group_ref['id'], 'created', 'group')

    def test_create_project(self):
        project_ref = self.new_project_ref(domain_id=self.domain_id)
        self.assignment_api.create_project(project_ref['id'], project_ref)
        self._assertLastNotify(project_ref['id'], 'created', 'project')

    def test_create_role(self):
        role_ref = self.new_role_ref()
        self.assignment_api.create_role(role_ref['id'], role_ref)
        self._assertLastNotify(role_ref['id'], 'created', 'role')

    def test_create_user(self):
        user_ref = self.new_user_ref(domain_id=self.domain_id)
        self.identity_api.create_user(user_ref['id'], user_ref)
        self._assertLastNotify(user_ref['id'], 'created', 'user')

    def test_delete_group(self):
        group_ref = self.new_group_ref(domain_id=self.domain_id)
        self.identity_api.create_group(group_ref['id'], group_ref)
        self.identity_api.delete_group(group_ref['id'])
        self._assertLastNotify(group_ref['id'], 'deleted', 'group')

    def test_delete_project(self):
        project_ref = self.new_project_ref(domain_id=self.domain_id)
        self.assignment_api.create_project(project_ref['id'], project_ref)
        self.assignment_api.delete_project(project_ref['id'])
        self._assertLastNotify(project_ref['id'], 'deleted', 'project')

    def test_delete_role(self):
        role_ref = self.new_role_ref()
        self.assignment_api.create_role(role_ref['id'], role_ref)
        self.assignment_api.delete_role(role_ref['id'])
        self._assertLastNotify(role_ref['id'], 'deleted', 'role')

    def test_delete_user(self):
        user_ref = self.new_user_ref(domain_id=self.domain_id)
        self.identity_api.create_user(user_ref['id'], user_ref)
        self.identity_api.delete_user(user_ref['id'])
        self._assertLastNotify(user_ref['id'], 'deleted', 'user')

    def test_update_group(self):
        group_ref = self.new_group_ref(domain_id=self.domain_id)
        self.identity_api.create_group(group_ref['id'], group_ref)
        self.identity_api.update_group(group_ref['id'], group_ref)
        self._assertLastNotify(group_ref['id'], 'updated', 'group')

    def test_update_project(self):
        project_ref = self.new_project_ref(domain_id=self.domain_id)
        self.assignment_api.create_project(project_ref['id'], project_ref)
        self.assignment_api.update_project(project_ref['id'], project_ref)
        self._assertLastNotify(project_ref['id'], 'updated', 'project')

    def test_update_role(self):
        role_ref = self.new_role_ref()
        self.assignment_api.create_role(role_ref['id'], role_ref)
        self.assignment_api.update_role(role_ref['id'], role_ref)
        self._assertLastNotify(role_ref['id'], 'updated', 'role')

    def test_update_user(self):
        user_ref = self.new_user_ref(domain_id=self.domain_id)
        self.identity_api.create_user(user_ref['id'], user_ref)
        self.identity_api.update_user(user_ref['id'], user_ref)
        self._assertLastNotify(user_ref['id'], 'updated', 'user')


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" android:layout_height="fill_parent"
	android:orientation="vertical"
	android:padding="10dip"
	android:id="@+id/linearLayoutAlertCautionRoot">
	<TextView android:text="@string/dialog_autodetect_caution_msg1"
		android:layout_width="fill_parent" android:layout_height="wrap_content"></TextView>
	<LinearLayout android:layout_height="wrap_content"
		android:layout_width="fill_parent" android:orientation="horizontal"
		android:layout_marginLeft="10dip" android:layout_marginRight="10dip"
		android:layout_marginTop="10dip">
		<TextView android:text="-" android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:layout_marginRight="6dip"></TextView>
		<TextView android:text="@string/dialog_autodetect_caution_msg2"
			android:layout_width="fill_parent" android:layout_height="wrap_content"></TextView>
	</LinearLayout>
	<LinearLayout android:layout_height="wrap_content"
		android:layout_width="fill_parent" android:orientation="horizontal"
		android:layout_marginLeft="10dip" android:layout_marginRight="10dip"
		android:layout_marginBottom="10dip">
		<TextView android:text="-" android:layout_width="wrap_content"
			android:layout_height="wrap_content" android:layout_marginRight="6dip"></TextView>
		<TextView android:text="@string/dialog_autodetect_caution_msg3"
			android:layout_width="fill_parent" android:layout_height="wrap_content"></TextView>
	</LinearLayout>
	<TextView android:text="@string/dialog_autodetect_caution_msg4"
		android:layout_width="fill_parent" android:layout_height="wrap_content"></TextView>
</LinearLayout>


text:
package com.myconnector.web.ajax;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.myconnector.domain.Bookmark;
import com.myconnector.service.BookmarkService;
import com.myconnector.util.HttpSessionThreadLocal;

public class BookmarkAJAXImpl implements BookmarkAJAX {

    private static Logger logger = Logger.getLogger(BookmarkAJAXImpl.class);

    private BookmarkService bookmarkService = null;

    public void setBookmarkService(BookmarkService bookmarkService) {
        // Check null in case someone tries to call using AJAX
        if (bookmarkService != null) {
            this.bookmarkService = bookmarkService;
        }
    }

    public boolean addBookmarkToCurrentUser(String bookmarkId, HttpSession httpSession) {
        HttpSessionThreadLocal.set(httpSession);
        if (logger.isDebugEnabled()) {
            logger.debug("userId = " + HttpSessionThreadLocal.getUserId());
            logger.debug("userName = " + HttpSessionThreadLocal.getUsername());
        }
        // TODO unit test
        logger.debug("Attempting to add bookmark id = " + bookmarkId);
        Bookmark bookmark = bookmarkService.loadBookmark(bookmarkId);
        bookmark.setId(null);
        bookmark.setAddDate(null);
        bookmark.setFolder(null);
        return bookmarkService.saveBookmark(bookmark);
    }

}


text:
from datetime import date

from kitsune.kpi.models import MetricKind, Metric
from kitsune.sumo.tests import with_save

@with_save
def metric_kind(**kwargs):
    return MetricKind(code=kwargs.get('code', 'something'))

@with_save
def metric(**kwargs):
    defaults = {'start': date(1980, 02, 16),
                'end': date(1980, 02, 23),
                'value': 33}
    if 'kind' not in kwargs:
        defaults['kind'] = metric_kind(save=True)
    defaults.update(kwargs)
    return Metric(**defaults)


text:
class PortfoliosController < ApplicationController
  before_filter :load_portfolio,  :only => [:edit, :update, :destroy, :show]
  before_filter :load_all_years,  :only => [:edit, :update, :show]
  before_filter :load_groups,     :only => [:index]
  before_filter :load_products,   :only => [:index, :edit, :update]
  before_filter :load_possible_groups, :only => [:edit, :update]

  # View for editing a portfolio.
  def edit
  end

  # View of all portfolios
  def index
    @new_portfolio = Portfolio.new
    @portfolios = filter_portfolios(params[:search])
    @portfolios = sort_results(params, @portfolios) unless params[:order].blank?
    @portfolios = @portfolios.includes(:products, :products => :groups).order("portfolios.name, products.name, groups.name").uniq
    @portfolios = @portfolios.paginate(:page => params[:page],
                                     :per_page => session[:results_per_page])
  end

  # View a portfolio in detail
  def show
    @products = @portfolio.products.includes(:groups).order("products.name", "groups.name").uniq.paginate(:page => params[:products_page],
                :per_page => session[:results_per_page])
    @total_allocation = @portfolio.get_total_allocation(@year, @allocation_precision)
    @groups = Group.includes(:product_group_portfolios => :product).where(:product_group_portfolios => {:portfolio_id => @portfolio.id}).order("groups.name", "products.name").uniq
  end

  # Creates new portfolio.
  def create
    @portfolio = Portfolio.new(params[:portfolio])
    if @portfolio.save
      flash[:notice] = "Portfolio created!"
      redirect_to edit_portfolio_path(@portfolio.id)
      return
    else
      flash[:error] = "Portfolio already exists"
      redirect_to portfolios_path
    end
  end

  # Destroys given portfolio and redirects to its parent group.
  def destroy
    @portfolio.destroy
    flash[:notice] = t(:portfolio) + t(:deleted)
    redirect_to portfolios_path
  end

  # Adds new product to the portfolio if one is supplied, removes any which were marked for removal.
  # If a new product is added, also adds it to the group's list of products if it is not already in
  # it.
  def update
    unless params[:new_product_group_portfolios].blank?
      params[:new_product_group_portfolios].to_a.each do |new_pg|
        new_pg = new_pg.last
        unless new_pg.blank? || new_pg["product_id"].blank?
          if @portfolio.product_group_portfolios.new(new_pg).save
            flash[:notice] = "Product added."
          end
        end
      end
    end
    @portfolio.update_attributes(params[:portfolio])
    flash[:notice] = "Portfolio updated"
    redirect_to edit_portfolio_path(@portfolio.id)
  end

  private
    # Filters the portfolios displayed on the index page based on paramaters provided
    def filter_portfolios(search)
      portfolios = Portfolio.where(true)
      return portfolios if search.blank?
      @group = search[:group]
      @product = search[:product]
      @name = search[:name]
      search_array = []
      search_array << "product_group_portfolios.group_id = #{@group}" unless @group.blank?
      search_array << "product_group_portfolios.product_id = #{@product}" unless @product.blank?
      search_string = search_array.join(" AND ")
      portfolios = portfolios.joins(:product_group_portfolios).uniq unless search_string.blank?
      portfolios = portfolios.where(search_string) unless search_string.blank?
      portfolios = portfolios.where("portfolios.name LIKE '%#{@name}%'") unless @name.blank?
      return portfolios
    end

    # Loads all years. Loads the last selected year
    def load_all_years
      @all_years = FiscalYear.order(:year)
      @year = FiscalYear.find_by_year(cookies[:year])
      @year = @current_fiscal_year if @year.blank?
    end

    # Loads all groups in alphabetical order
    def load_groups
      @groups = Group.order(:name)
    end

    # Loads the portfolio in question. Also loads its associated group
    def load_portfolio
      @portfolio = Portfolio.find(params[:id])
    end

    # Loads all groups that the current user can edit, along with any allocations that those
    # may have
    def load_possible_groups
      if can? :manage, :all
        @possible_groups = Group.order(:name)
      else
        @possible_groups = @current_user.admin_groups
      end
      @groups_with_product_group_portfolios = Group.where("groups.id IN (?)", @possible_groups.pluck(:id) ).includes(:product_group_portfolios => :product).where(:product_group_portfolios => {:portfolio_id => @portfolio.id}).order("groups.name", "products.name").uniq
    end

    # Loads all products
    def load_products
      @products = Product.order(:name)
    end
end


text:
<?php

namespace Toyota\Component\Ldap\Tests\Core\Manager;

use Toyota\Component\Ldap\Core\Manager;
use Toyota\Component\Ldap\Core\Node;
use Toyota\Component\Ldap\API\SearchInterface;
use Toyota\Component\Ldap\Platform\Test\Connection;
use Toyota\Component\Ldap\Platform\Test\Entry;
use Toyota\Component\Ldap\Platform\Test\Search;
use Toyota\Component\Ldap\Exception\NotBoundException;
use Toyota\Component\Ldap\Exception\SizeLimitException;
use Toyota\Component\Ldap\Exception\MalformedFilterException;
use Toyota\Component\Ldap\Exception\SearchException;
use Toyota\Component\Ldap\Exception\NodeNotFoundException;

class ManagerReadTest extends ManagerTest
{
    /**
     * Tests retrieving node with their Dn
     *
     * @return void
     */
    public function testGetNode()
    {
        $manager = new Manager($this->minimal, $this->driver);

        // Exception handling
        $this->assertBindingFirst($manager, 'getNode', array('test'));
        $manager->connect();
        $this->assertBindingFirst($manager, 'getNode', array('test'));
        $manager->bind();

        $this->driver->getConnection()->setFailure(Connection::ERR_SIZE_LIMIT);
        try {
            $manager->getNode('test');
            $this->fail('Size limit exception should be populated');
        } catch (SizeLimitException $e) {
            $this->assertRegExp('/Size limit reached/', $e->getMessage());
        }

        $this->driver->getConnection()->setFailure(Connection::ERR_MALFORMED_FILTER);
        try {
            $manager->getNode('test');
            $this->fail('Malformed filter exception should be populated');
        } catch (MalformedFilterException $e) {
            $this->assertRegExp('/Malformed filter/', $e->getMessage());
        }

        $this->driver->getConnection()->setFailure(Connection::ERR_DEFAULT);
        try {
            $manager->getNode('test');
            $this->fail('Any other search exception should be populated');
        } catch (SearchException $e) {
            $this->assertEquals('Toyota\Component\Ldap\Exception\SearchException', get_class($e));
            $this->assertRegExp('/Search failed/', $e->getMessage());
        }

        // Empty result set handling
        $this->driver->getConnection()->setFailure(Connection::ERR_NO_RESULT);
        try {
            $manager->getNode('test');
            $this->fail('Node cannot be retrieved as search result set is empty');
        } catch (NodeNotFoundException $e) {
            $this->assertRegExp('/test not found/', $e->getMessage());
        }

        try {
            $node = $manager->getNode('CN=TEST,DC=EXAMPLE,DC=COM');
            $this->fail('No exception get thrown by backend but no entry is retrieved either');
        } catch (NodeNotFoundException $e) {
            $this->assertSearchLog(
                $this->driver->getConnection()->shiftLog(),
                'CN=TEST,DC=EXAMPLE,DC=COM',
                '(objectclass=*)',
                Search::SCOPE_BASE
            );
            $this->assertRegExp('/CN=TEST,DC=EXAMPLE,DC=COM not found/', $e->getMessage());
        }

        $this->driver->getConnection()->stackResults(null);
        try {
            $node = $manager->getNode('CN=TEST,DC=EXAMPLE,DC=COM');
            $this->fail('A null entry is not a valid entry');
        } catch (NodeNotFoundException $e) {
            $this->assertSearchLog(
                $this->driver->getConnection()->shiftLog(),
                'CN=TEST,DC=EXAMPLE,DC=COM',
                '(objectclass=*)',
                Search::SCOPE_BASE
            );
            $this->assertRegExp('/CN=TEST,DC=EXAMPLE,DC=COM not found/', $e->getMessage());
        }

        // Basic search
        $entry = new Entry('cn=test,dc=example,dc=com', array('attr' => array('value')));
        $this->driver->getConnection()->stackResults(array($entry));

        $node = $manager->getNode('CN=TEST,DC=EXAMPLE,DC=COM');
        $this->assertSearchLog(
            $this->driver->getConnection()->shiftLog(),
            'CN=TEST,DC=EXAMPLE,DC=COM',
            '(objectclass=*)',
            Search::SCOPE_BASE,
            null,
            array($entry)
        );
        $this->assertInstanceOf('Toyota\Component\Ldap\Core\Node', $node);

        $this->assertEquals(
            'cn=test,dc=example,dc=com',
            $node->getDn(),
            'The right node got retrieved and hydrated'
        );
        $this->assertNull(
            $this->driver->getConnection()->shiftResults(),
            'Node got pulled from the stack'
        );

        // Alternative parameters search
        $entry = new Entry('cn=cyril,dc=example,dc=com', array('attr' => array('value2')));
        $this->driver->getConnection()->stackResults(array($entry));

        $node = $manager->getNode(
            'CN=OTHER,DC=EXAMPLE,DC=COM',
            array('*', '+'),
            '(objectclass=other)'
        );
        $this->assertSearchLog(
            $this->driver->getConnection()->shiftLog(),
            'CN=OTHER,DC=EXAMPLE,DC=COM',
            '(objectclass=other)',
            Search::SCOPE_BASE,
            array('*', '+'),
            array($entry)
        );
        $this->assertInstanceOf('Toyota\Component\Ldap\Core\Node', $node);

        $this->assertEquals(
            'cn=cyril,dc=example,dc=com',
            $node->getDn(),
            'The right node got retrieved and hydrated'
        );
        $this->assertNull(
            $this->driver->getConnection()->shiftResults(),
            'Node got pulled from the stack'
        );
    }

    /**
     * Tests querying a Ldap directory
     *
     * @return void
     */
    public function testSearch()
    {
        $manager = new Manager($this->minimal, $this->driver);

        // Exception handling
        $this->assertBindingFirst($manager, 'search');
        $manager->connect();
        $this->assertBindingFirst($manager, 'search');
        $manager->bind();

        $this->driver->getConnection()->setFailure(Connection::ERR_MALFORMED_FILTER);
        try {
            $res = $manager->search();
            $this->fail('Filter malformed, query shall fail');
        } catch (MalformedFilterException $e) {
            $this->assertRegExp('/Malformed filter/', $e->getMessage());
        }

        // Basic search
        $set = array(new Entry('a'), new Entry('b'), new Entry('c'));
        $this->driver->getConnection()->stackResults($set);
        $result = $manager->search();

        $this->assertSearchLog(
            $this->driver->getConnection()->shiftLog(),
            'dc=example,dc=com',
            '(objectclass=*)',
            SearchInterface::SCOPE_ALL,
            null,
            $set
        );

        $this->assertInstanceOf('Toyota\Component\Ldap\Core\SearchResult', $result);

        $data = array();
        foreach ($result as $key => $value) {
            $this->assertInstanceOf('Toyota\Component\Ldap\Core\Node', $value);
            $data[$key] = $value->getAttributes();
        }

        $this->assertArrayHasKey('a', $data);
        $this->assertArrayHasKey('b', $data);
        $this->assertArrayHasKey('c', $data);
        $this->assertEquals(
            3,
            count($data),
            'The right search result got retrieved'
        );

        // Empty result set search
        $this->driver->getConnection()->setFailure(Connection::ERR_NO_RESULT);
        $this->driver->getConnection()->stackResults($set);
        $result = $manager->search();
        $this->assertInstanceOf(
            'Toyota\Component\Ldap\Core\SearchResult',
            $result,
            'Query did not fail - Exception got handled'
        );

        $data = array();
        foreach ($result as $key => $value) {
            $data[$key] = $value->getAttributes();
        }
        $this->assertEquals(
            0,
            count($data),
            'The exception got handled and the search result set has not been set in the query'
        );

        // Alternative parameters search
        $result = $manager->search(
            'ou=other,dc=example,dc=com',
            '(objectclass=test)',
            false,
            array('attr1', 'attr2')
        );
        $this->assertSearchLog(
            $this->driver->getConnection()->shiftLog(),
            'ou=other,dc=example,dc=com',
            '(objectclass=test)',
            SearchInterface::SCOPE_ONE,
            array('attr1', 'attr2'),
            $set
        );
        $this->assertInstanceOf('Toyota\Component\Ldap\Core\SearchResult', $result);
    }

    /**
     * Retrieve children Ldap nodes
     *
     * @return void
     */
    public function testGetChildren()
    {
        $manager = new Manager($this->minimal, $this->driver);

        $node = new Node();
        $node->setDn('test_node');

        $set = array();
        $set[] = new Entry('ent1', array('val1'));
        $set[] = new Entry('ent2', array('val2'));
        $set[] = new Entry('ent3', array('val3'));

        // Binding exception handling
        $this->assertBindingFirst($manager, 'getChildrenNodes', array($node));
        $manager->connect();
        $this->assertBindingFirst($manager, 'getChildrenNodes', array($node));
        $manager->bind();

        // Basic behaviour
        $this->driver->getConnection()->stackResults($set);

        $nodes = $manager->getChildrenNodes($node);
        $this->assertSearchLog(
            $this->driver->getConnection()->shiftLog(),
            'test_node',
            '(objectclass=*)',
            SearchInterface::SCOPE_ONE,
            null,
            $set
        );
        $this->assertNull($this->driver->getConnection()->shiftLog(), 'No other log');

        $this->assertTrue(is_array($nodes), 'An array of nodes is retrieved');
        $this->assertCount(3, $nodes);
        $this->assertEquals('ent1', $nodes[0]->getDn());
        $this->assertEquals('ent2', $nodes[1]->getDn());
        $this->assertEquals('ent3', $nodes[2]->getDn());

        // Successful search with no entry in the result set
        $nodes = $manager->getChildrenNodes($node);

        $this->assertSearchLog(
            $this->driver->getConnection()->shiftLog(),
            'test_node',
            '(objectclass=*)',
            SearchInterface::SCOPE_ONE
        );
        $this->assertNull($this->driver->getConnection()->shiftLog(), 'No other log');

        $this->assertTrue(is_array($nodes), 'An array of nodes is retrieved');
        $this->assertCount(0, $nodes);

        // Handling of NoResultException
        $this->driver->getConnection()->setFailure(Connection::ERR_NO_RESULT);

        $nodes = $manager->getChildrenNodes($node);
        $this->assertTrue(is_array($nodes), 'An array of nodes is retrieved');
        $this->assertCount(0, $nodes);

        // Handling of other search exceptions
        $this->driver->getConnection()->setFailure();

        try {
            $nodes = $manager->getChildrenNodes($node);
            $this->fail('Other search exceptions do not get processed and are populated');
        } catch (SearchException $e) {
            $this->assertRegExp('/Search failed/', $e->getMessage());
        }
    }
}


text:
class AddUserCourseEnrollmentIndex < ActiveRecord::Migration
  def change
    add_index :plc_user_course_enrollments, [:user_id, :plc_course_id], unique: true
    remove_index :plc_user_course_enrollments, column: :user_id
  end
end


text:
using System;

namespace Azure.ResourceManager.KeyVault.Models
{
    /// <summary> Parameters for updating the access policy in a vault. </summary>
    public partial class VaultAccessPolicyParameters
    {
        /// <summary> Initializes a new instance of VaultAccessPolicyParameters. </summary>
        /// <param name="properties"> Properties of the access policy. </param>
        public VaultAccessPolicyParameters(VaultAccessPolicyProperties properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            Properties = properties;
        }

        /// <summary> Initializes a new instance of VaultAccessPolicyParameters. </summary>
        /// <param name="id"> The resource id of the access policy. </param>
        /// <param name="name"> The resource name of the access policy. </param>
        /// <param name="type"> The resource name of the access policy. </param>
        /// <param name="location"> The resource type of the access policy. </param>
        /// <param name="properties"> Properties of the access policy. </param>
        internal VaultAccessPolicyParameters(string id, string name, string type, string location, VaultAccessPolicyProperties properties)
        {
            Id = id;
            Name = name;
            Type = type;
            Location = location;
            Properties = properties;
        }

        /// <summary> The resource id of the access policy. </summary>
        public string Id { get; }
        /// <summary> The resource name of the access policy. </summary>
        public string Name { get; }
        /// <summary> The resource name of the access policy. </summary>
        public string Type { get; }
        /// <summary> The resource type of the access policy. </summary>
        public string Location { get; }
        /// <summary> Properties of the access policy. </summary>
        public VaultAccessPolicyProperties Properties { get; set; }
    }
}