text:
using namespace std;
using namespace fiber_bundle; // Workaround for MS C++ bug.

// ===========================================================
// STRUCTURED_BLOCK_3D_CRG_INTERVAL FACET
// ===========================================================

// PUBLIC DATA MEMBERS

fiber_bundle::structured_block_3d_crg_interval::
structured_block_3d_crg_interval()
{
  _i_size = 0;
  _j_size = 0;
  _k_size = 0;
  _jk_size = 0;

  _i_vertex_size = 0;
  _j_vertex_size = 0;
  _k_vertex_size = 0;
  _jk_vertex_size = 0;

  _zone_begin = 0;
  _zone_size = 0;

  _vertex_begin = 0;
  _vertex_size = 0;

  // Postconditions:

  ensure(invariant());
  ensure(!is_initialized());

  return;
}

fiber_bundle::structured_block_3d_crg_interval::
~structured_block_3d_crg_interval()
{
  // Preconditions:

  // Body:

  if(is_valid(_lower_covers_begin))
  {
    // Delete the block interval.

    _id_spaces->delete_space(_lower_covers_begin);

    // Delete the zones interval.

    _id_spaces->delete_space(_lower_covers_begin + 1);

    // Delete the vertices interval.

    _id_spaces->delete_space(_lower_covers_begin + 1 + _zone_size);
  }

  if(is_valid(_upper_covers_begin))
  {
    // Delete the block interval.

    _id_spaces->delete_space(_upper_covers_begin);

    // Delete the zones interval.

    _id_spaces->delete_space(_upper_covers_begin + 1);

    // Delete the vertices interval.

    _id_spaces->delete_space(_upper_covers_begin + 1 + _zone_size);
  }

  // Postconditions:

  // Exit:

  return;
}

sheaf::size_type
fiber_bundle::structured_block_3d_crg_interval::
i_size() const
{
  return _i_size;
}

sheaf::size_type
fiber_bundle::structured_block_3d_crg_interval::
j_size() const
{
  return _j_size;
}

sheaf::size_type
fiber_bundle::structured_block_3d_crg_interval::
k_size() const
{
  return _k_size;
}

// PROTECTED DATA MEMBERS

sheaf::pod_index_type
fiber_bundle::structured_block_3d_crg_interval::
vertex_id(pod_index_type xi, pod_index_type xj, pod_index_type xk) const
{
  // Preconditions:

  require((0 <= xi) && (xi <= i_size()));
  require((0 <= xj) && (xj <= j_size()));
  require((0 <= xk) && (xk <= k_size()));

  // Body:

  pod_index_type result =
    (xi*_j_vertex_size + xj)*_k_vertex_size + xk + _vertex_begin;

  // Postconditions:

  ensure(contains_member(result));

  // Exit:

  return result;
}

// PRIVATE DATA MEMBERS

// ===========================================================
// HOMOGENEOUS_BLOCK FACET
// ===========================================================

// PUBLIC DATA MEMBERS

// PROTECTED DATA MEMBERS

// PRIVATE DATA MEMBERS

// ===========================================================
// ZONES FACET
// ===========================================================

// PUBLIC DATA MEMBERS

// PROTECTED DATA MEMBERS

void
fiber_bundle::structured_block_3d_crg_interval::
initialize_zones(base_space_poset& xhost)
{
  // Preconditions:

  require(id_spaces_initialized());
  require(local_id_space_initialized());
  require(!zones_initialized());

  // Body:

  // Construct the zone id space.

  const string& lzone_id_space_name =
    section_space_schema_member::intersection_id_space_name(xhost.d_cells(3),
							    interval_member());

  _zones_space_id =
    offset_index_space_state::new_space(*_id_spaces,
					lzone_id_space_name,
					_zone_begin,
					_zone_size).index();

  _zones_initialized = true;

  // Construct the product structure for the zone id space.

  ijk_product_structure lzone_structure(_i_size, _j_size, _k_size);
  _id_spaces->new_product_structure(_zones_space_id, lzone_structure);

  // Postconditions:

  ensure(zones_initialized());
  ensure(id_spaces().has_product_structure(zones_space_id()));
  ensure(id_spaces().product_structure_conforms_to<ijk_product_structure>(_zones_space_id));

  // Exit:

  return;
}

// PRIVATE DATA MEMBERS

// ===========================================================
// VERTICES FACET
// ===========================================================

// PUBLIC DATA MEMBERS

// PROTECTED DATA MEMBERS

void
fiber_bundle::structured_block_3d_crg_interval::
initialize_vertices(base_space_poset& xhost)
{
  // Preconditions:

  require(id_spaces_initialized());
  require(local_id_space_initialized());
  require(!vertices_initialized());

  // Body:

  // Construct the vertex id space.

  const string& lvertex_id_space_name =
    section_space_schema_member::intersection_id_space_name(xhost.d_cells(0),
							    interval_member());

  _vertices_space_id =
    offset_index_space_state::new_space(*_id_spaces,
					lvertex_id_space_name,
					_vertex_begin,
					_vertex_size).index();

  _vertices_initialized = true;

  // Construct the product structure for the vertex id space.

  ijk_product_structure lvertex_structure(_i_vertex_size, _j_vertex_size, _k_vertex_size);
  _id_spaces->new_product_structure(_vertices_space_id, lvertex_structure);

  // Postconditions:

  ensure(vertices_initialized());
  ensure(id_spaces().has_product_structure(vertices_space_id()));
  ensure(id_spaces().product_structure_conforms_to<ijk_product_structure>(_vertices_space_id));

  // Exit:

  return;
}

// PRIVATE DATA MEMBERS

// ===========================================================
// BASE_SPACE_CRG_INTERVAL FACET
// ===========================================================

// PUBLIC DATA MEMBERS

int
fiber_bundle::structured_block_3d_crg_interval::
db(pod_index_type xmbr_id) const
{
  // Preconditions:

  require(contains_member(xmbr_id));

  // Body:

  static const int ldb[MEMBER_CLASS_END] =
    {
      3, 3, 0
    };

  int result = ldb[member_class(xmbr_id)];

  // Postconditions:

  // Exit:

  return result;
}

sheaf::pod_index_type
fiber_bundle::structured_block_3d_crg_interval::
d_cells_space_id(int xd) const
{
  // Preconditions:

  // Body:

  pod_index_type result;

  switch(xd)
  {
  case 0:
    result = _vertices_space_id;
    break;

  case 3:
    result = _zones_space_id;
    break;

  default:
    result = invalid_pod_index();
    break;
  }

  // Postconditions:

  // Exit:

  return result;
}

// PROTECTED DATA MEMBERS

// PRIVATE DATA MEMBERS

// ===========================================================
// BLOCK VERTICES FACET
// ===========================================================

// PUBLIC DATA MEMBERS

// PROTECTED DATA MEMBERS

void
fiber_bundle::structured_block_3d_crg_interval::
initialize_block_vertices()
{
  // Preconditions:

  require(!block_vertices_initialized());
  require(vertices_initialized());

  // Body:

 // Construct the block vertices id space.

  list_index_space_handle lblock_vertices_id_space =
     list_index_space_state::new_space(*_id_spaces,
				       block_vertices_name(),
				       false);

  _block_vertices_space_id = lblock_vertices_id_space.index();

  // Insert the private data into the id space.

  int I = i_size();
  int J = j_size();
  int K = k_size();

  // (0,0,0); client id 0

  lblock_vertices_id_space.push_back(_vertex_begin);

  // (I,0,0); client id 1.

  lblock_vertices_id_space.push_back(vertex_id(I, 0, 0));

  // (I,J,0); client id 2.

  lblock_vertices_id_space.push_back(vertex_id(I, J, 0));

  // (0,J,0); client id 3;

  lblock_vertices_id_space.push_back(vertex_id(0, J, 0));

  // (0,0,K); client id 4

  lblock_vertices_id_space.push_back(vertex_id(0, 0, K));

  // (I,0,K); client id 5.

  lblock_vertices_id_space.push_back(vertex_id(I, 0, K));

  // (I,J,K); client id 6.

  lblock_vertices_id_space.push_back(vertex_id(I, J, K));

  // (0,J,K); client id 7;

  lblock_vertices_id_space.push_back(vertex_id(0, J, K));

  // The block vertices is initialized.

  _block_vertices_initialized = true;

  // Postconditions:

  ensure(block_vertices_initialized());

  // Exit:

  return;
}

// PRIVATE DATA MEMBERS

// ===========================================================
// IMPLICIT_CRG_INTERVAL FACET
// ===========================================================

// PUBLIC DATA MEMBERS

// PROTECTED DATA MEMBERS

// PRIVATE DATA MEMBERS

// ===========================================================
// CRG_INTERVAL FACET
// ===========================================================

// PUBLIC DATA MEMBERS

// PROTECTED DATA MEMBERS

// PRIVATE DATA MEMBERS

// ===========================================================
// INTERVAL FACET
// ===========================================================

// PUBLIC DATA MEMBERS

void
fiber_bundle::structured_block_3d_crg_interval::
get_size(size_type xi_size, size_type xj_size, size_type xk_size, size_type& result)
{
  // Preconditions:

  // Body:

  size_type lzone_size   = xi_size*xj_size*xk_size;
  size_type lvertex_size = (xi_size + 1)*(xj_size + 1)*(xk_size + 1);

  result = 1 + lzone_size + lvertex_size;

  // Postconditions:

  // Exit:

  return;
}

// PROTECTED DATA MEMBERS

// PRIVATE DATA MEMBERS

// ===========================================================
// COVER SET FACET
// ===========================================================

// PUBLIC DATA MEMBERS

// PROTECTED DATA MEMBERS

void
fiber_bundle::structured_block_3d_crg_interval::
initialize_lower_covers()
{
  // Preconditions:

  require(id_spaces_initialized());
  require(local_id_space_initialized());
  require(!covers_initialized(LOWER));

  // Body:

  // Construct the lower cover of the block.
  //
  // The lower cover of the block is initialized to an id space that contains
  // all the zones.

  _lower_covers_begin =
    explicit_index_space_interval::new_space(*_id_spaces, 1).begin();

  offset_index_space_state::new_space(*_id_spaces,
				      _lower_covers_begin,
				      implicit_cover_name(LOWER, interval_member()),
				      _zone_begin,
				      _zone_size);

  // Construct the lower cover of the zones.
  //
  // The lower cover of the zones is initialized to the nodal connectivity.
  // The user may change the lower cover of the zones by using the explicit
  // overrides in crg_range.  However, the underlineing connectivity id space
  // interval will remain in the id space family.  For that reason, we can
  // set the connectivity begin to beginning of the connectivity id space
  // interval created below.

  _connectivity_begin =
    ijk_connectivity_index_space_interval::new_space(*_id_spaces,
						     _zone_size,
						     _vertex_begin,
						     _j_size,
						     _k_size).begin();

  // Construct the lower cover of the vertices.
  //
  // The lower cover of the vertices is initialized to bottom.

  constant_index_space_interval::new_space(*_id_spaces,
					   _vertex_size,
					   BOTTOM_INDEX);

  // The lower cover is initialized.

  _lower_covers_initialized = true;

  // Posconditions:

  ensure(covers_initialized(LOWER));

  // Exit:

  return;
}

void
fiber_bundle::structured_block_3d_crg_interval::
initialize_upper_covers()
{
  // Preconditions:

  require(id_spaces_initialized());
  require(local_id_space_initialized());
  require(!covers_initialized(UPPER));

  // Body:

  // Construct the upper cover of the block
  //
  // The upper cover of block is initialized to an empty explicit id space.

  _upper_covers_begin =
    explicit_index_space_interval::new_space(*_id_spaces, 1).begin();

  list_index_space_state::new_space(*_id_spaces,
				    _upper_covers_begin,
				    explicit_cover_name(UPPER, interval_member()),
				    false);

  // Construct the upper cover of the zones.
  //
  // The upper cover of the zones is initialized to the block.

  constant_index_space_interval::new_space(*_id_spaces,
					   _zone_size,
					   interval_member());

  // Construct the upper cover of the vertices.
  //
  // The upper cover of the vertices is initialized to the zonal adjacency.
  // The user may change the upper cover of the vertices by using the explicit
  // overrides in crg_range.  However, the underlineing adjacency id space
  // interval will remain in the id space family.  For that reason, we can
  // set the adjacency begin to the beginning of the adjacency id space
  // interval created below.

  _adjacency_begin =
    ijk_adjacency_index_space_interval::new_space(*_id_spaces,
						  _vertex_size,
						  _zone_begin,
						  _i_size,
						  _j_size,
						  _k_size).begin();

  // The upper cover is initialized.

  _upper_covers_initialized = true;

  // Posconditions:

  ensure(covers_initialized(UPPER));

  // Exit:

  return;
}

// PRIVATE DATA MEMBERS

// ===========================================================
// DOF_TUPLE_ID FACET
// ===========================================================

// PUBLIC DATA MEMBERS

void
fiber_bundle::structured_block_3d_crg_interval::
get_dof_tuple_ids(poset_state_handle& xhost,
                  size_type xi_size,
                  size_type xj_size,
                  size_type xk_size,
                  block<pod_index_type>& result)
{
  // Preconditions:

  // Body:

  result.reserve(MEMBER_CLASS_END);
  result.set_ct(MEMBER_CLASS_END);

  result[BLOCK]  = structured_block_3d::new_row_dof_map(xhost, xi_size, xj_size, xk_size, true).hub_pod();
  result[ZONE]   = base_space_member::new_row_dof_map(xhost, "hex_nodes", true).hub_pod();
  result[VERTEX] = base_space_member::new_row_dof_map(xhost, "point", true).hub_pod();

  // Postconditions:

  // Exit:

  return;
}

// PROTECTED DATA MEMBERS

// PRIVATE DATA MEMBERS

// ===========================================================
// PRIVATE_DATA FACET
// ===========================================================

// PUBLIC DATA MEMBERS

void
fiber_bundle::structured_block_3d_crg_interval::
get_private_data(size_type xi_size,
                 size_type xj_size,
                 size_type xk_size,
                 block<pod_index_type>& result)
{
  // Preconditions:

  // Body:

  result.reserve(5);
  result.set_ct(5);

  result[0] = xi_size;
  result[1] = xj_size;
  result[2] = xk_size;
  result[3] = 0;
  result[4] = 0;

  // Postconditions:

  // Exit:

  return;
}

// PROTECTED DATA MEMBERS

sheaf::size_type
fiber_bundle::structured_block_3d_crg_interval::
implicit_private_data_size() const
{
  return 3;
}

void
fiber_bundle::structured_block_3d_crg_interval::
get_implicit_private_data(block<pod_index_type>& xdata) const
{
  // Preconditions:

  // Body:

  xdata.push_back(_i_size);
  xdata.push_back(_j_size);
  xdata.push_back(_k_size);

  // Postconditions:

  ensure(xdata.ct() == implicit_private_data_size());

  // Exit:

  return;
}

void
fiber_bundle::structured_block_3d_crg_interval::
put_implicit_private_data(const block<pod_index_type>& xdata)
{
  // Preconditions:

  // Body:

  _i_size = xdata[0];
  _j_size = xdata[1];
  _k_size = xdata[2];

  _jk_size = _j_size*_k_size;

  _i_vertex_size = _i_size + 1;
  _j_vertex_size = _j_size + 1;
  _k_vertex_size = _k_size + 1;
  _jk_vertex_size = _j_vertex_size*_k_vertex_size;

  _zone_begin = implicit_begin();
  _zone_size = _i_size*_j_size*_k_size;

  _vertex_begin = _zone_begin + _zone_size;
  _vertex_size = _i_vertex_size*_jk_vertex_size;

  // Postconditions:

  ensure(invariant());

  // Exit:

  return;
}

// PRIVATE DATA MEMBERS

// ===========================================================
// FINIALIZE FACET
// ===========================================================

// PUBLIC DATA MEMBERS

void
fiber_bundle::structured_block_3d_crg_interval::
finalize(poset_state_handle& xhost)
{
  // Preconditions:

  require(dynamic_cast<base_space_poset*>(&xhost) != 0);
  require(xhost.state_is_read_accessible());

  // Body:

  base_space_poset& lhost = dynamic_cast<base_space_poset&>(xhost);

  // Initialize the zone id space.

  initialize_zones(lhost);

  // Initialize the vertex id space.

  initialize_vertices(lhost);

  // Initialize block vertices id space.

  initialize_block_vertices();

  // Initialize the cover id spaces.

  initialize_covers();

  // Now this can be inserted in the standard subposets (d-cells, etc).

  lhost.insert_interval_in_standard_subposets(*this);

  // Insert the vertices into the upper cover of bottom.

  xhost.append_upper_cover_of_bottom(_vertex_begin,
				     _vertex_begin + _vertex_size);

  homogeneous_block_crg_interval::finalize(xhost);

  // Postconditions:

  ensure(invariant());
  ensure(is_initialized());

  // Exit:

  return;
}

// PROTECTED DATA MEMBERS

// PRIVATE DATA MEMBERS

// ===========================================================
// FACTORY FACET
// ===========================================================

// PUBLIC DATA MEMBERS

const std::string&
fiber_bundle::structured_block_3d_crg_interval::
class_name() const
{
  static const string result("structured_block_3d_crg_interval");
  return result;
}

// PROTECTED DATA MEMBERS

// PRIVATE DATA MEMBERS

bool
fiber_bundle::structured_block_3d_crg_interval::
make_prototype()
{
  // Preconditions:

  // Body:

  structured_block_3d_crg_interval* lproto = new structured_block_3d_crg_interval();

  interval_factory().insert_prototype(lproto);

  // Postconditions:

  // Exit:

  return true;
}

// ===========================================================
// ANY FACET
// ===========================================================

// PUBLIC DATA MEMBERS

bool
fiber_bundle::structured_block_3d_crg_interval::
is_ancestor_of(const any* other) const
{

  // Preconditions:

  require(other != 0);

  // Body:

  // True if other conforms to this

  bool result = dynamic_cast<const structured_block_3d_crg_interval*>(other) != 0;

  // Postconditions:

  return result;
}

fiber_bundle::structured_block_3d_crg_interval*
fiber_bundle::structured_block_3d_crg_interval::
clone() const
{
  // Preconditions:

  // Body:

  structured_block_3d_crg_interval* result = new structured_block_3d_crg_interval();

  // Postconditions:

  ensure(result != 0);
  ensure(is_same_type(result));

  // Exit:

  return result;
}

bool
fiber_bundle::structured_block_3d_crg_interval::
invariant() const
{
  bool result = true;

  if(invariant_check())
  {
    // Prevent recursive calls to invariant

    disable_invariant_check();

    // Must satisfy base class invariant

    invariance(homogeneous_block_crg_interval::invariant());

    // Invariances for this class:

    invariance(dof_tuple_ids_initialized() ? is_valid(block_dof_tuple_id()) : true);
    invariance(dof_tuple_ids_initialized() ? is_valid(zone_dof_tuple_id()) : true);
    invariance(dof_tuple_ids_initialized() ? is_valid(vertex_dof_tuple_id()) : true);

    // Finished, turn invariant checking back on.

    enable_invariant_check();
  }

  // Exit

  return result;
}

// PROTECTED DATA MEMBERS

// PRIVATE DATA MEMBERS

// ===========================================================
// NON-MEMBER FUNCTIONS
// ===========================================================


text:
name              'rackspace_sudo'
maintainer        'Rackspace, US Inc.'
maintainer_email  'rackspace-cookbooks@rackspace.com'
license           'Apache 2.0'
description       'Installs sudo and configures /etc/sudoers'
version           '3.1.1'

recipe 'rackspace_sudo', 'Installs sudo and configures /etc/sudoers'

%w{redhat centos ubuntu debian}.each do |os|
  supports os
end

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.skyframe;

import static com.google.common.collect.ImmutableList.toImmutableList;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.ConfiguredTargetValue;
import com.google.devtools.build.lib.analysis.PlatformConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
import com.google.devtools.build.lib.analysis.platform.DeclaredToolchainInfo;
import com.google.devtools.build.lib.analysis.platform.PlatformProviderUtils;
import com.google.devtools.build.lib.bazel.bzlmod.BazelModuleResolutionValue;
import com.google.devtools.build.lib.bazel.bzlmod.ExternalDepsException;
import com.google.devtools.build.lib.bazel.bzlmod.Module;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelConstants;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.cmdline.SignedTargetPattern;
import com.google.devtools.build.lib.cmdline.TargetParsingException;
import com.google.devtools.build.lib.cmdline.TargetPattern;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.pkgcache.FilteringPolicies;
import com.google.devtools.build.lib.rules.repository.RepositoryDelegatorFunction;
import com.google.devtools.build.lib.server.FailureDetails.Toolchain.Code;
import com.google.devtools.build.lib.skyframe.TargetPatternUtil.InvalidTargetPatternException;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionException;
import com.google.devtools.build.skyframe.SkyFunctionException.Transience;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import com.google.devtools.build.skyframe.ValueOrException;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;

/**
 * {@link SkyFunction} that returns all registered toolchains available for toolchain resolution.
 */
public class RegisteredToolchainsFunction implements SkyFunction {

  @Nullable
  @Override
  public SkyValue compute(SkyKey skyKey, Environment env)
      throws SkyFunctionException, InterruptedException {

    BuildConfigurationValue configuration =
        (BuildConfigurationValue)
            env.getValue(((RegisteredToolchainsValue.Key) skyKey).getConfigurationKey());
    RepositoryMappingValue mainRepoMapping =
        (RepositoryMappingValue) env.getValue(RepositoryMappingValue.key(RepositoryName.MAIN));
    if (env.valuesMissing()) {
      return null;
    }

    TargetPattern.Parser mainRepoParser =
        new TargetPattern.Parser(
            PathFragment.EMPTY_FRAGMENT,
            RepositoryName.MAIN,
            mainRepoMapping.getRepositoryMapping());
    ImmutableList.Builder<SignedTargetPattern> targetPatternBuilder = new ImmutableList.Builder<>();

    // Get the toolchains from the configuration.
    PlatformConfiguration platformConfiguration =
        configuration.getFragment(PlatformConfiguration.class);
    try {
      targetPatternBuilder.addAll(
          TargetPatternUtil.parseAllSigned(
              platformConfiguration.getExtraToolchains(), mainRepoParser));
    } catch (InvalidTargetPatternException e) {
      throw new RegisteredToolchainsFunctionException(
          new InvalidToolchainLabelException(e), Transience.PERSISTENT);
    }

    // Get registered toolchains from bzlmod.
    ImmutableList<TargetPattern> bzlmodToolchains = getBzlmodToolchains(env);
    if (bzlmodToolchains == null) {
      return null;
    }
    targetPatternBuilder.addAll(TargetPatternUtil.toSigned(bzlmodToolchains));

    // Get the registered toolchains from the WORKSPACE.
    ImmutableList<TargetPattern> workspaceToolchains = getWorkspaceToolchains(env);
    if (workspaceToolchains == null) {
      return null;
    }
    targetPatternBuilder.addAll(TargetPatternUtil.toSigned(workspaceToolchains));

    // Expand target patterns.
    ImmutableList<Label> toolchainLabels;
    try {
      toolchainLabels =
          TargetPatternUtil.expandTargetPatterns(
              env, targetPatternBuilder.build(), FilteringPolicies.ruleTypeExplicit("toolchain"));
      if (env.valuesMissing()) {
        return null;
      }
    } catch (TargetPatternUtil.InvalidTargetPatternException e) {
      throw new RegisteredToolchainsFunctionException(
          new InvalidToolchainLabelException(e), Transience.PERSISTENT);
    }

    // Load the configured target for each, and get the declared toolchain providers.
    ImmutableList<DeclaredToolchainInfo> registeredToolchains =
        configureRegisteredToolchains(env, configuration, toolchainLabels);
    if (env.valuesMissing()) {
      return null;
    }

    return RegisteredToolchainsValue.create(registeredToolchains);
  }

  /**
   * Loads the external package and then returns the registered toolchains.
   *
   * @param env the environment to use for lookups
   */
  @Nullable
  @VisibleForTesting
  public static ImmutableList<TargetPattern> getWorkspaceToolchains(Environment env)
      throws InterruptedException {
    PackageValue externalPackageValue =
        (PackageValue) env.getValue(PackageValue.key(LabelConstants.EXTERNAL_PACKAGE_IDENTIFIER));
    if (externalPackageValue == null) {
      return null;
    }

    Package externalPackage = externalPackageValue.getPackage();
    return externalPackage.getRegisteredToolchains();
  }

  @Nullable
  private static ImmutableList<TargetPattern> getBzlmodToolchains(Environment env)
      throws InterruptedException, RegisteredToolchainsFunctionException {
    if (!RepositoryDelegatorFunction.ENABLE_BZLMOD.get(env)) {
      return ImmutableList.of();
    }
    BazelModuleResolutionValue bazelModuleResolutionValue =
        (BazelModuleResolutionValue) env.getValue(BazelModuleResolutionValue.KEY);
    if (bazelModuleResolutionValue == null) {
      return null;
    }
    ImmutableList.Builder<TargetPattern> toolchains = ImmutableList.builder();
    for (Module module : bazelModuleResolutionValue.getDepGraph().values()) {
      TargetPattern.Parser parser =
          new TargetPattern.Parser(
              PathFragment.EMPTY_FRAGMENT,
              RepositoryName.createFromValidStrippedName(module.getCanonicalRepoName()),
              bazelModuleResolutionValue.getFullRepoMapping(module.getKey()));
      for (String pattern : module.getToolchainsToRegister()) {
        try {
          toolchains.add(parser.parse(pattern));
        } catch (TargetParsingException e) {
          throw new RegisteredToolchainsFunctionException(
              new InvalidToolchainLabelException(pattern, e), Transience.PERSISTENT);
        }
      }
    }
    return toolchains.build();
  }

  private static ImmutableList<DeclaredToolchainInfo> configureRegisteredToolchains(
      Environment env, BuildConfigurationValue configuration, List<Label> labels)
      throws InterruptedException, RegisteredToolchainsFunctionException {
    ImmutableList<SkyKey> keys =
        labels.stream()
            .map(
                label ->
                    ConfiguredTargetKey.builder()
                        .setLabel(label)
                        .setConfiguration(configuration)
                        .build())
            .collect(toImmutableList());

    Map<SkyKey, ValueOrException<ConfiguredValueCreationException>> values =
        env.getValuesOrThrow(keys, ConfiguredValueCreationException.class);
    ImmutableList.Builder<DeclaredToolchainInfo> toolchains = new ImmutableList.Builder<>();
    boolean valuesMissing = false;
    for (SkyKey key : keys) {
      ConfiguredTargetKey configuredTargetKey = (ConfiguredTargetKey) key.argument();
      Label toolchainLabel = configuredTargetKey.getLabel();
      try {
        ValueOrException<ConfiguredValueCreationException> valueOrException = values.get(key);
        if (valueOrException.get() == null) {
          valuesMissing = true;
          continue;
        }

        ConfiguredTarget target =
            ((ConfiguredTargetValue) valueOrException.get()).getConfiguredTarget();
        DeclaredToolchainInfo toolchainInfo = PlatformProviderUtils.declaredToolchainInfo(target);
        if (toolchainInfo == null) {
          throw new RegisteredToolchainsFunctionException(
              new InvalidToolchainLabelException(toolchainLabel), Transience.PERSISTENT);
        }
        toolchains.add(toolchainInfo);
      } catch (ConfiguredValueCreationException e) {
        throw new RegisteredToolchainsFunctionException(
            new InvalidToolchainLabelException(toolchainLabel, e), Transience.PERSISTENT);
      }
    }

    if (valuesMissing) {
      return null;
    }
    return toolchains.build();
  }

  @Nullable
  @Override
  public String extractTag(SkyKey skyKey) {
    return null;
  }

  /**
   * Used to indicate that the given {@link Label} represents a {@link ConfiguredTarget} which is
   * not a valid {@link DeclaredToolchainInfo} provider.
   */
  public static final class InvalidToolchainLabelException extends ToolchainException {

    public InvalidToolchainLabelException(Label invalidLabel) {
      super(
          formatMessage(
              invalidLabel.getCanonicalForm(),
              "target does not provide the DeclaredToolchainInfo provider"));
    }

    public InvalidToolchainLabelException(Label invalidLabel, String reason) {
      super(formatMessage(invalidLabel.getCanonicalForm(), reason));
    }

    public InvalidToolchainLabelException(TargetPatternUtil.InvalidTargetPatternException e) {
      this(e.getInvalidPattern(), e.getTpe());
    }

    public InvalidToolchainLabelException(String invalidPattern, TargetParsingException e) {
      super(formatMessage(invalidPattern, e.getMessage()), e);
    }

    public InvalidToolchainLabelException(Label invalidLabel, ConfiguredValueCreationException e) {
      super(formatMessage(invalidLabel.getCanonicalForm(), e.getMessage()), e);
    }

    @Override
    protected Code getDetailedCode() {
      return Code.INVALID_TOOLCHAIN;
    }

    private static String formatMessage(String invalidPattern, String reason) {
      return String.format("invalid registered toolchain '%s': %s", invalidPattern, reason);
    }
  }

  /**
   * Used to declare all the exception types that can be wrapped in the exception thrown by {@link
   * #compute}.
   */
  public static class RegisteredToolchainsFunctionException extends SkyFunctionException {

    public RegisteredToolchainsFunctionException(
        InvalidToolchainLabelException cause, Transience transience) {
      super(cause, transience);
    }

    public RegisteredToolchainsFunctionException(
        ExternalDepsException cause, Transience transience) {
      super(cause, transience);
    }
  }
}


text:
package com.hewking.custom;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by hewking on 2016/10/21.
 */
public class DrawPath extends View {

    private int width;
    private int height;

    private Paint mPaint;

    public DrawPath(Context context) {
        this(context,null);
    }

    public DrawPath(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public DrawPath(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(Color.BLUE);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.translate(width / 2 , height / 2);
        Path path = new Path();
        //连接到 某个点
        path.lineTo(200,200);
        path.lineTo(200,0);

        //改变上一次操作最后一个点位置
        path.setLastPoint(300,0);

        //移动到某个位置
        path.moveTo(150,150);

        path.addRect(new RectF(-200,200,200,200),Path.Direction.CW);

        canvas.scale(1,-1);//反转y轴坐标 跟正常正交坐标系一样了 哈哈

        Path circle = new Path();
        circle.addCircle(0,200,100, Path.Direction.CW);
        path.addPath(circle);

        //连接成闭合曲线
        path.close();
        canvas.drawPath(path,mPaint);
    }
}


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

namespace ExchangeVariableValues
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = int.Parse(Console.ReadLine());
            int b = int.Parse(Console.ReadLine());

            Console.WriteLine("Before:");

            Console.WriteLine($"a = {a}");
            Console.WriteLine($"b = {b}");

            int tempNum = a;
            a = b;

            Console.WriteLine("After:");
            Console.WriteLine($"a = {a}");
            Console.WriteLine($"b = {tempNum}");
        }
    }
}


text:
title: Core
template: core.hbs
collection: pages
menu: 1
---


text:
Wordpress themes telah banyak membantu pengguna wordpress dan juga ramai peniaga yang memerlukan cara mudah, pantas dan murah untuk memiliki alamn web sendiri. Samada melalui freelancer ataupun marketplace yang banyak ada di pasaran, tidak dapat disangkal bahawa jasa Wordpress Themes sangat besar kepada pengguna internet.

Namun dengan lambakan themes wordpress di pasaran, terdapat lebih banyak themes yang tidak bagus berbanding yang bagus.

Prestasi themes wordpress perlu dilihat dari dua sudutu iaitu:

1. Sudut pengguna themes yang mahukan themes tersebut mempunyai banyak fungsi dan mudah digunakan
2. Sudut web developer yang mahukan themes tersebut mudah diubahsuai kodnya dan tidak menjadi punca sakit kepala.

Benarkah sakit kepala? Ya, boleh google dan baca banyak perkara tentang "Bad Wordpress Themes".

Jadi, sebagai peringatan kepada diri saya pada masa hadapan, berikut adalah perkara-perkara yang perlu diambil kira jika kau perlu membina themes wordpress:

## 1) Gunakan Themes Framework

Themes framework adalah kumpulan kod yang menyediakan banyak fungsi yang diperlukan oleh themes seperti shortcodes dan juga themes options.

[Gunakan Hybrid Core](http://themehybrid.com/hybrid-core) atau [Redux](http://notes.envato.com/industry-news/introducing-the-redux-framework/) buat masa sekarang sehinggalah Themeforest mengeluar Theme Framework mereka kelak.

## 2) Kod untuk Desain pada Themes, kod untuk Fungsi pada Plugin

Ya, gunakan konsep MVC sebaik mungkin walaupun ia mungkin tidak disokong secara native oleh Wordpress. Ini penting untuk memudahkan kita ubahsuai kod pada masa hadapan

## 3) Gunakan Plugin khas untuk Dependencies

Gunakan plugin [TGM Plugin Activation](https://github.com/thomasgriffin/TGM-Plugin-Activation) untuk menguruskan plugin-plugin yang diperlukan oleh themes supaya turut sama diiinstall semasa themes activation. Dengan ini pembangunan Themes tidak perlu lagi pening kepala memikirkan untuk ditambah kod plugin yang diperlukan.

## 4) Design Yang tercantik dan paling Fleksibel

Pengguna wordpress rata-rata mahukan ciri-ciri berikut untuk desain wordpress mereka tidak kira harga mahupun siapa penulis themes tersebut:

1. Desain yang cantik, kemas dan unik
2. Desain yang fleksibel (themes options)
3. Themes yang bersih daripada bug
4. Themes yang tidak mengganggu plugin sedia ada
5. Setting yang boleh digunakan pada themes lain
6. Support yang mantap!

Itulah 4 perkara penting yang harus diambil kira jika mahu menghasilkan wordpress themes yang digunakan oleh ramai orang dan dikagumi oleh ramai web developer!


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
/**
 * The "function" token can not be used as identifier
 *
 * @path ch07/7.6/7.6.1/7.6.1.1/S7.6.1.1_A1.11.js
 * @description Checking if execution of "function=1" fails
 * @negative
 */

function = 1;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>sympy.physics.quantum.piab — SymPy 1.0.1.dev documentation</title>

    <link rel="stylesheet" href="../../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="http://96.sympy-live-tests.appspot.com/static/live-core.css" type="text/css" />
    <link rel="stylesheet" href="http://96.sympy-live-tests.appspot.com/static/live-autocomplete.css" type="text/css" />
    <link rel="stylesheet" href="http://96.sympy-live-tests.appspot.com/static/live-sphinx.css" type="text/css" />

    <link rel="shortcut icon" href="../../../../_static/sympy-notailtext-favicon.ico"/>
    <link rel="top" title="SymPy 1.0.1.dev documentation" href="../../../../index.html" />
    <link rel="up" title="Module code" href="../../../index.html" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

Source code for sympy.physics.quantum.piab

"""1D quantum particle in a box."""

from __future__ import print_function, division

from sympy import Symbol, pi, sqrt, sin, Interval, S

from sympy.physics.quantum.operator import HermitianOperator
from sympy.physics.quantum.state import Ket, Bra
from sympy.physics.quantum.constants import hbar
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.physics.quantum.hilbert import L2

m = Symbol('m')
L = Symbol('L')

__all__ = [
    'PIABHamiltonian',
    'PIABKet',
    'PIABBra'
]

[docs]class PIABHamiltonian(HermitianOperator):
    """Particle in a box Hamiltonian operator."""

    @classmethod
    def _eval_hilbert_space(cls, label):
        return L2(Interval(S.NegativeInfinity, S.Infinity))

    def _apply_operator_PIABKet(self, ket, **options):
        n = ket.label[0]
        return (n**2*pi**2*hbar**2)/(2*m*L**2)*ket

[docs]class PIABKet(Ket):
    """Particle in a box eigenket."""

    @classmethod
    def _eval_hilbert_space(cls, args):
        return L2(Interval(S.NegativeInfinity, S.Infinity))

    @classmethod
    def dual_class(self):
        return PIABBra

    def _represent_default_basis(self, **options):
        return self._represent_XOp(None, **options)

    def _represent_XOp(self, basis, **options):
        x = Symbol('x')
        n = Symbol('n')
        subs_info = options.get('subs', {})
        return sqrt(2/L)*sin(n*pi*x/L).subs(subs_info)

    def _eval_innerproduct_PIABBra(self, bra):
        return KroneckerDelta(bra.label[0], self.label[0])

[docs]class PIABBra(Bra):
    """Particle in a box eigenbra."""

    @classmethod
    def _eval_hilbert_space(cls, label):
        return L2(Interval(S.NegativeInfinity, S.Infinity))

    @classmethod
    def dual_class(self):
        return PIABKet

Related Topics

Documentation overview

Module code

Quick search

    <form class="search" action="../../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2015 SymPy Development Team.

      |
      Powered by Sphinx 1.4.1
      & Alabaster 0.7.7


text:
'use strict';

// require('./_signup.scss');

module.exports = {
  template: require('./signup.html'),
  controllerAs: 'signupCtrl',
  controller: [
    '$log',
    '$location',
    '$window',
    'authService',
    SignupController,
  ],
};

function SignupController($log, $location, $window, authService) {
  this.$onInit = () => {
    $log.debug('SignupController');
    this.title = 'Signup';

    if (!$window.localStorage.token) {
      authService.getToken()
      .then(
        () => $location.url('/home'),
        () => $location.url('/signup')
      );
    }

    this.signup = function(user) {
      $log.debug('signupCtrl.signup()');

      return authService.signup(user)
      .then(() => $location.url('/home'));
    };
  };
}


text:
package org.apache.stratos.autoscaler.monitor.component;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.autoscaler.algorithms.PartitionAlgorithm;
import org.apache.stratos.autoscaler.algorithms.partition.OneAfterAnother;
import org.apache.stratos.autoscaler.algorithms.partition.RoundRobin;
import org.apache.stratos.autoscaler.applications.ApplicationHolder;
import org.apache.stratos.autoscaler.applications.dependency.DependencyBuilder;
import org.apache.stratos.autoscaler.applications.dependency.DependencyTree;
import org.apache.stratos.autoscaler.applications.dependency.context.ApplicationChildContext;
import org.apache.stratos.autoscaler.applications.topic.ApplicationBuilder;
import org.apache.stratos.autoscaler.context.InstanceContext;
import org.apache.stratos.autoscaler.context.application.ParentInstanceContext;
import org.apache.stratos.autoscaler.context.partition.network.NetworkPartitionContext;
import org.apache.stratos.autoscaler.event.publisher.ClusterStatusEventPublisher;
import org.apache.stratos.autoscaler.exception.application.DependencyBuilderException;
import org.apache.stratos.autoscaler.exception.application.TopologyInConsistentException;
import org.apache.stratos.autoscaler.exception.partition.PartitionValidationException;
import org.apache.stratos.autoscaler.exception.policy.PolicyValidationException;
import org.apache.stratos.autoscaler.monitor.Monitor;
import org.apache.stratos.autoscaler.monitor.MonitorFactory;
import org.apache.stratos.autoscaler.monitor.cluster.ClusterMonitor;
import org.apache.stratos.autoscaler.monitor.events.ScalingDownBeyondMinEvent;
import org.apache.stratos.autoscaler.monitor.events.ScalingEvent;
import org.apache.stratos.autoscaler.monitor.events.ScalingUpBeyondMaxEvent;
import org.apache.stratos.autoscaler.util.AutoscalerConstants;
import org.apache.stratos.autoscaler.util.AutoscalerUtil;
import org.apache.stratos.autoscaler.util.ServiceReferenceHolder;
import org.apache.stratos.common.constants.StratosConstants;
import org.apache.stratos.common.threading.StratosThreadPool;
import org.apache.stratos.messaging.domain.application.GroupStatus;
import org.apache.stratos.messaging.domain.application.ParentComponent;
import org.apache.stratos.messaging.domain.application.ScalingDependentList;
import org.apache.stratos.messaging.domain.instance.ClusterInstance;
import org.apache.stratos.messaging.domain.instance.GroupInstance;
import org.apache.stratos.messaging.domain.instance.Instance;
import org.apache.stratos.messaging.domain.topology.ClusterStatus;
import org.apache.stratos.messaging.message.receiver.topology.TopologyManager;

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

/**
 * Monitor is to monitor it's child monitors and
 * control them according to the dependencies respectively.
 */
public abstract class ParentComponentMonitor extends Monitor {

    private static final Log log = LogFactory.getLog(ParentComponentMonitor.class);

    //Scheduler executor service to execute this monitor in a thread
    private final ScheduledExecutorService scheduler = StratosThreadPool.getScheduledExecutorService(
            "autoscaler.monitor.scheduler.thread.pool", 100);
    //The monitors dependency tree with all the start-able/kill-able dependencies
    protected DependencyTree startupDependencyTree;
    //The monitors dependency tree with all the scaling dependencies
    protected Set<ScalingDependentList> scalingDependencies;
    //monitors map, key=GroupAlias/clusterId and value=GroupMonitor/AbstractClusterMonitor
    protected Map<String, Monitor> aliasToActiveChildMonitorsMap;
    //Pending monitors list
    protected List<String> pendingChildMonitorsList;
    //instanceIds map, key=alias, value instanceIds stopped monitors
    protected Map<String, List<String>> inactiveInstancesMap;
    //terminating map, key=alias, value instanceIds
    protected Map<String, List<String>> terminatingInstancesMap;
    //network partition contexts
    protected Map<String, NetworkPartitionContext> networkPartitionContextsMap;
    // future to cancel it when destroying monitors
    private ScheduledFuture<?> schedulerFuture;
    //Executor service to maintain the thread pool
    private ExecutorService executorService;

    public ParentComponentMonitor(ParentComponent component) throws DependencyBuilderException {
        aliasToActiveChildMonitorsMap = new ConcurrentHashMap<String, Monitor>();
        inactiveInstancesMap = new ConcurrentHashMap<String, List<String>>();
        terminatingInstancesMap = new ConcurrentHashMap<String, List<String>>();
        pendingChildMonitorsList = new ArrayList<String>();
        id = component.getUniqueIdentifier();

        // Building the startup dependencies for this monitor within the immediate children
        startupDependencyTree = DependencyBuilder.getInstance().buildDependency(component);

        // Building the scaling dependencies for this monitor within the immediate children
        if ((component.getDependencyOrder() != null) &&
                (component.getDependencyOrder().getScalingDependents() != null)) {
            scalingDependencies = DependencyBuilder.getInstance().buildScalingDependencies(component);
        } else {
            // No scaling dependencies found, initialize to an empty set
            scalingDependencies = new HashSet<ScalingDependentList>();
        }

        // Create the executor service with identifier and thread pool size
        executorService = StratosThreadPool.getExecutorService(AutoscalerConstants.AUTOSCALER_THREAD_POOL_ID,
                AutoscalerConstants.AUTOSCALER_THREAD_POOL_SIZE);
        networkPartitionContextsMap = new ConcurrentHashMap<String, NetworkPartitionContext>();
    }

    /**
     * This will create Instance on demand as requested by monitors
     *
     * @param instanceId instance Id of the instance to be created
     * @return whether it is created or not
     */
    public abstract boolean createInstanceOnTermination(String instanceId);

    /**
     * Starting the scheduler for the monitor
     */
    public void startScheduler() {
        int monitoringIntervalMilliseconds = 60000;
        schedulerFuture = scheduler.scheduleAtFixedRate(this, 0,
                monitoringIntervalMilliseconds, TimeUnit.MILLISECONDS);
    }

    /**
     * This will stop the scheduler which is running for the monitor
     */
    protected void stopScheduler() {
        schedulerFuture.cancel(true);
    }

    /**
     * This will start the parallel dependencies at once from the top level.
     * it will get invoked when the monitor starts up only.
     */
    public void startDependency(ParentComponent component, List<String> parentInstanceIds) {
        //start the first dependency
        List<ApplicationChildContext> applicationContexts = this.startupDependencyTree.
                getStartAbleDependencies();
        startDependency(applicationContexts, parentInstanceIds);
    }

    /**
     * This will start the parallel dependencies at once from the top level.
     * it will get invoked when the monitor starts up only.
     *
     * @param component        The component which needs to be used to create the monitor
     * @param parentInstanceId parent-instance-id of the instance which added to the monitor
     */
    public void startDependency(ParentComponent component, String parentInstanceId) {
        //start the first dependency
        List<ApplicationChildContext> applicationContexts = this.startupDependencyTree.
                getStartAbleDependencies();
        List<String> parentInstanceIds = new ArrayList<String>();
        parentInstanceIds.add(parentInstanceId);
        startDependency(applicationContexts, parentInstanceIds);
    }

    /**
     * This will get invoked based on the activation event of its one of the child
     *
     * @param componentId alias/clusterId of which receive the activated event
     * @param instanceId  instance id of the instance
     * @return whether the instance has created or not
     */
    public boolean startDependency(String componentId, String instanceId) {
        List<ApplicationChildContext> applicationContexts = this.startupDependencyTree.
                getStarAbleDependencies(componentId);
        List<String> instanceIds = new ArrayList<String>();
        instanceIds.add(instanceId);
        return startDependency(applicationContexts, instanceIds);
    }

    /**
     * This will start the parallel dependencies at once from the top level
     * by traversing to find the terminated dependencies.
     * it will get invoked when starting a child instance on termination of a sub tree
     *
     * @param instanceId instance id of the instance
     */
    public void startDependencyOnTermination(String instanceId) {

        //start the first dependency which went to terminated
        List<ApplicationChildContext> applicationContexts = this.startupDependencyTree.
                getStarAbleDependenciesByTermination(this, instanceId);
        for (ApplicationChildContext context : applicationContexts) {
            if (log.isDebugEnabled()) {
                log.debug("Dependency check for the Group " + context.getId() + " started");
            }
            if (!this.aliasToActiveChildMonitorsMap.containsKey(context.getId())) {
                log.info(String.format("Starting dependent monitor on termination: [application] %s " +
                        "[component] %s", getAppId(), context.getId()));
                List<String> parentInstanceIds = new ArrayList<String>();
                parentInstanceIds.add(instanceId);
                startMonitor(this, context, parentInstanceIds);
            } else {
                //starting a new instance of the child
                Monitor monitor = aliasToActiveChildMonitorsMap.get(context.getId());
                //Creating the new instance
                if (monitor instanceof ParentComponentMonitor) {
                    ((ParentComponentMonitor) monitor).createInstanceOnTermination(instanceId);
                } else {
                    monitor.createInstanceOnDemand(instanceId);
                }
            }
        }
    }

    /**
     * To start the dependency of the given application contexts
     *
     * @param applicationContexts the found applicationContexts to be started
     * @param parentInstanceIds   the instance-ids of the parent instance
     */
    private boolean startDependency(List<ApplicationChildContext> applicationContexts,
                                    List<String> parentInstanceIds) {
        if (applicationContexts == null || applicationContexts.isEmpty()) {
            //all the groups/clusters have been started and waiting for activation
            log.info("No more dependent monitors to be started for component: [type] " +
                    getMonitorType().toString().toLowerCase()
                    + "[component] " + this.id);
            return false;

        } else {
            for (ApplicationChildContext context : applicationContexts) {
                if (!this.aliasToActiveChildMonitorsMap.containsKey(context.getId())) {
                    log.info(String.format("Starting dependent monitor: [application] %s [component] %s",
                            getAppId(), context.getId()));
                    startMonitor(this, context, parentInstanceIds);
                } else {
                    log.info(String.format("Dependent monitor already created, creating instance: " +
                            "[application] %s [component] %s", getAppId(), context.getId()));

                    Monitor monitor = aliasToActiveChildMonitorsMap.get(context.getId());
                    // Creating new instance
                    for (String instanceId : parentInstanceIds) {
                        if (monitor.getInstancesByParentInstanceId(instanceId) == null ||
                                monitor.getInstancesByParentInstanceId(instanceId).isEmpty()) {
                            monitor.createInstanceOnDemand(instanceId);
                        } else {
                            log.info(String.format("Instance has already exists for [application] " +
                                            "%s [component] %s [instance-id] %s", getAppId(),
                                    context.getId(), instanceId));
                        }
                    }
                }
            }
            return true;
        }

    }

    @Override
    public void onChildScalingEvent(ScalingEvent scalingEvent) {
        if (log.isInfoEnabled()) {
            log.info(String.format("Child scaling event received to [parent] %s [network-partition] %s [event-id] %s " +
                            "[group-instance] %s [factor] %s", this.getId(), scalingEvent.getNetworkPartitionId(),
                    scalingEvent.getId(), scalingEvent.getInstanceId(), scalingEvent.getFactor()));
        }
        String networkPartitionId = scalingEvent.getNetworkPartitionId();
        String instanceId = scalingEvent.getInstanceId();
        String id = scalingEvent.getId();
        NetworkPartitionContext networkPartitionContext =
                this.getNetworkPartitionContextsMap().get(networkPartitionId);
        if (networkPartitionContext != null) {
            InstanceContext instanceContext = networkPartitionContext.
                    getInstanceContext(instanceId);
            ParentInstanceContext parentInstanceContext = (ParentInstanceContext) instanceContext;
            if (instanceContext != null) {
                if (parentInstanceContext.containsScalingEvent(id)) {
                    parentInstanceContext.removeScalingEvent(id);
                    parentInstanceContext.addScalingEvent(scalingEvent);
                } else {
                    parentInstanceContext.addScalingEvent(scalingEvent);
                }
            }
        }

    }

    /**
     * This will get triggered by the child when scale down beyond min happened in the child
     *
     * @param scalingDownBeyondMinEvent scalingDownBeyondMinEvent used to keep the instance-id,
     *                                  network-partition-id of the instance
     *                                  which is trying to get scale down.
     */
    public void onChildScalingDownBeyondMinEvent(ScalingDownBeyondMinEvent scalingDownBeyondMinEvent) {

        String networkPartitionId = scalingDownBeyondMinEvent.getNetworkPartitionId();
        String instanceId = scalingDownBeyondMinEvent.getInstanceId();
        InstanceContext instanceContext = getNetworkPartitionContext(networkPartitionId).
                getInstanceContext(instanceId);
        ((ParentInstanceContext) instanceContext).addScalingDownBeyondMinEvent(scalingDownBeyondMinEvent);
    }

    @Override
    public void onChildScalingOverMaxEvent(ScalingUpBeyondMaxEvent scalingUpBeyondMaxEvent) {
        if (log.isDebugEnabled()) {
            log.debug("Child Scaling max out event received to [group]: " + this.getId()
                    + ", [network partition]: " + scalingUpBeyondMaxEvent.getNetworkPartitionId()
                    + ", [event] " + scalingUpBeyondMaxEvent.getId() + ", " +
                    "[group instance] " + scalingUpBeyondMaxEvent.getInstanceId());
        }
        //adding the scaling over max event to group instance Context
        String networkPartitionId = scalingUpBeyondMaxEvent.getNetworkPartitionId();
        String instanceId = scalingUpBeyondMaxEvent.getInstanceId();
        String id = scalingUpBeyondMaxEvent.getId();
        NetworkPartitionContext networkPartitionContext =
                this.getNetworkPartitionContextsMap().get(networkPartitionId);
        if (networkPartitionContext != null) {
            InstanceContext instanceContext = networkPartitionContext.
                    getInstanceContext(instanceId);
            if (instanceContext != null) {
                ParentInstanceContext parentInstanceContext = (ParentInstanceContext) instanceContext;
                if (parentInstanceContext.containsScalingEvent(id)) {
                    parentInstanceContext.removeScalingOverMaxEvent(id);
                    parentInstanceContext.addScalingOverMaxEvent(scalingUpBeyondMaxEvent);
                } else {
                    parentInstanceContext.addScalingOverMaxEvent(scalingUpBeyondMaxEvent);
                }
            }
        }
        //calling monitor to go for group scaling or notify the parent
        //this.monitor();

    }

    public NetworkPartitionContext getNetworkPartitionContext(String networkPartitionId) {
        return this.getNetworkPartitionContextsMap().get(networkPartitionId);
    }

    /**
     * This will start the child monitors based on the active of siblings according to start up order
     *
     * @param childId parent id of the event which received
     */
    protected void onChildActivatedEvent(String childId, String instanceId) {

        removeInstanceFromFromInactiveMap(childId, instanceId);
        removeInstanceFromFromTerminatingMap(childId, instanceId);

        boolean startDep = false;
        if (!aliasToActiveChildMonitorsMap.containsKey(childId) ||
                !pendingChildMonitorsList.contains(childId)) {

            // Need to decide whether it has become active in the first iteration.
            // Then need to start the dependents.
            // If it is a second iteration, then if there is no dependents,
            // no need to invoke start dependencies.

            Monitor childMonitor = aliasToActiveChildMonitorsMap.get(childId);
            if (childMonitor != null) {
                Instance instance = childMonitor.getInstance(instanceId);
                boolean firstIteration = false;
                if (instance != null) {
                    if (instance instanceof GroupInstance) {
                        GroupInstance groupInstance = (GroupInstance) instance;
                        firstIteration = groupInstance.getPreviousState() == GroupStatus.Created;
                    } else if (instance instanceof ClusterInstance) {
                        ClusterInstance clusterInstance = (ClusterInstance) instance;
                        firstIteration = clusterInstance.getPreviousState() == ClusterStatus.Created;
                    }
                    if (firstIteration || childMonitor.hasStartupDependents()) {
                        startDep = startDependency(childId, instanceId);
                    }
                } else {
                    startDep = startDependency(childId, instanceId);
                }
            } else {
                startDep = startDependency(childId, instanceId);
            }

        }

        //Checking whether all the monitors got created
        if (!startDep) {
            ServiceReferenceHolder.getInstance().getGroupStatusProcessorChain().
                    process(this.id, this.appId, instanceId);
        } else {
            log.info("started a child upon activation of " + childId +
                    " for [application] " + appId + " [" + getMonitorType() + "] " + id);
        }

    }

    /**
     * This will act upon the any child in-activated event and terminate other dependents or
     * terminate all according to the termination behavior
     *
     * @param childId    id of the child
     * @param instanceId id of the instance which got the status changed
     */
    protected void onChildInactiveEvent(String childId, final String instanceId) {
        List<ApplicationChildContext> terminationList;
        terminationList = this.startupDependencyTree.getTerminationDependencies(childId);

        //Need to notify the parent about the status  change from Active-->Inactive
        ServiceReferenceHolder.getInstance().getGroupStatusProcessorChain().
                process(id, appId, instanceId);

        /**
         * Since it is reached the most independent unit and has few independent monitors,
         * has to put the children down to terminating
         */
        if (this.startupDependencyTree.getTerminationBehavior() ==
                DependencyTree.TerminationBehavior.TERMINATE_ALL &&
                terminationList.size() == this.aliasToActiveChildMonitorsMap.size()) {
            //handling the kill-all scenario
            if (parent != null) {
                //send terminating to the parent. So that it will push terminating to its children
                log.info("[group-instance] " + instanceId + "  in [group] " + id +
                        " in [application] " + appId + " has been marked as " +
                        "terminating due to [terminate-all] behavior");
                ApplicationBuilder.handleGroupTerminatingEvent(appId, id, instanceId);

            } else {
                //if it is an application, send terminating event individually for children
                log.info("Since this is application, all children will get terminated one-by-one " +
                        "for [application] " + appId + " [application-instance] " + instanceId +
                        " due to [terminate-all] behavior");
                sendTerminatingEventOnNotification(terminationList, childId, true, instanceId);
            }
        } else {
            log.info("Dependent children of [instance] " + instanceId + "  in [group] " + id +
                    " in [application] " + appId + " will be marked as terminating due to " +
                    "[terminate-dependents] behavior");
            sendTerminatingEventOnNotification(terminationList, childId, false, instanceId);
        }
    }

    /**
     * Utility method to send the termination notification to group/cluster based on termination list
     *
     * @param terminationList termination list of siblings
     * @param notifier        who notified
     * @param terminateAll    whether terminate-all or not
     * @param instanceId      instance id of the instance
     */
    private void sendTerminatingEventOnNotification(List<ApplicationChildContext> terminationList,
                                                    String notifier, boolean terminateAll, String instanceId) {
        Monitor monitor;
        //Checking the termination dependents status
        for (ApplicationChildContext terminationContext : terminationList) {
            //Check whether dependent is in_active, then start to kill it
            monitor = this.aliasToActiveChildMonitorsMap.
                    get(terminationContext.getId());
            //start to kill it
            if (monitor != null) {
                if (monitor instanceof GroupMonitor) {
                    //it is a group, so not sending terminating as it can be in inactive. If group needs terminating,
                    //it will be handled by the terminating case of its children
                    if (terminateAll || !notifier.equals(monitor.getId())) {
                        ApplicationBuilder.handleGroupTerminatingEvent(this.appId,
                                terminationContext.getId(), instanceId);
                    }
                } else {
                    if (log.isInfoEnabled()) {
                        log.info("Publishing Cluster Terminating event for [application] " + appId +
                                " [group] " + this.id + " [cluster]: " + terminationContext.getId());
                    }
                    ClusterStatusEventPublisher.sendClusterStatusClusterTerminatingEvent(this.appId,
                            ((ClusterMonitor) monitor).getServiceId(),
                            terminationContext.getId(), instanceId);
                }
            } else {
                log.warn("The relevant [monitor] " + terminationContext.getId() +
                        " in [application] " + appId + "is not in the active map....");
            }

        }
    }

    /**
     * Act upon one of its children got terminated
     *
     * @param eventId id of the notifier
     */
    protected void onChildTerminatedEvent(String eventId, String instanceId) {
        List<ApplicationChildContext> terminationList;
        boolean allDependentTerminated = false;

        //Retrieving the termination list
        terminationList = this.startupDependencyTree.getTerminationDependencies(eventId);

        //Make sure that all the dependents have been terminated properly to start the recovery
        if (terminationList != null) {
            allDependentTerminated = allDependentTerminated(terminationList, instanceId);
        }
        log.info("Calculating the dependencies to be started upon the termination of the " +
                "[group/cluster] " + eventId + " for [instance] " + instanceId +
                " of [application] " + appId);

        List<ApplicationChildContext> parentContexts = this.startupDependencyTree.
                findAllParentContextWithId(eventId);
        boolean parentsTerminated = false;
        boolean allParentsActive = false;
        //make sure all the parent contexts got terminated or whether all of them are active
        if (parentContexts != null) {
            parentsTerminated = allParentTerminated(parentContexts, instanceId);
            allParentsActive = allParentActive(parentContexts, instanceId);
        }

        if ((terminationList == null || terminationList.isEmpty() || allDependentTerminated) &&
                (parentContexts == null || parentContexts.isEmpty() ||
                        parentsTerminated || allParentsActive)) {
            //Starting the dependency sibling upon termination of most in-dependent sibling
            this.startDependencyOnTermination(instanceId);
        } else {
            ServiceReferenceHolder.getInstance().getGroupStatusProcessorChain().
                    process(id, appId, instanceId);
            log.info("Checking the status of [group/application] as no dependent found for " +
                    "[application] " + appId + " [group] " + id + " [instance] " + instanceId);
        }

    }

    /**
     * Calculating whether all the dependent has terminated or not
     *
     * @param terminationList termination list of siblings
     * @param instanceId      instance id of the instance
     * @return whether all dependents terminated or not
     */
    private boolean allDependentTerminated(List<ApplicationChildContext> terminationList, String instanceId) {
        boolean allDependentTerminated = false;
        for (ApplicationChildContext context1 : terminationList) {
            if (this.inactiveInstancesMap.containsKey(context1.getId()) &&
                    this.inactiveInstancesMap.get(context1.getId()).contains(instanceId)
                    || this.terminatingInstancesMap.containsKey(context1.getId()) &&
                    this.terminatingInstancesMap.get(context1.getId()).contains(instanceId)) {
                log.info("Waiting for the [dependent] " + context1.getId() + " [instance] " +
                        instanceId + "to be terminated...");
                return false;
            } else if (this.aliasToActiveChildMonitorsMap.get(context1.getId()).getInstance(instanceId) != null) {
                log.info("[Dependent] " + context1.getId() + "[Instance] " + instanceId +
                        "has not been started to terminate yet. Hence waiting....");
            } else {
                allDependentTerminated = true;
            }
        }
        return allDependentTerminated;
    }

    /**
     * Calculating whether all the required siblings are terminated or not
     *
     * @param parentContexts all the siblings who required to be active
     * @param instanceId     instance id of the instance which has state change
     * @return whether all the required siblings are terminated or not
     */
    private boolean allParentTerminated(List<ApplicationChildContext> parentContexts,
                                        String instanceId) {
        boolean parentsTerminated = false;
        for (ApplicationChildContext context1 : parentContexts) {
            if (this.inactiveInstancesMap.containsKey(context1.getId()) &&
                    this.inactiveInstancesMap.get(context1.getId()).contains(instanceId)
                    || this.terminatingInstancesMap.containsKey(context1.getId()) &&
                    this.terminatingInstancesMap.get(context1.getId()).contains(instanceId)) {
                log.info("Waiting for the [Parent Monitor] " + context1.getId()
                        + " to be terminated");
                return false;
            } else if (this.aliasToActiveChildMonitorsMap.get(context1.getId()).getInstance(instanceId) != null) {
                log.info("[Dependent Parent] " + context1.getId() + "[Instance] " + instanceId +
                        "has not been started to terminate yet. Hence waiting....");
            } else {
                log.info("[Parent Monitor] " + context1.getId()
                        + " has already been terminated");
                parentsTerminated = true;
            }
        }
        return parentsTerminated;
    }

    /**
     * Calculating whether all the required siblings are active or not
     *
     * @param parentContexts all the siblings who required to be active
     * @param instanceId     instance id of the instance which has state change
     * @return whether all the required siblings are active or not
     */
    private boolean allParentActive(List<ApplicationChildContext> parentContexts, String instanceId) {
        boolean parentsActive = false;
        for (ApplicationChildContext context1 : parentContexts) {
            if (this.inactiveInstancesMap.containsKey(context1.getId()) &&
                    this.inactiveInstancesMap.get(context1.getId()).contains(instanceId) ||
                    this.terminatingInstancesMap.containsKey(context1.getId()) &&
                            this.terminatingInstancesMap.get(context1.getId()).contains(instanceId)) {
                log.info("Dependent [Monitor] " + context1.getId()
                        + " is not yet active");
                return false;
            } else if (this.aliasToActiveChildMonitorsMap.containsKey(context1.getId())) {
                Monitor monitor = this.aliasToActiveChildMonitorsMap.get(context1.getId());

                if (monitor instanceof GroupMonitor) {
                    try {
                        ApplicationHolder.acquireReadLock();
                        //verify whether the GroupInstance is active or not
                        parentsActive = verifyGroupStatus(context1.getId(), instanceId,
                                GroupStatus.Active);
                    } finally {
                        ApplicationHolder.releaseReadLock();
                    }
                } else if (monitor instanceof ClusterMonitor) {
                    ClusterMonitor monitor1 = (ClusterMonitor) monitor;
                    try {
                        TopologyManager.acquireReadLockForCluster(monitor1.getServiceId(),
                                monitor1.getClusterId());
                        ClusterInstance clusterInstance = (ClusterInstance) monitor1.
                                getInstance(instanceId);
                        parentsActive = clusterInstance != null &&
                                clusterInstance.getStatus() == ClusterStatus.Active;
                    } finally {
                        TopologyManager.releaseReadLockForCluster(monitor1.getServiceId(),
                                monitor1.getClusterId());
                    }
                }

            }
        }
        return parentsActive;
    }

    /**
     * Calculating whether the instance of the group in a required status
     *
     * @param childId        id of the child where the instance resides
     * @param instanceId     instance id of the instance which has state change
     * @param requiredStatus the status to be checked
     * @return whether the group instance in required status or not
     */
    public boolean verifyGroupStatus(String childId, String instanceId, GroupStatus requiredStatus) {
        Monitor monitor = this.getMonitor(childId);
        if (!(monitor instanceof GroupMonitor)) {
            return false;
        }
        List<String> groupInstances;
        GroupInstance groupInstance = (GroupInstance) monitor.getInstance(instanceId);
        if (groupInstance == null) {
            groupInstances = monitor.getInstancesByParentInstanceId(instanceId);
        } else {
            return groupInstance.getStatus() == requiredStatus;
        }

        String networkPartitionId = null;
        int noOfInstancesOfRequiredStatus = 0;
        for (String childInstanceId : groupInstances) {
            GroupInstance childGroupInstance = (GroupInstance) monitor.getInstance(childInstanceId);
            networkPartitionId = childGroupInstance.getNetworkPartitionId();
            if (childGroupInstance.getStatus() == requiredStatus) {
                noOfInstancesOfRequiredStatus++;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug(String.format("Calculating the group instances status for [application] " +
                            "%s [group] %s [group-instance] %s [required-status] %s [no-of-instances] %s",
                    appId, childId, instanceId, requiredStatus.toString(),
                    noOfInstancesOfRequiredStatus));
        }

        if (!groupInstances.isEmpty()) {
            NetworkPartitionContext networkPartitionContext =
                    (NetworkPartitionContext) ((GroupMonitor) monitor).
                            getNetworkPartitionContextsMap().get(networkPartitionId);
            int minInstances = networkPartitionContext.getMinInstanceCount();
            //if terminated all the instances in this instances map should be in terminated state
            if (noOfInstancesOfRequiredStatus == this.inactiveInstancesMap.size() &&
                    requiredStatus == GroupStatus.Terminated) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Group instances in required status for [application] " +
                                    "%s [group] %s [group-instance] %s [required-status] %s",
                            appId, childId, instanceId, GroupStatus.Terminated.toString()));
                }
                return true;
            } else if (noOfInstancesOfRequiredStatus >= minInstances) {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Group instances in required status for [application] " +
                                    "%s [group] %s [group-instance] %s [required-status] %s",
                            appId, childId, instanceId, requiredStatus.toString()));
                }
                return true;
            } else {
                //of only one is inActive implies that the whole group is Inactive
                if (requiredStatus == GroupStatus.Inactive && noOfInstancesOfRequiredStatus >= 1) {
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Group instances in required status for [application] " +
                                        "%s [group] %s [group-instance] %s [required-status] %s",
                                appId, childId, instanceId, GroupStatus.Inactive.toString()));
                    }
                    return true;
                }
            }

        }
        return false;
    }

    /**
     * handling the dependent scaling
     *
     * @param instanceContext         instance-context of the Instance which receives
     *                                the scale notification from the child
     * @param networkPartitionContext network-partition-context which belongs to the instance
     */
    protected void handleDependentScaling(ParentInstanceContext instanceContext,
                                          NetworkPartitionContext networkPartitionContext) {
        /**
         * Dependency scaling handling
         * Finding out the highest scaling events within the scaling dependencies
         */
        List<ScalingEvent> highestScalingEventOfDependencies = new ArrayList<ScalingEvent>();
        for (ScalingDependentList scalingDependentList : scalingDependencies) {
            ScalingEvent highestFactorEvent = null;
            for (String scalingDependentListComponent : scalingDependentList.
                    getScalingDependentListComponents()) {
                ScalingEvent scalingEvent = instanceContext.
                        getScalingEvent(scalingDependentListComponent);
                if (scalingEvent != null) {
                    if (highestFactorEvent == null) {
                        highestFactorEvent = scalingEvent;
                    } else {
                        if (scalingEvent.getFactor() > highestFactorEvent.getFactor()) {
                            highestFactorEvent = scalingEvent;
                        }
                    }
                }
            }
            if (highestFactorEvent != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Found the highest factor for the [dependent set] " +
                            highestFactorEvent.getId() + " the factor is " +
                            highestFactorEvent.getFactor());
                }
                highestScalingEventOfDependencies.add(highestFactorEvent);
            }
        }

        for (ScalingEvent highestScalingEventOfChild : highestScalingEventOfDependencies) {
            //find the child context of this group,
            //Notifying children, if this group has scaling dependencies
            if (scalingDependencies != null && !scalingDependencies.isEmpty()) {
                for (ScalingDependentList scalingDependentList : scalingDependencies) {
                    if (scalingDependentList.getScalingDependentListComponents().
                            contains(highestScalingEventOfChild.getId())) {
                        for (String scalingDependentListComponent : scalingDependentList
                                .getScalingDependentListComponents()) {
                            Monitor monitor = aliasToActiveChildMonitorsMap.get(
                                    scalingDependentListComponent);
                            if (monitor instanceof GroupMonitor ||
                                    monitor instanceof ClusterMonitor) {
                                ScalingEvent scalingEvent = new ScalingEvent(monitor.getId(),
                                        networkPartitionContext.getId(),
                                        instanceContext.getId(),
                                        highestScalingEventOfChild.getFactor());

                                log.info("Notifying the [child] " + scalingEvent.getId() + " [instance] " +
                                        scalingEvent.getInstanceId() + " with the highest [factor] " +
                                        scalingEvent.getFactor() + " upon decision of dependent scaling");

                                monitor.onParentScalingEvent(scalingEvent);
                            }
                        }
                        break;
                    }

                }
            }
        }
    }

    /**
     * move to inactive monitors list to use in the Terminated event
     *
     * @param childId    id of the child where the instance resides
     * @param instanceId instance id of the instance which has state change
     */
    protected synchronized void markInstanceAsInactive(String childId, String instanceId) {
        if (this.inactiveInstancesMap.containsKey(childId)) {
            this.inactiveInstancesMap.get(childId).add(instanceId);
        } else {
            List<String> instanceIds = new ArrayList<String>();
            instanceIds.add(instanceId);
            this.inactiveInstancesMap.put(childId, instanceIds);
        }
    }

    /**
     * move to inactive monitors list to use in the Terminated event
     *
     * @param childId    id of the child where the instance resides
     * @param instanceId instance id of the instance which has state change
     */
    protected synchronized void removeInstanceFromFromInactiveMap(String childId,
                                                                  String instanceId) {
        if (this.inactiveInstancesMap.containsKey(childId) &&
                this.inactiveInstancesMap.get(childId).contains(instanceId)) {
            this.inactiveInstancesMap.get(childId).remove(instanceId);
            if (this.inactiveInstancesMap.get(childId).isEmpty()) {
                this.inactiveInstancesMap.remove(childId);
            }
        }
    }

    /**
     * move to inactive monitors list to use in the Terminated event
     *
     * @param childId    id of the child where the instance resides
     * @param instanceId instance id of the instance which has state change
     */
    protected synchronized void removeInstanceFromFromTerminatingMap(String childId, String instanceId) {
        if (this.terminatingInstancesMap.containsKey(childId) &&
                this.terminatingInstancesMap.get(childId).contains(instanceId)) {
            this.terminatingInstancesMap.get(childId).remove(instanceId);
            if (this.terminatingInstancesMap.get(childId).isEmpty()) {
                this.terminatingInstancesMap.remove(childId);
            }
        }
    }

    /**
     * move to inactive monitors list to use in the Terminated event
     *
     * @param childId    id of the child where the instance resides
     * @param instanceId instance id of the instance which has state change
     */
    protected synchronized void markInstanceAsTerminating(String childId, String instanceId) {
        if (this.inactiveInstancesMap.containsKey(childId) &&
                this.inactiveInstancesMap.get(childId).contains(instanceId)) {
            this.inactiveInstancesMap.get(childId).remove(instanceId);
        }
        if (this.terminatingInstancesMap.containsKey(childId)) {
            this.terminatingInstancesMap.get(childId).add(instanceId);
        } else {
            List<String> instanceIds = new ArrayList<String>();
            instanceIds.add(instanceId);
            this.terminatingInstancesMap.put(childId, instanceIds);
        }
    }

    /**
     * Utility method to start the monitor thread for the children
     *
     * @param parent            The parent monitor which starting its own children
     * @param context           the child context which used to start the specific child
     * @param parentInstanceIds the instance-ids of the parent instance
     */
    protected synchronized void startMonitor(ParentComponentMonitor parent,
                                             ApplicationChildContext context, List<String> parentInstanceIds) {
        if (!this.aliasToActiveChildMonitorsMap.containsKey(context.getId())) {
            pendingChildMonitorsList.add(context.getId());
            executorService.submit(new MonitorAdder(parent, context, this.appId, parentInstanceIds));

            String monitorTypeStr = AutoscalerUtil.findMonitorType(context).toString().toLowerCase();
            log.info(String.format("Monitor scheduled: [type] %s [component] %s ",
                    monitorTypeStr, context.getId()));
        }
    }

    /**
     * This will return the child monitors map
     *
     * @return child monitors map
     */
    public Map<String, Monitor> getAliasToActiveChildMonitorsMap() {
        return aliasToActiveChildMonitorsMap;
    }

    /**
     * This will return the specific child monitor
     *
     * @param childId id of the child
     * @return child monitor
     */
    public Monitor getMonitor(String childId) {
        return this.aliasToActiveChildMonitorsMap.get(childId);
    }

    /**
     * Whether the monitor has child monitors or not
     *
     * @return true if the monitor has child monitors
     */
    public boolean hasMonitors() {

        return this.aliasToActiveChildMonitorsMap != null;
    }

    /**
     * This will give the algorithm for the partitions for this monitor
     *
     * @param partitionAlgorithm algorithm name to be used for the partitions
     * @return partition-algorithm instance of relevant partition algorithm
     */
    public PartitionAlgorithm getAutoscaleAlgorithm(String partitionAlgorithm) {
        PartitionAlgorithm autoscaleAlgorithm = null;
        if (log.isDebugEnabled()) {
            log.debug(String.format("Partition algorithm is %s ", partitionAlgorithm));
        }
        if (StratosConstants.PARTITION_ROUND_ROBIN_ALGORITHM_ID.equals(partitionAlgorithm)) {

            autoscaleAlgorithm = new RoundRobin();
        } else if (StratosConstants.PARTITION_ONE_AFTER_ANOTHER_ALGORITHM_ID.equals(partitionAlgorithm)) {

            autoscaleAlgorithm = new OneAfterAnother();
        } else {
            if (log.isErrorEnabled()) {
                log.error(String.format("Partition algorithm %s could not be identified !", partitionAlgorithm));
            }
        }
        return autoscaleAlgorithm;
    }

    /**
     * Scale dependencies from the children
     *
     * @return scale dependencies
     */
    public Set<ScalingDependentList> getScalingDependencies() {
        return scalingDependencies;
    }

    /**
     * Startup-order tree built among the children according to the specified startup-order
     *
     * @return startup-dependency-tree
     */
    public DependencyTree getStartupDependencyTree() {
        return startupDependencyTree;
    }

    /**
     * This will give the network partitions used by this monitor
     *
     * @return network-partition-contexts
     */
    public Map<String, NetworkPartitionContext> getNetworkPartitionContextsMap() {
        return networkPartitionContextsMap;
    }

    /**
     * This will give the network partitions used by this monitor
     *
     * @return network-partition-contexts
     */
    public void removeNetworkPartitionContext(String networkPartitionId) {
        networkPartitionContextsMap.remove(networkPartitionId);
    }

    /**
     * Inner class used a Thread to start the relevant child monitor in a asynchronous manner
     */
    private class MonitorAdder implements Runnable {

        private final ApplicationChildContext context;
        private final ParentComponentMonitor parent;
        private final String appId;
        private final List<String> parentInstanceIds;
        private final String monitorTypeStr;

        public MonitorAdder(ParentComponentMonitor parent, ApplicationChildContext context,
                            String appId, List<String> parentInstanceIds) {
            this.parent = parent;
            this.context = context;
            this.appId = appId;
            this.parentInstanceIds = parentInstanceIds;
            this.monitorTypeStr = AutoscalerUtil.findMonitorType(context).toString().toLowerCase();
        }

        public void run() {
            try {
                long startTime = System.currentTimeMillis();
                long endTime = startTime;
                int retries = 5;
                Monitor monitor = null;
                boolean success = false;
                while (!success && retries >= 0) {

                    startTime = System.currentTimeMillis();
                    if (log.isInfoEnabled()) {
                        log.info(String.format("Starting monitor: [type] %s [component] %s",
                                monitorTypeStr, context.getId()));
                    }

                    try {
                        monitor = MonitorFactory.getMonitor(parent, context, appId, parentInstanceIds);
                    } catch (DependencyBuilderException e) {
                        String msg = String.format("Monitor creation failed: [type] %s [component] %s",
                                monitorTypeStr, context.getId());
                        log.warn(msg, e);
                        retries--;
                    } catch (TopologyInConsistentException e) {
                        String msg = String.format("Monitor creation failed: [type] %s [component] %s",
                                monitorTypeStr, context.getId());
                        log.warn(msg, e);
                        retries--;
                    } catch (PolicyValidationException e) {
                        String msg = String.format("Monitor creation failed: [type] %s [component] %s",
                                monitorTypeStr, context.getId());
                        log.warn(msg, e);
                        retries--;
                    } catch (PartitionValidationException e) {
                        String msg = String.format("Monitor creation failed: [type] %s [component] %s",
                                monitorTypeStr, context.getId());
                        log.warn(msg, e);
                        retries--;
                    }
                    success = true;
                    endTime = System.currentTimeMillis();
                }

                if (monitor == null) {
                    String msg = String.format("Monitor creation failed even after retrying for " +
                            "5 times: [type] %s [component] %s ", monitorTypeStr, context.getId());
                    log.error(msg);
                    throw new RuntimeException(msg);
                }

                aliasToActiveChildMonitorsMap.put(context.getId(), monitor);
                pendingChildMonitorsList.remove(context.getId());

                if (log.isInfoEnabled()) {
                    long startupTime = (endTime - startTime) / 1000;
                    log.info(String.format("Monitor started successfully: [type] %s [component] %s [dependents] %s " +
                                    "[startup-time] %d seconds", monitorTypeStr, context.getId(),
                            getIdList(context.getApplicationChildContextList()), startupTime));
                }
            } catch (Exception e) {
                log.error(String.format("An error occurred while starting monitor: [type] %s [component] %s",
                        monitorTypeStr, context.getId()), e);
            }
        }

        private String getIdList(List<ApplicationChildContext> applicationChildContextList) {
            StringBuilder stringBuilder = new StringBuilder();
            if ((applicationChildContextList != null) && (applicationChildContextList.size() > 0)) {
                for (ApplicationChildContext applicationChildContext : applicationChildContextList) {
                    stringBuilder.append(applicationChildContext.getId());
                    if (applicationChildContextList.indexOf(applicationChildContext) <
                            (applicationChildContextList.size() - 1)) {
                        stringBuilder.append(", ");
                    }
                }
            } else {
                stringBuilder.append("none");
            }
            return stringBuilder.toString();
        }
    }
}