text:
"""Logical units dealing with instance migration an failover."""

import logging
import time

from ganeti import constants
from ganeti import errors
from ganeti import locking
from ganeti import hypervisor
from ganeti.masterd import iallocator
from ganeti import utils
from ganeti.cmdlib.base import LogicalUnit, Tasklet
from ganeti.cmdlib.common import ExpandInstanceUuidAndName, \
  CheckIAllocatorOrNode, ExpandNodeUuidAndName
from ganeti.cmdlib.instance_storage import CheckDiskConsistency, \
  ExpandCheckDisks, ShutdownInstanceDisks, AssembleInstanceDisks
from ganeti.cmdlib.instance_utils import BuildInstanceHookEnvByObject, \
  CheckTargetNodeIPolicy, ReleaseLocks, CheckNodeNotDrained, \
  CopyLockList, CheckNodeFreeMemory, CheckInstanceBridgesExist

import ganeti.masterd.instance

def _ExpandNamesForMigration(lu):
  """Expands names for use with L{TLMigrateInstance}.

  @type lu: L{LogicalUnit}

  """
  if lu.op.target_node is not None:
    (lu.op.target_node_uuid, lu.op.target_node) = \
      ExpandNodeUuidAndName(lu.cfg, lu.op.target_node_uuid, lu.op.target_node)

  lu.needed_locks[locking.LEVEL_NODE] = []
  lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
  lu.dont_collate_locks[locking.LEVEL_NODE] = True

  lu.needed_locks[locking.LEVEL_NODE_RES] = []
  lu.recalculate_locks[locking.LEVEL_NODE_RES] = constants.LOCKS_REPLACE
  lu.dont_collate_locks[locking.LEVEL_NODE_RES] = True

def _DeclareLocksForMigration(lu, level):
  """Declares locks for L{TLMigrateInstance}.

  @type lu: L{LogicalUnit}
  @param level: Lock level

  """
  if level == locking.LEVEL_NODE:
    assert lu.op.instance_name in lu.owned_locks(locking.LEVEL_INSTANCE)

    instance = lu.cfg.GetInstanceInfo(lu.op.instance_uuid)

    disks = lu.cfg.GetInstanceDisks(instance.uuid)
    if utils.AnyDiskOfType(disks, constants.DTS_EXT_MIRROR):
      if lu.op.target_node is None:
        lu.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
      else:
        lu.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
                                               lu.op.target_node_uuid]
    else:
      lu._LockInstancesNodes() # pylint: disable=W0212

    assert (lu.needed_locks[locking.LEVEL_NODE] or
            lu.needed_locks[locking.LEVEL_NODE] is locking.ALL_SET)

  elif level == locking.LEVEL_NODE_RES:
    # Copy node locks
    lu.needed_locks[locking.LEVEL_NODE_RES] = \
      CopyLockList(lu.needed_locks[locking.LEVEL_NODE])

class LUInstanceFailover(LogicalUnit):
  """Failover an instance.

  This is migration by shutting the instance down, but with the disks
  of the instance already available on the new node.

  See also:
  L{LUInstanceMove} for moving an instance by copying the data.

  L{LUInstanceMigrate} for the live migration of an instance (no shutdown
  required).
  """
  HPATH = "instance-failover"
  HTYPE = constants.HTYPE_INSTANCE
  REQ_BGL = False

  def CheckArguments(self):
    """Check the arguments.

    """
    self.iallocator = getattr(self.op, "iallocator", None)
    self.target_node = getattr(self.op, "target_node", None)

  def ExpandNames(self):
    self._ExpandAndLockInstance(allow_forthcoming=True)
    _ExpandNamesForMigration(self)

    self._migrater = \
      TLMigrateInstance(self, self.op.instance_uuid, self.op.instance_name,
                        self.op.cleanup, True, False,
                        self.op.ignore_consistency, True,
                        self.op.shutdown_timeout, self.op.ignore_ipolicy, True)

    self.tasklets = [self._migrater]

  def DeclareLocks(self, level):
    _DeclareLocksForMigration(self, level)

  def BuildHooksEnv(self):
    """Build hooks env.

    This runs on master, primary and secondary nodes of the instance.

    """
    instance = self._migrater.instance
    source_node_uuid = instance.primary_node
    target_node_uuid = self._migrater.target_node_uuid
    env = {
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
      "OLD_PRIMARY": self.cfg.GetNodeName(source_node_uuid),
      "NEW_PRIMARY": self.cfg.GetNodeName(target_node_uuid),
      "FAILOVER_CLEANUP": self.op.cleanup,
      }

    disks = self.cfg.GetInstanceDisks(instance.uuid)
    if utils.AnyDiskOfType(disks, constants.DTS_INT_MIRROR):
      secondary_nodes = self.cfg.GetInstanceSecondaryNodes(instance.uuid)
      env["OLD_SECONDARY"] = self.cfg.GetNodeName(secondary_nodes[0])
      env["NEW_SECONDARY"] = self.cfg.GetNodeName(source_node_uuid)
    else:
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""

    env.update(BuildInstanceHookEnvByObject(self, instance))

    return env

  def BuildHooksNodes(self):
    """Build hooks nodes.

    """
    instance = self._migrater.instance
    secondary_nodes = self.cfg.GetInstanceSecondaryNodes(instance.uuid)
    nl = [self.cfg.GetMasterNode()] + list(secondary_nodes)
    nl.append(self._migrater.target_node_uuid)
    return (nl, nl + [instance.primary_node])

class LUInstanceMigrate(LogicalUnit):
  """Migrate an instance.

  This is migration without shutting down (live migration) and the disks are
  already available on the new node.

  See also:
  L{LUInstanceMove} for moving an instance by copying the data.

  L{LUInstanceFailover} for the migration of an instance where a shutdown is
  required.
  """
  HPATH = "instance-migrate"
  HTYPE = constants.HTYPE_INSTANCE
  REQ_BGL = False

  def ExpandNames(self):
    self._ExpandAndLockInstance()
    _ExpandNamesForMigration(self)

    self._migrater = \
      TLMigrateInstance(self, self.op.instance_uuid, self.op.instance_name,
                        self.op.cleanup, False, self.op.allow_failover, False,
                        self.op.allow_runtime_changes,
                        constants.DEFAULT_SHUTDOWN_TIMEOUT,
                        self.op.ignore_ipolicy, self.op.ignore_hvversions)

    self.tasklets = [self._migrater]

  def DeclareLocks(self, level):
    _DeclareLocksForMigration(self, level)

  def BuildHooksEnv(self):
    """Build hooks env.

    This runs on master, primary and secondary nodes of the instance.

    """
    instance = self._migrater.instance
    source_node_uuid = instance.primary_node
    target_node_uuid = self._migrater.target_node_uuid
    env = BuildInstanceHookEnvByObject(self, instance)
    env.update({
      "MIGRATE_LIVE": self._migrater.live,
      "MIGRATE_CLEANUP": self.op.cleanup,
      "OLD_PRIMARY": self.cfg.GetNodeName(source_node_uuid),
      "NEW_PRIMARY": self.cfg.GetNodeName(target_node_uuid),
      "ALLOW_RUNTIME_CHANGES": self.op.allow_runtime_changes,
      })

    disks = self.cfg.GetInstanceDisks(instance.uuid)
    if utils.AnyDiskOfType(disks, constants.DTS_INT_MIRROR):
      secondary_nodes = self.cfg.GetInstanceSecondaryNodes(instance.uuid)
      env["OLD_SECONDARY"] = self.cfg.GetNodeName(secondary_nodes[0])
      env["NEW_SECONDARY"] = self.cfg.GetNodeName(source_node_uuid)
    else:
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""

    return env

  def BuildHooksNodes(self):
    """Build hooks nodes.

    """
    instance = self._migrater.instance
    secondary_nodes = self.cfg.GetInstanceSecondaryNodes(instance.uuid)
    snode_uuids = list(secondary_nodes)
    nl = [self.cfg.GetMasterNode(), instance.primary_node] + snode_uuids
    nl.append(self._migrater.target_node_uuid)
    return (nl, nl)

class TLMigrateInstance(Tasklet):
  """Tasklet class for instance migration.

  @type live: boolean
  @ivar live: whether the migration will be done live or non-live;
      this variable is initalized only after CheckPrereq has run
  @type cleanup: boolean
  @ivar cleanup: Wheater we cleanup from a failed migration
  @type iallocator: string
  @ivar iallocator: The iallocator used to determine target_node
  @type target_node_uuid: string
  @ivar target_node_uuid: If given, the target node UUID to reallocate the
      instance to
  @type failover: boolean
  @ivar failover: Whether operation results in failover or migration
  @type fallback: boolean
  @ivar fallback: Whether fallback to failover is allowed if migration not
                  possible
  @type ignore_consistency: boolean
  @ivar ignore_consistency: Wheter we should ignore consistency between source
                            and target node
  @type shutdown_timeout: int
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
  @type ignore_ipolicy: bool
  @ivar ignore_ipolicy: If true, we can ignore instance policy when migrating
  @type ignore_hvversions: bool
  @ivar ignore_hvversions: If true, accept incompatible hypervisor versions

  """

  # Constants
  _MIGRATION_POLL_INTERVAL = 1      # seconds
  _MIGRATION_FEEDBACK_INTERVAL = 10 # seconds

  def __init__(self, lu, instance_uuid, instance_name, cleanup, failover,
               fallback, ignore_consistency, allow_runtime_changes,
               shutdown_timeout, ignore_ipolicy, ignore_hvversions):
    """Initializes this class.

    """
    Tasklet.__init__(self, lu)

    # Parameters
    self.instance_uuid = instance_uuid
    self.instance_name = instance_name
    self.cleanup = cleanup
    self.live = False # will be overridden later
    self.failover = failover
    self.fallback = fallback
    self.ignore_consistency = ignore_consistency
    self.shutdown_timeout = shutdown_timeout
    self.ignore_ipolicy = ignore_ipolicy
    self.allow_runtime_changes = allow_runtime_changes
    self.ignore_hvversions = ignore_hvversions

  def CheckPrereq(self):
    """Check prerequisites.

    This checks that the instance is in the cluster.

    """
    (self.instance_uuid, self.instance_name) = \
      ExpandInstanceUuidAndName(self.lu.cfg, self.instance_uuid,
                                self.instance_name)
    self.instance = self.cfg.GetInstanceInfo(self.instance_uuid)
    assert self.instance is not None
    cluster = self.cfg.GetClusterInfo()

    if (not self.cleanup and
        not self.instance.admin_state == constants.ADMINST_UP and
        not self.failover and self.fallback):
      self.lu.LogInfo("Instance is marked down or offline, fallback allowed,"
                      " switching to failover")
      self.failover = True

    disks = self.cfg.GetInstanceDisks(self.instance.uuid)

    if not utils.AllDiskOfType(disks, constants.DTS_MIRRORED):
      if self.failover:
        text = "failovers"
      else:
        text = "migrations"
      invalid_disks = set(d.dev_type for d in disks
                             if d.dev_type not in constants.DTS_MIRRORED)
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
                                 " %s" % (utils.CommaJoin(invalid_disks), text),
                                 errors.ECODE_STATE)

    # TODO allow heterogeneous disk types if all are mirrored in some way.
    if utils.AllDiskOfType(disks, constants.DTS_EXT_MIRROR):
      CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")

      if self.lu.op.iallocator:
        self._RunAllocator()
      else:
        # We set set self.target_node_uuid as it is required by
        # BuildHooksEnv
        self.target_node_uuid = self.lu.op.target_node_uuid

      # Check that the target node is correct in terms of instance policy
      nodeinfo = self.cfg.GetNodeInfo(self.target_node_uuid)
      group_info = self.cfg.GetNodeGroup(nodeinfo.group)
      ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(cluster,
                                                              group_info)
      CheckTargetNodeIPolicy(self.lu, ipolicy, self.instance, nodeinfo,
                             self.cfg, ignore=self.ignore_ipolicy)

      # self.target_node is already populated, either directly or by the
      # iallocator run
      target_node_uuid = self.target_node_uuid
      if self.target_node_uuid == self.instance.primary_node:
        raise errors.OpPrereqError(
          "Cannot migrate instance %s to its primary (%s)" %
          (self.instance.name,
           self.cfg.GetNodeName(self.instance.primary_node)),
          errors.ECODE_STATE)

      if len(self.lu.tasklets) == 1:
        # It is safe to release locks only when we're the only tasklet
        # in the LU
        ReleaseLocks(self.lu, locking.LEVEL_NODE,
                     keep=[self.instance.primary_node, self.target_node_uuid])

    elif utils.AllDiskOfType(disks, constants.DTS_INT_MIRROR):
      templates = [d.dev_type for d in disks]
      secondary_node_uuids = \
        self.cfg.GetInstanceSecondaryNodes(self.instance.uuid)
      if not secondary_node_uuids:
        raise errors.ConfigurationError("No secondary node but using"
                                        " %s disk types" %
                                        utils.CommaJoin(set(templates)))
      self.target_node_uuid = target_node_uuid = secondary_node_uuids[0]
      if self.lu.op.iallocator or \
        (self.lu.op.target_node_uuid and
         self.lu.op.target_node_uuid != target_node_uuid):
        if self.failover:
          text = "failed over"
        else:
          text = "migrated"
        raise errors.OpPrereqError("Instances with disk types %s cannot"
                                   " be %s to arbitrary nodes"
                                   " (neither an iallocator nor a target"
                                   " node can be passed)" %
                                   (utils.CommaJoin(set(templates)), text),
                                   errors.ECODE_INVAL)
      nodeinfo = self.cfg.GetNodeInfo(target_node_uuid)
      group_info = self.cfg.GetNodeGroup(nodeinfo.group)
      ipolicy = ganeti.masterd.instance.CalculateGroupIPolicy(cluster,
                                                              group_info)
      CheckTargetNodeIPolicy(self.lu, ipolicy, self.instance, nodeinfo,
                             self.cfg, ignore=self.ignore_ipolicy)

    else:
      raise errors.OpPrereqError("Instance mixes internal and external "
                                 "mirroring. This is not currently supported.")

    i_be = cluster.FillBE(self.instance)

    # check memory requirements on the secondary node
    if (not self.cleanup and
         (not self.failover or
           self.instance.admin_state == constants.ADMINST_UP)):
      self.tgt_free_mem = CheckNodeFreeMemory(
          self.lu, target_node_uuid,
          "migrating instance %s" % self.instance.name,
          i_be[constants.BE_MINMEM], self.instance.hypervisor,
          self.cfg.GetClusterInfo().hvparams[self.instance.hypervisor])
    else:
      self.lu.LogInfo("Not checking memory on the secondary node as"
                      " instance will not be started")

    # check if failover must be forced instead of migration
    if (not self.cleanup and not self.failover and
        i_be[constants.BE_ALWAYS_FAILOVER]):
      self.lu.LogInfo("Instance configured to always failover; fallback"
                      " to failover")
      self.failover = True

    # check bridge existance
    CheckInstanceBridgesExist(self.lu, self.instance,
                              node_uuid=target_node_uuid)

    if not self.cleanup:
      CheckNodeNotDrained(self.lu, target_node_uuid)
      if not self.failover:
        result = self.rpc.call_instance_migratable(self.instance.primary_node,
                                                   self.instance)
        if result.fail_msg and self.fallback:
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
                          " failover")
          self.failover = True
        else:
          result.Raise("Can't migrate, please use failover",
                       prereq=True, ecode=errors.ECODE_STATE)

    assert not (self.failover and self.cleanup)

    if not self.failover:
      if self.lu.op.live is not None and self.lu.op.mode is not None:
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
                                   " parameters are accepted",
                                   errors.ECODE_INVAL)
      if self.lu.op.live is not None:
        if self.lu.op.live:
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
        else:
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
        # reset the 'live' parameter to None so that repeated
        # invocations of CheckPrereq do not raise an exception
        self.lu.op.live = None
      elif self.lu.op.mode is None:
        # read the default value from the hypervisor
        i_hv = cluster.FillHV(self.instance, skip_globals=False)
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]

      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
    else:
      # Failover is never live
      self.live = False

    if not (self.failover or self.cleanup):
      remote_info = self.rpc.call_instance_info(
          self.instance.primary_node, self.instance.name,
          self.instance.hypervisor, cluster.hvparams[self.instance.hypervisor])
      remote_info.Raise("Error checking instance on node %s" %
                        self.cfg.GetNodeName(self.instance.primary_node),
                        prereq=True)
      instance_running = bool(remote_info.payload)
      if instance_running:
        self.current_mem = int(remote_info.payload["memory"])

  def _RunAllocator(self):
    """Run the allocator based on input opcode.

    """
    # FIXME: add a self.ignore_ipolicy option
    req = iallocator.IAReqRelocate(
          inst_uuid=self.instance_uuid,
          relocate_from_node_uuids=[self.instance.primary_node])
    ial = iallocator.IAllocator(self.cfg, self.rpc, req)

    ial.Run(self.lu.op.iallocator)

    if not ial.success:
      raise errors.OpPrereqError("Can't compute nodes using"
                                 " iallocator '%s': %s" %
                                 (self.lu.op.iallocator, ial.info),
                                 errors.ECODE_NORES)
    self.target_node_uuid = self.cfg.GetNodeInfoByName(ial.result[0]).uuid
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
                    self.instance_name, self.lu.op.iallocator,
                    utils.CommaJoin(ial.result))

  def _WaitUntilSync(self):
    """Poll with custom rpc for disk sync.

    This uses our own step-based rpc call.

    """
    self.feedback_fn("* wait until resync is done")
    all_done = False
    disks = self.cfg.GetInstanceDisks(self.instance.uuid)
    while not all_done:
      all_done = True
      result = self.rpc.call_drbd_wait_sync(self.all_node_uuids,
                                            (disks, self.instance))
      min_percent = 100
      for node_uuid, nres in result.items():
        nres.Raise("Cannot resync disks on node %s" %
                   self.cfg.GetNodeName(node_uuid))
        node_done, node_percent = nres.payload
        all_done = all_done and node_done
        if node_percent is not None:
          min_percent = min(min_percent, node_percent)
      if not all_done:
        if min_percent < 100:
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
        time.sleep(2)

  def _OpenInstanceDisks(self, node_uuid, exclusive):
    """Open instance disks.

    """
    if exclusive:
      mode = "in exclusive mode"
    else:
      mode = "in shared mode"

    self.feedback_fn("* opening instance disks on node %s %s" %
                     (self.cfg.GetNodeName(node_uuid), mode))

    disks = self.cfg.GetInstanceDisks(self.instance.uuid)
    result = self.rpc.call_blockdev_open(node_uuid, self.instance.name,
                                         (disks, self.instance), exclusive)
    result.Raise("Cannot open disks on node %s" %
                 self.cfg.GetNodeName(node_uuid))

  def _CloseInstanceDisks(self, node_uuid):
    """Close instance disks.

    """
    self.feedback_fn("* closing instance disks on node %s" %
                     self.cfg.GetNodeName(node_uuid))

    disks = self.cfg.GetInstanceDisks(self.instance.uuid)
    result = self.rpc.call_blockdev_close(node_uuid, self.instance.name,
                                          (disks, self.instance))
    result.Raise("Cannot close instance disks on node %s" %
                 self.cfg.GetNodeName(node_uuid))

  def _GoStandalone(self):
    """Disconnect from the network.

    """
    self.feedback_fn("* changing into standalone mode")
    disks = self.cfg.GetInstanceDisks(self.instance.uuid)
    result = self.rpc.call_drbd_disconnect_net(
               self.all_node_uuids, (disks, self.instance))
    for node_uuid, nres in result.items():
      nres.Raise("Cannot disconnect disks node %s" %
                 self.cfg.GetNodeName(node_uuid))

  def _GoReconnect(self, multimaster):
    """Reconnect to the network.

    """
    if multimaster:
      msg = "dual-master"
    else:
      msg = "single-master"
    self.feedback_fn("* changing disks into %s mode" % msg)
    disks = self.cfg.GetInstanceDisks(self.instance.uuid)
    result = self.rpc.call_drbd_attach_net(self.all_node_uuids,
                                           (disks, self.instance),
                                           multimaster)
    for node_uuid, nres in result.items():
      nres.Raise("Cannot change disks config on node %s" %
                 self.cfg.GetNodeName(node_uuid))

  def _ExecCleanup(self):
    """Try to cleanup after a failed migration.

    The cleanup is done by:
      - check that the instance is running only on one node
        (and update the config if needed)
      - change disks on its secondary node to secondary
      - wait until disks are fully synchronized
      - disconnect from the network
      - change disks into single-master mode
      - wait again until disks are fully synchronized

    """
    # check running on only one node
    self.feedback_fn("* checking where the instance actually runs"
                     " (if this hangs, the hypervisor might be in"
                     " a bad state)")
    cluster_hvparams = self.cfg.GetClusterInfo().hvparams
    ins_l = self.rpc.call_instance_list(self.all_node_uuids,
                                        [self.instance.hypervisor],
                                        cluster_hvparams)
    for node_uuid, result in ins_l.items():
      result.Raise("Can't contact node %s" % node_uuid)

    runningon_source = self.instance.name in \
                         ins_l[self.source_node_uuid].payload
    runningon_target = self.instance.name in \
                         ins_l[self.target_node_uuid].payload

    if runningon_source and runningon_target:
      raise errors.OpExecError("Instance seems to be running on two nodes,"
                               " or the hypervisor is confused; you will have"
                               " to ensure manually that it runs only on one"
                               " and restart this operation")

    if not (runningon_source or runningon_target):
      raise errors.OpExecError("Instance does not seem to be running at all;"
                               " in this case it's safer to repair by"
                               " running 'gnt-instance stop' to ensure disk"
                               " shutdown, and then restarting it")

    if runningon_target:
      # the migration has actually succeeded, we need to update the config
      self.feedback_fn("* instance running on secondary node (%s),"
                       " updating config" %
                       self.cfg.GetNodeName(self.target_node_uuid))
      self.cfg.SetInstancePrimaryNode(self.instance.uuid,
                                      self.target_node_uuid)
      demoted_node_uuid = self.source_node_uuid
    else:
      self.feedback_fn("* instance confirmed to be running on its"
                       " primary node (%s)" %
                       self.cfg.GetNodeName(self.source_node_uuid))
      demoted_node_uuid = self.target_node_uuid

    disks = self.cfg.GetInstanceDisks(self.instance.uuid)

    self._CloseInstanceDisks(demoted_node_uuid)

    if utils.AnyDiskOfType(disks, constants.DTS_INT_MIRROR):
      try:
        self._WaitUntilSync()
      except errors.OpExecError:
        # we ignore here errors, since if the device is standalone, it
        # won't be able to sync
        pass
      self._GoStandalone()
      self._GoReconnect(False)
      self._WaitUntilSync()
    elif utils.AnyDiskOfType(disks, constants.DTS_EXT_MIRROR):
      self._OpenInstanceDisks(self.instance.primary_node, True)

    self.feedback_fn("* done")

  def _RevertDiskStatus(self):
    """Try to revert the disk status after a failed migration.

    """

    disks = self.cfg.GetInstanceDisks(self.instance.uuid)

    self._CloseInstanceDisks(self.target_node_uuid)

    if utils.AllDiskOfType(disks, constants.DTS_EXT_MIRROR):
      self._OpenInstanceDisks(self.source_node_uuid, True)
      return

    try:
      self._GoStandalone()
      self._GoReconnect(False)
      self._WaitUntilSync()
    except errors.OpExecError, err:
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
                         " please try to recover the instance manually;"
                         " error '%s'" % str(err))

  def _AbortMigration(self):
    """Call the hypervisor code to abort a started migration.

    """
    abort_result = self.rpc.call_instance_finalize_migration_dst(
                     self.target_node_uuid, self.instance, self.migration_info,
                     False)
    abort_msg = abort_result.fail_msg
    if abort_msg:
      logging.error("Aborting migration failed on target node %s: %s",
                    self.cfg.GetNodeName(self.target_node_uuid), abort_msg)
      # Don't raise an exception here, as we stil have to try to revert the
      # disk status, even if this step failed.

    abort_result = self.rpc.call_instance_finalize_migration_src(
      self.source_node_uuid, self.instance, False, self.live)
    abort_msg = abort_result.fail_msg
    if abort_msg:
      logging.error("Aborting migration failed on source node %s: %s",
                    self.cfg.GetNodeName(self.source_node_uuid), abort_msg)

  def _ExecMigration(self):
    """Migrate an instance.

    The migrate is done by:
      - change the disks into dual-master mode
      - wait until disks are fully synchronized again
      - migrate the instance
      - change disks on the new secondary node (the old primary) to secondary
      - wait until disks are fully synchronized
      - change disks into single-master mode

    """
    # Check for hypervisor version mismatch and warn the user.
    hvspecs = [(self.instance.hypervisor,
                self.cfg.GetClusterInfo().hvparams[self.instance.hypervisor])]
    nodeinfo = self.rpc.call_node_info(
                 [self.source_node_uuid, self.target_node_uuid], None, hvspecs)
    for ninfo in nodeinfo.values():
      ninfo.Raise("Unable to retrieve node information from node '%s'" %
                  ninfo.node)
    (_, _, (src_info, )) = nodeinfo[self.source_node_uuid].payload
    (_, _, (dst_info, )) = nodeinfo[self.target_node_uuid].payload

    if ((constants.HV_NODEINFO_KEY_VERSION in src_info) and
        (constants.HV_NODEINFO_KEY_VERSION in dst_info)):
      src_version = src_info[constants.HV_NODEINFO_KEY_VERSION]
      dst_version = dst_info[constants.HV_NODEINFO_KEY_VERSION]
      if src_version != dst_version:
        self.feedback_fn("* warning: hypervisor version mismatch between"
                         " source (%s) and target (%s) node" %
                         (src_version, dst_version))
        hv = hypervisor.GetHypervisor(self.instance.hypervisor)
        if hv.VersionsSafeForMigration(src_version, dst_version):
          self.feedback_fn("  migrating from hypervisor version %s to %s should"
                           " be safe" % (src_version, dst_version))
        else:
          self.feedback_fn("  migrating from hypervisor version %s to %s is"
                           " likely unsupported" % (src_version, dst_version))
          if self.ignore_hvversions:
            self.feedback_fn("  continuing anyway (told to ignore version"
                             " mismatch)")
          else:
            raise errors.OpExecError("Unsupported migration between hypervisor"
                                     " versions (%s to %s)" %
                                     (src_version, dst_version))

    self.feedback_fn("* checking disk consistency between source and target")
    for (idx, dev) in enumerate(self.cfg.GetInstanceDisks(self.instance.uuid)):
      if not CheckDiskConsistency(self.lu, self.instance, dev,
                                  self.target_node_uuid,
                                  False):
        raise errors.OpExecError("Disk %s is degraded or not fully"
                                 " synchronized on target node,"
                                 " aborting migration" % idx)

    if self.current_mem > self.tgt_free_mem:
      if not self.allow_runtime_changes:
        raise errors.OpExecError("Memory ballooning not allowed and not enough"
                                 " free memory to fit instance %s on target"
                                 " node %s (have %dMB, need %dMB)" %
                                 (self.instance.name,
                                  self.cfg.GetNodeName(self.target_node_uuid),
                                  self.tgt_free_mem, self.current_mem))
      self.feedback_fn("* setting instance memory to %s" % self.tgt_free_mem)
      rpcres = self.rpc.call_instance_balloon_memory(self.instance.primary_node,
                                                     self.instance,
                                                     self.tgt_free_mem)
      rpcres.Raise("Cannot modify instance runtime memory")

    # First get the migration information from the remote node
    result = self.rpc.call_migration_info(self.source_node_uuid, self.instance)
    msg = result.fail_msg
    if msg:
      log_err = ("Failed fetching source migration information from %s: %s" %
                 (self.cfg.GetNodeName(self.source_node_uuid), msg))
      logging.error(log_err)
      raise errors.OpExecError(log_err)

    self.migration_info = migration_info = result.payload

    disks = self.cfg.GetInstanceDisks(self.instance.uuid)

    self._CloseInstanceDisks(self.target_node_uuid)

    if utils.AnyDiskOfType(disks, constants.DTS_INT_MIRROR):
      # Then switch the disks to master/master mode
      self._GoStandalone()
      self._GoReconnect(True)
      self._WaitUntilSync()

    self._OpenInstanceDisks(self.source_node_uuid, False)
    self._OpenInstanceDisks(self.target_node_uuid, False)

    self.feedback_fn("* preparing %s to accept the instance" %
                     self.cfg.GetNodeName(self.target_node_uuid))
    result = self.rpc.call_accept_instance(self.target_node_uuid,
                                           self.instance,
                                           migration_info,
                                           self.nodes_ip[self.target_node_uuid])

    msg = result.fail_msg
    if msg:
      logging.error("Instance pre-migration failed, trying to revert"
                    " disk status: %s", msg)
      self.feedback_fn("Pre-migration failed, aborting")
      self._AbortMigration()
      self._RevertDiskStatus()
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
                               (self.instance.name, msg))

    self.feedback_fn("* migrating instance to %s" %
                     self.cfg.GetNodeName(self.target_node_uuid))
    cluster = self.cfg.GetClusterInfo()
    result = self.rpc.call_instance_migrate(
        self.source_node_uuid, cluster.cluster_name, self.instance,
        self.nodes_ip[self.target_node_uuid], self.live)
    msg = result.fail_msg
    if msg:
      logging.error("Instance migration failed, trying to revert"
                    " disk status: %s", msg)
      self.feedback_fn("Migration failed, aborting")
      self._AbortMigration()
      self._RevertDiskStatus()
      raise errors.OpExecError("Could not migrate instance %s: %s" %
                               (self.instance.name, msg))

    self.feedback_fn("* starting memory transfer")
    last_feedback = time.time()
    while True:
      result = self.rpc.call_instance_get_migration_status(
                 self.source_node_uuid, self.instance)
      msg = result.fail_msg
      ms = result.payload   # MigrationStatus instance
      if msg or (ms.status in constants.HV_MIGRATION_FAILED_STATUSES):
        logging.error("Instance migration failed, trying to revert"
                      " disk status: %s", msg)
        self.feedback_fn("Migration failed, aborting")
        self._AbortMigration()
        self._RevertDiskStatus()
        if not msg:
          msg = "hypervisor returned failure"
        raise errors.OpExecError("Could not migrate instance %s: %s" %
                                 (self.instance.name, msg))

      if result.payload.status != constants.HV_MIGRATION_ACTIVE:
        self.feedback_fn("* memory transfer complete")
        break

      if (utils.TimeoutExpired(last_feedback,
                               self._MIGRATION_FEEDBACK_INTERVAL) and
          ms.transferred_ram is not None):
        mem_progress = 100 * float(ms.transferred_ram) / float(ms.total_ram)
        self.feedback_fn("* memory transfer progress: %.2f %%" % mem_progress)
        last_feedback = time.time()

      time.sleep(self._MIGRATION_POLL_INTERVAL)

    result = self.rpc.call_instance_finalize_migration_src(
               self.source_node_uuid, self.instance, True, self.live)
    msg = result.fail_msg
    if msg:
      logging.error("Instance migration succeeded, but finalization failed"
                    " on the source node: %s", msg)
      raise errors.OpExecError("Could not finalize instance migration: %s" %
                               msg)

    self.cfg.SetInstancePrimaryNode(self.instance.uuid, self.target_node_uuid)
    self.instance = self.cfg.GetInstanceInfo(self.instance_uuid)
    disks = self.cfg.GetInstanceDisks(self.instance_uuid)

    result = self.rpc.call_instance_finalize_migration_dst(
               self.target_node_uuid, self.instance, migration_info, True)
    msg = result.fail_msg
    if msg:
      logging.error("Instance migration succeeded, but finalization failed"
                    " on the target node: %s", msg)
      raise errors.OpExecError("Could not finalize instance migration: %s" %
                               msg)

    self._CloseInstanceDisks(self.source_node_uuid)

    if utils.AnyDiskOfType(disks, constants.DTS_INT_MIRROR):
      self._WaitUntilSync()
      self._GoStandalone()
      self._GoReconnect(False)
      self._WaitUntilSync()
    elif utils.AnyDiskOfType(disks, constants.DTS_EXT_MIRROR):
      self._OpenInstanceDisks(self.target_node_uuid, True)

    # If the instance's disk template is `rbd' or `ext' and there was a
    # successful migration, unmap the device from the source node.
    unmap_types = (constants.DT_RBD, constants.DT_EXT)

    if utils.AnyDiskOfType(disks, unmap_types):
      unmap_disks = [d for d in disks if d.dev_type in unmap_types]
      disks = ExpandCheckDisks(unmap_disks, unmap_disks)
      self.feedback_fn("* unmapping instance's disks %s from %s" %
                       (utils.CommaJoin(d.name for d in unmap_disks),
                        self.cfg.GetNodeName(self.source_node_uuid)))
      for disk in disks:
        result = self.rpc.call_blockdev_shutdown(self.source_node_uuid,
                                                 (disk, self.instance))
        msg = result.fail_msg
        if msg:
          logging.error("Migration was successful, but couldn't unmap the"
                        " block device %s on source node %s: %s",
                        disk.iv_name,
                        self.cfg.GetNodeName(self.source_node_uuid), msg)
          logging.error("You need to unmap the device %s manually on %s",
                        disk.iv_name,
                        self.cfg.GetNodeName(self.source_node_uuid))

    self.feedback_fn("* done")

  def _ExecFailover(self):
    """Failover an instance.

    The failover is done by shutting it down on its present node and
    starting it on the secondary.

    """
    if self.instance.forthcoming:
      self.feedback_fn("Instance is forthcoming, just updating the"
                       "  configuration")
      self.cfg.SetInstancePrimaryNode(self.instance.uuid,
                                      self.target_node_uuid)
      return

    primary_node = self.cfg.GetNodeInfo(self.instance.primary_node)

    source_node_uuid = self.instance.primary_node

    if self.instance.disks_active:
      self.feedback_fn("* checking disk consistency between source and target")
      inst_disks = self.cfg.GetInstanceDisks(self.instance.uuid)
      for (idx, dev) in enumerate(inst_disks):
        # for drbd, these are drbd over lvm
        if not CheckDiskConsistency(self.lu, self.instance, dev,
                                    self.target_node_uuid, False):
          if primary_node.offline:
            self.feedback_fn("Node %s is offline, ignoring degraded disk %s on"
                             " target node %s" %
                             (primary_node.name, idx,
                              self.cfg.GetNodeName(self.target_node_uuid)))
          elif not self.ignore_consistency:
            raise errors.OpExecError("Disk %s is degraded on target node,"
                                     " aborting failover" % idx)
    else:
      self.feedback_fn("* not checking disk consistency as instance is not"
                       " running")

    self.feedback_fn("* shutting down instance on source node")
    logging.info("Shutting down instance %s on node %s",
                 self.instance.name, self.cfg.GetNodeName(source_node_uuid))

    result = self.rpc.call_instance_shutdown(source_node_uuid, self.instance,
                                             self.shutdown_timeout,
                                             self.lu.op.reason)
    msg = result.fail_msg
    if msg:
      if self.ignore_consistency or primary_node.offline:
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
                           " proceeding anyway; please make sure node"
                           " %s is down; error details: %s",
                           self.instance.name,
                           self.cfg.GetNodeName(source_node_uuid),
                           self.cfg.GetNodeName(source_node_uuid), msg)
      else:
        raise errors.OpExecError("Could not shutdown instance %s on"
                                 " node %s: %s" %
                                 (self.instance.name,
                                  self.cfg.GetNodeName(source_node_uuid), msg))

    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
      self._CloseInstanceDisks(source_node_uuid)

    self.feedback_fn("* deactivating the instance's disks on source node")
    if not ShutdownInstanceDisks(self.lu, self.instance, ignore_primary=True):
      raise errors.OpExecError("Can't shut down the instance's disks")

    self.cfg.SetInstancePrimaryNode(self.instance.uuid, self.target_node_uuid)
    self.instance = self.cfg.GetInstanceInfo(self.instance_uuid)

    # Only start the instance if it's marked as up
    if self.instance.admin_state == constants.ADMINST_UP:
      self.feedback_fn("* activating the instance's disks on target node %s" %
                       self.cfg.GetNodeName(self.target_node_uuid))
      logging.info("Starting instance %s on node %s", self.instance.name,
                   self.cfg.GetNodeName(self.target_node_uuid))

      disks_ok, _, _ = AssembleInstanceDisks(self.lu, self.instance,
                                             ignore_secondaries=True)
      if not disks_ok:
        ShutdownInstanceDisks(self.lu, self.instance)
        raise errors.OpExecError("Can't activate the instance's disks")

      self.feedback_fn("* starting the instance on the target node %s" %
                       self.cfg.GetNodeName(self.target_node_uuid))
      result = self.rpc.call_instance_start(self.target_node_uuid,
                                            (self.instance, None, None), False,
                                            self.lu.op.reason)
      msg = result.fail_msg
      if msg:
        ShutdownInstanceDisks(self.lu, self.instance)
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
                                 (self.instance.name,
                                  self.cfg.GetNodeName(self.target_node_uuid),
                                  msg))

  def Exec(self, feedback_fn):
    """Perform the migration.

    """
    self.feedback_fn = feedback_fn
    self.source_node_uuid = self.instance.primary_node

    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
    disks = self.cfg.GetInstanceDisks(self.instance.uuid)

    # TODO allow mixed disks
    if utils.AllDiskOfType(disks, constants.DTS_INT_MIRROR):
      secondary_nodes = self.cfg.GetInstanceSecondaryNodes(self.instance.uuid)
      self.target_node_uuid = secondary_nodes[0]
      # Otherwise self.target_node has been populated either
      # directly, or through an iallocator.

    self.all_node_uuids = [self.source_node_uuid, self.target_node_uuid]
    self.nodes_ip = dict((uuid, node.secondary_ip) for (uuid, node)
                         in self.cfg.GetMultiNodeInfo(self.all_node_uuids))

    if self.failover:
      feedback_fn("Failover instance %s" % self.instance.name)
      self._ExecFailover()
    else:
      feedback_fn("Migrating instance %s" % self.instance.name)

      if self.cleanup:
        return self._ExecCleanup()
      else:
        return self._ExecMigration()


text:
package VMOMI::HostBootDeviceInfo;
use parent 'VMOMI::DynamicData';

use strict;
use warnings;

our @class_ancestors = (
    'DynamicData',
);

our @class_members = (
    ['bootDevices', 'HostBootDevice', 1, 1],
    ['currentBootDeviceKey', undef, 0, 1],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;

redpajama_set_name: RedPajamaGithub


text:
//********************************************************************
//*
//* Warning: This file was generated by MDE4CPP Generator
//*
//********************************************************************

#ifndef STANDARDPROFILE_CALL_CALLIMPL_HPP
#define STANDARDPROFILE_CALL_CALLIMPL_HPP

#include <functional>

//Model includes
#include "../Call.hpp"
#include "uml/impl/StereotypeImpl.hpp"

class AnyObject;
typedef std::shared_ptr<AnyObject> Any;

namespace uml
{
	class Property;
	class Operation;
}

//*********************************
namespace StandardProfile
{
	class CallImpl : virtual public uml::StereotypeImpl, virtual public Call
	{
		public:
			CallImpl(const CallImpl & obj);
			virtual std::shared_ptr<ecore::EObject> copy() const;
			CallImpl& operator=(CallImpl const&);

		protected:
			friend class StandardProfileFactoryImpl;
			//constructor
			CallImpl();
			virtual std::shared_ptr<Call> getThisCallPtr();
			virtual void setThisCallPtr(std::weak_ptr<Call> thisCallPtr);

		public:

			//destructor
			virtual ~CallImpl();

			//*********************************
			// Operations
			//*********************************

			//*********************************
			// Attributes Getter Setter
			//*********************************
			virtual std::weak_ptr<uml::Usage> getBase_Usage() const ;
			virtual void setBase_Usage(std::weak_ptr<uml::Usage> _base_Usage);

			//*********************************
			// Union Getter
			//*********************************

		protected:
			virtual std::shared_ptr<uml::Class> getMetaClass() const;
			virtual void instantiate();
			virtual void destroy();

		public:
			//*********************************
			// Structural Feature Getter/Setter
			//*********************************
			//Get
			virtual Any get(std::shared_ptr<uml::Property> _property) const ;
			virtual Any get(std::string _qualifiedName) const ;
			virtual Any get(unsigned long _uID) const ;
			//Set
			virtual void set(std::shared_ptr<uml::Property> _property, Any value) ;
			virtual void set(std::string _qualifiedName, Any value) ;
			virtual void set(unsigned long _uID, Any value) ;
			//Unset
			virtual void unset(std::shared_ptr<uml::Property> _property) ;
			virtual void unset(std::string _qualifiedName) ;
			virtual void unset(unsigned long _uID) ;

			//*********************************
			// Operation Invocation
			//*********************************
			//Invoke
			virtual Any invoke(std::shared_ptr<uml::Operation> _operation, std::shared_ptr<Bag<Any>> _arguments) ;
			virtual Any invoke(std::string _qualifiedName, std::shared_ptr<Bag<Any>> _arguments) ;
			virtual Any invoke(unsigned long _uID, std::shared_ptr<Bag<Any>> _arguments) ;

		private:
			std::weak_ptr<Call> m_thisCallPtr;
			std::map<unsigned long,std::function<Any()>> m_getterMap;
			std::map<unsigned long,std::function<void(Any)>> m_setterMap;
			std::map<unsigned long,std::function<void()>> m_unsetterMap;
			std::map<unsigned long,std::function<Any(std::shared_ptr<Bag<Any>>)>> m_invocationMap;
	};
}
#endif /* end of include guard: STANDARDPROFILE_CALL_CALLIMPL_HPP */


text:
! Test Fortran 90 statements
! David Engster <dengste@eml.cc>

program main
  use testmodule
  implicit none

  integer :: eineVar, foo1, foo2, ppp
  double precision, parameter :: bar, foo3
  complex :: honk
  DOUBLE PRECISION, parameter :: foopi=3.141
  integer, dimension(:,:) :: anArray
  integer :: foo4=5,foo5,foo6=42
  ! Old style declarations
  INTEGER fooOldStyleDecl
  integer :: foo7(:,:),foo8(5)

  type :: aType
     integer :: one,two
     complex :: three,four
     real :: five
  end type aType

  type(aType) :: theType

  ! completion of subroutines
  call external!-1-
  !#1# ( "externalPolySub" "externalSub" )
  call my!-2-
  !#2# ( "myModSub" "mySub" )

  ! type-aware completion of functions
  bar = m!-3-
  !#3# ( "myFunc" "myModFunc" )

  ! completion of variables
  eineVar = foo!-4-
  !#4# ( "foo1" "foo2" "foo4" "foo5" "foo6" "foo7" "foo8" "fooOldStyleDecl" )

  bar = foo!-5-
  !#5# ( "foo3" "foopi" )

  ! completion of type members
  theType%!-6-
  !#6# ( "one" "two" "three" "four" "five" )
  honk = theType%!-7-
  !#7# ( "four" "three" )

contains

  subroutine mySub(aaa,bbb,ccc)
    integer,intent(in) :: aaa,bbb
    real,intent(out) :: ccc

    ccc = aaa*bbb
  end subroutine mySub

  function myFunc(ddd,eee)
    integer :: ddd
    real :: eee
    double precision myFunc

    myFunc = ddd*e!-8-
    !#8# ( "eee" "eineVar" )
  end function myFunc

  integer function anotherFunc(fff)
    integer,intent(in),dimension(:) :: fff
    anotherFunc = fff(1)
  end function anotherFunc

end program main


text:
package com.gs.fw.common.mithra.test;

import com.gs.fw.common.mithra.*;
import com.gs.fw.common.mithra.finder.Operation;
import com.gs.fw.common.mithra.test.domain.*;
import com.gs.fw.common.mithra.test.glew.BitemporalProductSynonym;
import com.gs.fw.common.mithra.test.glew.BitemporalProductSynonymFinder;
import com.gs.fw.common.mithra.util.DefaultInfinityTimestamp;
import com.gs.fw.common.mithra.util.MithraTimestamp;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public abstract class TestTimezoneConversion extends MithraTestAbstract
{
    private static SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    private static final int ONE_HOUR = 60*60*1000;

    public Class[] getRestrictedClassList()
    {
        return new Class[]
        {
            TimezoneTest.class,
            BitemporalProductSynonym.class,
            PkTimezoneTest.class
        };
    }

    public void checkBitemporalInfinity(TimeZone tz) throws Exception
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        final Timestamp timestamp = new Timestamp(timestampFormat.parse("2013-01-01 00:00:00.000").getTime());
        Operation bizOp = BitemporalProductSynonymFinder.businessDate().eq(timestamp);
        BitemporalProductSynonym one = BitemporalProductSynonymFinder.findOne(BitemporalProductSynonymFinder.instrumentId().eq(1).and(bizOp));
        assertNotNull(one);
        assertEquals(DefaultInfinityTimestamp.getDefaultInfinity().getTime(), one.getProcessingDateTo().getTime());
        one = BitemporalProductSynonymFinder.findOne(BitemporalProductSynonymFinder.instrumentId().eq(1).and(BitemporalProductSynonymFinder.processingDate().eq(timestamp).and(bizOp)));
        assertNotNull(one);
        assertEquals(DefaultInfinityTimestamp.getDefaultInfinity().getTime(), one.getProcessingDateTo().getTime());
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand<Object>()
        {
            @Override
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                BitemporalProductSynonym newSyn = new BitemporalProductSynonym(timestamp, DefaultInfinityTimestamp.getDefaultInfinity());
                newSyn.setInstrumentId(2);
                newSyn.setSynonymType("CUS");
                newSyn.setSynonymValue("DEF");
                newSyn.insert();
                return null;
            }
        });

        one = BitemporalProductSynonymFinder.findOne(BitemporalProductSynonymFinder.instrumentId().eq(2).and(bizOp));
        assertNotNull(one);
        assertEquals(DefaultInfinityTimestamp.getDefaultInfinity().getTime(), one.getProcessingDateTo().getTime());
        one = BitemporalProductSynonymFinder.findOne(BitemporalProductSynonymFinder.instrumentId().eq(2).and(BitemporalProductSynonymFinder.processingDate().eq(new Timestamp(System.currentTimeMillis() + 1000)).and(bizOp)));
        assertNotNull(one);
        assertEquals(DefaultInfinityTimestamp.getDefaultInfinity().getTime(), one.getProcessingDateTo().getTime());

    }

    public void checkFixInfinityPerformance(TimeZone tz)
    {
        Timestamp localInfinity = new Timestamp(DefaultInfinityTimestamp.getDefaultInfinity().getTime());
        MithraTimestamp.convertTimeToLocalTimeZone(tz, localInfinity);

        MithraTimestamp defaultInfinity = DefaultInfinityTimestamp.getDefaultInfinity();

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 300000000; i++)
        {
            Timestamp fixedInfinity = MithraTimestamp.zFixInfinity(localInfinity, tz, defaultInfinity);
            assertSame(fixedInfinity, defaultInfinity);
        }
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        // This test always fails : this is intended as a reminder to disable the test before committing
        fail("Performance test: took " + duration + " msecs");
    }

    public void checkRead(TimeZone tz)
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        TimezoneTest timezoneTest = TimezoneTestFinder.findOne(TimezoneTestFinder.timezoneTestId().eq(1));
        assertNotNull(timezoneTest);

        Timestamp insensitiveTimestamp = timezoneTest.getInsensitiveTimestamp();
        Timestamp databaseTimestamp = timezoneTest.getDatabaseTimestamp();
        Timestamp utcTimestamp = timezoneTest.getUtcTimestamp();

        assertTrue(databaseTimestamp.getTime() != utcTimestamp.getTime());

        TimezoneTest.assertDatesAndTimestamps(timezoneTest.getInsensitiveDate(), timezoneTest.getUtcDate(), timezoneTest.getDatabaseDate(), insensitiveTimestamp, utcTimestamp, databaseTimestamp, tz);

    }

    public void checkReadAggregate(TimeZone tz)
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        AggregateList list = new AggregateList(TimezoneTestFinder.timezoneTestId().eq(1));
        list.addAggregateAttribute("insensitiveDate", TimezoneTestFinder.insensitiveDate().max());
        list.addAggregateAttribute("databaseDate", TimezoneTestFinder.databaseDate().max());
        list.addAggregateAttribute("utcDate", TimezoneTestFinder.utcDate().max());
        list.addAggregateAttribute("insensitiveTimestamp", TimezoneTestFinder.insensitiveTimestamp().max());
        list.addAggregateAttribute("databaseTimestamp", TimezoneTestFinder.databaseTimestamp().max());
        list.addAggregateAttribute("utcTimestamp", TimezoneTestFinder.utcTimestamp().max());

        assertEquals(1, list.size());

        AggregateData data = list.get(0);

        Date insensitiveDate = data.getAttributeAsDate("insensitiveDate");
        Date databaseDate = data.getAttributeAsDate("databaseDate");
        Date utcDate = data.getAttributeAsDate("utcDate");
        Timestamp insensitiveTimestamp = data.getAttributeAsTimestamp("insensitiveTimestamp");
        Timestamp databaseTimestamp = data.getAttributeAsTimestamp("databaseTimestamp");
        Timestamp utcTimestamp = data.getAttributeAsTimestamp("utcTimestamp");

        assertTrue(databaseTimestamp.getTime() != utcTimestamp.getTime());

        TimezoneTest.assertDatesAndTimestamps(insensitiveDate, utcDate, databaseDate, insensitiveTimestamp, utcTimestamp, databaseTimestamp, tz);
    }

    // todo: figure out why the tests failed on 2006-10-28 14:23 NYK time
    public void xtestDaylightSavingsSwitch() throws ParseException
    {
        Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("America/New_York"));
        c.set(Calendar.YEAR, 2006);
        c.set(Calendar.MONTH, 9);
        c.set(Calendar.DAY_OF_MONTH, 28);
        c.set(Calendar.HOUR_OF_DAY, 14);
        c.set(Calendar.MINUTE, 23);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        long time = c.getTimeInMillis();

        Timestamp toTokyo = new Timestamp(time);
        MithraTimestamp.convertTimeToLocalTimeZone(TimeZone.getTimeZone("Asia/Tokyo"), toTokyo);
    }

    public void checkQuery(TimeZone tz) throws ParseException
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        TimezoneTest timezoneTest = TimezoneTestFinder.findOne(
                TimezoneTestFinder.insensitiveTimestamp().eq(new Timestamp(timestampFormat.parse("2005-10-01 10:12:30.150").getTime())));
        assertNotNull(timezoneTest);
        assertEquals(1, timezoneTest.getTimezoneTestId());

        timezoneTest = TimezoneTestFinder.findOne(
                TimezoneTestFinder.databaseTimestamp().eq(timezoneTest.getDatabaseTimestamp()));
        assertNotNull(timezoneTest);
        assertEquals(1, timezoneTest.getTimezoneTestId());

        timezoneTest = TimezoneTestFinder.findOne(
                TimezoneTestFinder.utcTimestamp().eq(timezoneTest.getUtcTimestamp()));
        assertNotNull(timezoneTest);
        assertEquals(1, timezoneTest.getTimezoneTestId());

        timezoneTest = TimezoneTestFinder.findOne(
                TimezoneTestFinder.utcTimestamp().eq(timezoneTest.getUtcTimestamp()).and(
                        TimezoneTestFinder.databaseTimestamp().eq(timezoneTest.getDatabaseTimestamp())).and(
                        TimezoneTestFinder.insensitiveTimestamp().eq(new Timestamp(timestampFormat.parse("2005-10-01 10:12:30.150").getTime())
                        )));
        assertNotNull(timezoneTest);
        assertEquals(1, timezoneTest.getTimezoneTestId());
    }

    public void checkUpdate(TimeZone tz) throws ParseException
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        TimezoneTest timezoneTest = TimezoneTestFinder.findOne(TimezoneTestFinder.timezoneTestId().eq(1));
        timezoneTest.setDatabaseTimestamp(nextHour(timezoneTest.getDatabaseTimestamp()));
        timezoneTest.setUtcTimestamp(nextHour(timezoneTest.getUtcTimestamp()));

        checkQuery(tz);

        timezoneTest.setInsensitiveTimestamp(nextHour(timezoneTest.getInsensitiveTimestamp()));

        timezoneTest = TimezoneTestFinder.findOne(
                TimezoneTestFinder.insensitiveTimestamp().eq(timezoneTest.getInsensitiveTimestamp()));
        assertNotNull(timezoneTest);
        assertEquals(1, timezoneTest.getTimezoneTestId());
    }

    private Timestamp nextHour(Timestamp timestamp)
    {
        return new Timestamp(timestamp.getTime()+ONE_HOUR);
    }

    public void checkInsert(TimeZone tz) throws ParseException
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        TimezoneTest timezoneTest = new TimezoneTest();
        timezoneTest.setTimezoneTestId(1000);
        timezoneTest.setInsensitiveTimestamp(new Timestamp(timestampFormat.parse("2005-10-01 10:12:30.150").getTime()));
        Timestamp databaseTimestamp = new Timestamp(System.currentTimeMillis());
        Timestamp utcTimestamp = new Timestamp(databaseTimestamp.getTime()+1000);
        timezoneTest.setDatabaseTimestamp(databaseTimestamp);
        timezoneTest.setUtcTimestamp(utcTimestamp);
        timezoneTest.insert();

        timezoneTest = TimezoneTestFinder.findOne(
                TimezoneTestFinder.utcTimestamp().eq(timezoneTest.getUtcTimestamp()).and(
                        TimezoneTestFinder.databaseTimestamp().eq(timezoneTest.getDatabaseTimestamp())).and(
                        TimezoneTestFinder.insensitiveTimestamp().eq(new Timestamp(timestampFormat.parse("2005-10-01 10:12:30.150").getTime())
                        )));
        assertNotNull(timezoneTest);
        assertEquals(databaseTimestamp.getTime(), timezoneTest.getDatabaseTimestamp().getTime());
        assertEquals(utcTimestamp.getTime(), timezoneTest.getUtcTimestamp().getTime());
        assertEquals(1000, timezoneTest.getTimezoneTestId());
    }

    public void checkUpdateWithPk(TimeZone tz) throws ParseException
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        PkTimezoneTest pkTimezoneTest = PkTimezoneTestFinder.findOne(PkTimezoneTestFinder.value().eq(1));
        assertNotNull(pkTimezoneTest);
        pkTimezoneTest.setValue(1000);

        pkTimezoneTest = PkTimezoneTestFinder.findOneBypassCache(PkTimezoneTestFinder.value().eq(1000));
        assertNotNull(pkTimezoneTest);
    }

    public void checkDelete(TimeZone tz) throws ParseException
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        PkTimezoneTest pkTimezoneTest = PkTimezoneTestFinder.findOne(PkTimezoneTestFinder.value().eq(1));
        assertNotNull(pkTimezoneTest);
        pkTimezoneTest.delete();

        pkTimezoneTest = PkTimezoneTestFinder.findOneBypassCache(PkTimezoneTestFinder.value().eq(1));
        assertNull(pkTimezoneTest);
    }

    public void checkRefresh(TimeZone tz) throws ParseException
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        PkTimezoneTest pkTimezoneTest = PkTimezoneTestFinder.findOne(PkTimezoneTestFinder.value().eq(1));
        assertNotNull(pkTimezoneTest);
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        pkTimezoneTest.setValue(1000);
        tx.commit();
        pkTimezoneTest = PkTimezoneTestFinder.findOneBypassCache(PkTimezoneTestFinder.value().eq(1000));
        assertNotNull(pkTimezoneTest);
    }

    public void checkBatchInsert(TimeZone tz) throws ParseException
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        long startTime = System.currentTimeMillis();
        for(int i=0;i<10;i++)
        {
            TimezoneTest timezoneTest = new TimezoneTest();
            timezoneTest.setTimezoneTestId(1000+i);
            timezoneTest.setInsensitiveTimestamp(new Timestamp(timestampFormat.parse("2005-10-01 10:12:30.150").getTime()));
            Timestamp databaseTimestamp = new Timestamp(startTime + i*100);
            Timestamp utcTimestamp = new Timestamp(databaseTimestamp.getTime()+1000);
            timezoneTest.setDatabaseTimestamp(databaseTimestamp);
            timezoneTest.setUtcTimestamp(utcTimestamp);
            timezoneTest.insert();
        }
        tx.commit();

        for(int i=0;i<10;i++)
        {
            Timestamp databaseTimestamp = new Timestamp(startTime + i*100);
            Timestamp utcTimestamp = new Timestamp(databaseTimestamp.getTime()+1000);
            TimezoneTest timezoneTest = TimezoneTestFinder.findOne(
                    TimezoneTestFinder.utcTimestamp().eq(utcTimestamp).and(
                            TimezoneTestFinder.databaseTimestamp().eq(databaseTimestamp)).and(
                            TimezoneTestFinder.insensitiveTimestamp().eq(new Timestamp(timestampFormat.parse("2005-10-01 10:12:30.150").getTime())
                            )));
            assertNotNull(timezoneTest);
            assertEquals(databaseTimestamp.getTime(), timezoneTest.getDatabaseTimestamp().getTime());
            assertEquals(utcTimestamp.getTime(), timezoneTest.getUtcTimestamp().getTime());
            assertEquals(1000+i, timezoneTest.getTimezoneTestId());
        }
    }

    public void checkBatchUpdateWithPk(TimeZone tz) throws ParseException
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PkTimezoneTestList list = new PkTimezoneTestList(PkTimezoneTestFinder.value().eq(123));
        int originalSize = list.size();
        assertTrue(originalSize > 1);
        for(int i=0;i<list.size();i++)
        {
            list.getPkTimezoneTestAt(i).setValue(1000);
        }
        tx.commit();
        PkTimezoneTestList newList = new PkTimezoneTestList(PkTimezoneTestFinder.value().eq(1000));
        assertEquals(originalSize, newList.size());
    }

    public void checkBatchDelete(TimeZone tz) throws ParseException
    {
        ConnectionManagerForTests.getInstance().setDatabaseTimeZone(tz);
        PkTimezoneTestList list = new PkTimezoneTestList(PkTimezoneTestFinder.value().eq(123));
        assertTrue(list.size() > 1);
        list.deleteAll();

        list = new PkTimezoneTestList(PkTimezoneTestFinder.value().eq(123));
        assertEquals(0, list.size());
    }

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;

// ReSharper disable InconsistentNaming

namespace GlmSharp
{
    /// <summary>
    /// Static class that contains static glm functions
    /// </summary>
    public static partial class glm
    {

        /// <summary>
        /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy)
        /// </summary>
        public static swizzle_dvec3 swizzle(dvec3 v) => v.swizzle;

        /// <summary>
        /// Returns an array with all values
        /// </summary>
        public static double[] Values(dvec3 v) => v.Values;

        /// <summary>
        /// Returns an enumerator that iterates through all components.
        /// </summary>
        public static IEnumerator<double> GetEnumerator(dvec3 v) => v.GetEnumerator();

        /// <summary>
        /// Returns a string representation of this vector using ', ' as a seperator.
        /// </summary>
        public static string ToString(dvec3 v) => v.ToString();

        /// <summary>
        /// Returns a string representation of this vector using a provided seperator.
        /// </summary>
        public static string ToString(dvec3 v, string sep) => v.ToString(sep);

        /// <summary>
        /// Returns a string representation of this vector using a provided seperator and a format provider for each component.
        /// </summary>
        public static string ToString(dvec3 v, string sep, IFormatProvider provider) => v.ToString(sep, provider);

        /// <summary>
        /// Returns a string representation of this vector using a provided seperator and a format for each component.
        /// </summary>
        public static string ToString(dvec3 v, string sep, string format) => v.ToString(sep, format);

        /// <summary>
        /// Returns a string representation of this vector using a provided seperator and a format and format provider for each component.
        /// </summary>
        public static string ToString(dvec3 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider);

        /// <summary>
        /// Returns the number of components (3).
        /// </summary>
        public static int Count(dvec3 v) => v.Count;

        /// <summary>
        /// Returns true iff this equals rhs component-wise.
        /// </summary>
        public static bool Equals(dvec3 v, dvec3 rhs) => v.Equals(rhs);

        /// <summary>
        /// Returns true iff this equals rhs type- and component-wise.
        /// </summary>
        public static bool Equals(dvec3 v, object obj) => v.Equals(obj);

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        public static int GetHashCode(dvec3 v) => v.GetHashCode();

        /// <summary>
        /// Returns true iff distance between lhs and rhs is less than or equal to epsilon
        /// </summary>
        public static bool ApproxEqual(dvec3 lhs, dvec3 rhs, double eps = 0.1d) => dvec3.ApproxEqual(lhs, rhs, eps);

        /// <summary>
        /// Returns a bvec3 from component-wise application of Equal (lhs == rhs).
        /// </summary>
        public static bvec3 Equal(dvec3 lhs, dvec3 rhs) => dvec3.Equal(lhs, rhs);

        /// <summary>
        /// Returns a bvec3 from component-wise application of Equal (lhs == rhs).
        /// </summary>
        public static bool Equal(double lhs, double rhs) => lhs == rhs;

        /// <summary>
        /// Returns a bvec3 from component-wise application of NotEqual (lhs != rhs).
        /// </summary>
        public static bvec3 NotEqual(dvec3 lhs, dvec3 rhs) => dvec3.NotEqual(lhs, rhs);

        /// <summary>
        /// Returns a bvec3 from component-wise application of NotEqual (lhs != rhs).
        /// </summary>
        public static bool NotEqual(double lhs, double rhs) => lhs != rhs;

        /// <summary>
        /// Returns a bvec3 from component-wise application of GreaterThan (lhs > rhs).
        /// </summary>
        public static bvec3 GreaterThan(dvec3 lhs, dvec3 rhs) => dvec3.GreaterThan(lhs, rhs);

        /// <summary>
        /// Returns a bvec3 from component-wise application of GreaterThan (lhs > rhs).
        /// </summary>
        public static bool GreaterThan(double lhs, double rhs) => lhs > rhs;

        /// <summary>
        /// Returns a bvec3 from component-wise application of GreaterThanEqual (lhs >= rhs).
        /// </summary>
        public static bvec3 GreaterThanEqual(dvec3 lhs, dvec3 rhs) => dvec3.GreaterThanEqual(lhs, rhs);

        /// <summary>
        /// Returns a bvec3 from component-wise application of GreaterThanEqual (lhs >= rhs).
        /// </summary>
        public static bool GreaterThanEqual(double lhs, double rhs) => lhs >= rhs;

        /// <summary>
        /// Returns a bvec3 from component-wise application of LesserThan (lhs < rhs).
        /// </summary>
        public static bvec3 LesserThan(dvec3 lhs, dvec3 rhs) => dvec3.LesserThan(lhs, rhs);

        /// <summary>
        /// Returns a bvec3 from component-wise application of LesserThan (lhs < rhs).
        /// </summary>
        public static bool LesserThan(double lhs, double rhs) => lhs < rhs;

        /// <summary>
        /// Returns a bvec3 from component-wise application of LesserThanEqual (lhs <= rhs).
        /// </summary>
        public static bvec3 LesserThanEqual(dvec3 lhs, dvec3 rhs) => dvec3.LesserThanEqual(lhs, rhs);

        /// <summary>
        /// Returns a bvec3 from component-wise application of LesserThanEqual (lhs <= rhs).
        /// </summary>
        public static bool LesserThanEqual(double lhs, double rhs) => lhs <= rhs;

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsInfinity (double.IsInfinity(v)).
        /// </summary>
        public static bvec3 IsInfinity(dvec3 v) => dvec3.IsInfinity(v);

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsInfinity (double.IsInfinity(v)).
        /// </summary>
        public static bool IsInfinity(double v) => double.IsInfinity(v);

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsFinite (!double.IsNaN(v) && !double.IsInfinity(v)).
        /// </summary>
        public static bvec3 IsFinite(dvec3 v) => dvec3.IsFinite(v);

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsFinite (!double.IsNaN(v) && !double.IsInfinity(v)).
        /// </summary>
        public static bool IsFinite(double v) => !double.IsNaN(v) && !double.IsInfinity(v);

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsNaN (double.IsNaN(v)).
        /// </summary>
        public static bvec3 IsNaN(dvec3 v) => dvec3.IsNaN(v);

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsNaN (double.IsNaN(v)).
        /// </summary>
        public static bool IsNaN(double v) => double.IsNaN(v);

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsNegativeInfinity (double.IsNegativeInfinity(v)).
        /// </summary>
        public static bvec3 IsNegativeInfinity(dvec3 v) => dvec3.IsNegativeInfinity(v);

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsNegativeInfinity (double.IsNegativeInfinity(v)).
        /// </summary>
        public static bool IsNegativeInfinity(double v) => double.IsNegativeInfinity(v);

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsPositiveInfinity (double.IsPositiveInfinity(v)).
        /// </summary>
        public static bvec3 IsPositiveInfinity(dvec3 v) => dvec3.IsPositiveInfinity(v);

        /// <summary>
        /// Returns a bvec3 from component-wise application of IsPositiveInfinity (double.IsPositiveInfinity(v)).
        /// </summary>
        public static bool IsPositiveInfinity(double v) => double.IsPositiveInfinity(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Abs (Math.Abs(v)).
        /// </summary>
        public static dvec3 Abs(dvec3 v) => dvec3.Abs(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Abs (Math.Abs(v)).
        /// </summary>
        public static double Abs(double v) => Math.Abs(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v).
        /// </summary>
        public static dvec3 HermiteInterpolationOrder3(dvec3 v) => dvec3.HermiteInterpolationOrder3(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v).
        /// </summary>
        public static double HermiteInterpolationOrder3(double v) => (3 - 2 * v) * v * v;

        /// <summary>
        /// Returns a dvec3 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v).
        /// </summary>
        public static dvec3 HermiteInterpolationOrder5(dvec3 v) => dvec3.HermiteInterpolationOrder5(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v).
        /// </summary>
        public static double HermiteInterpolationOrder5(double v) => ((6 * v - 15) * v + 10) * v * v * v;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sqr (v * v).
        /// </summary>
        public static dvec3 Sqr(dvec3 v) => dvec3.Sqr(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sqr (v * v).
        /// </summary>
        public static double Sqr(double v) => v * v;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Pow2 (v * v).
        /// </summary>
        public static dvec3 Pow2(dvec3 v) => dvec3.Pow2(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Pow2 (v * v).
        /// </summary>
        public static double Pow2(double v) => v * v;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Pow3 (v * v * v).
        /// </summary>
        public static dvec3 Pow3(dvec3 v) => dvec3.Pow3(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Pow3 (v * v * v).
        /// </summary>
        public static double Pow3(double v) => v * v * v;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Step (v >= 0.0 ? 1.0 : 0.0).
        /// </summary>
        public static dvec3 Step(dvec3 v) => dvec3.Step(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Step (v >= 0.0 ? 1.0 : 0.0).
        /// </summary>
        public static double Step(double v) => v >= 0.0 ? 1.0 : 0.0;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sqrt ((double)Math.Sqrt((double)v)).
        /// </summary>
        public static dvec3 Sqrt(dvec3 v) => dvec3.Sqrt(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sqrt ((double)Math.Sqrt((double)v)).
        /// </summary>
        public static double Sqrt(double v) => (double)Math.Sqrt((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of InverseSqrt ((double)(1.0 / Math.Sqrt((double)v))).
        /// </summary>
        public static dvec3 InverseSqrt(dvec3 v) => dvec3.InverseSqrt(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of InverseSqrt ((double)(1.0 / Math.Sqrt((double)v))).
        /// </summary>
        public static double InverseSqrt(double v) => (double)(1.0 / Math.Sqrt((double)v));

        /// <summary>
        /// Returns a ivec3 from component-wise application of Sign (Math.Sign(v)).
        /// </summary>
        public static ivec3 Sign(dvec3 v) => dvec3.Sign(v);

        /// <summary>
        /// Returns a ivec3 from component-wise application of Sign (Math.Sign(v)).
        /// </summary>
        public static int Sign(double v) => Math.Sign(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Max (Math.Max(lhs, rhs)).
        /// </summary>
        public static dvec3 Max(dvec3 lhs, dvec3 rhs) => dvec3.Max(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Max (Math.Max(lhs, rhs)).
        /// </summary>
        public static double Max(double lhs, double rhs) => Math.Max(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Min (Math.Min(lhs, rhs)).
        /// </summary>
        public static dvec3 Min(dvec3 lhs, dvec3 rhs) => dvec3.Min(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Min (Math.Min(lhs, rhs)).
        /// </summary>
        public static double Min(double lhs, double rhs) => Math.Min(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Pow ((double)Math.Pow((double)lhs, (double)rhs)).
        /// </summary>
        public static dvec3 Pow(dvec3 lhs, dvec3 rhs) => dvec3.Pow(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Pow ((double)Math.Pow((double)lhs, (double)rhs)).
        /// </summary>
        public static double Pow(double lhs, double rhs) => (double)Math.Pow((double)lhs, (double)rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Log ((double)Math.Log((double)lhs, (double)rhs)).
        /// </summary>
        public static dvec3 Log(dvec3 lhs, dvec3 rhs) => dvec3.Log(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Log ((double)Math.Log((double)lhs, (double)rhs)).
        /// </summary>
        public static double Log(double lhs, double rhs) => (double)Math.Log((double)lhs, (double)rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)).
        /// </summary>
        public static dvec3 Clamp(dvec3 v, dvec3 min, dvec3 max) => dvec3.Clamp(v, min, max);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)).
        /// </summary>
        public static double Clamp(double v, double min, double max) => Math.Min(Math.Max(v, min), max);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Mix (min * (1-a) + max * a).
        /// </summary>
        public static dvec3 Mix(dvec3 min, dvec3 max, dvec3 a) => dvec3.Mix(min, max, a);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Mix (min * (1-a) + max * a).
        /// </summary>
        public static double Mix(double min, double max, double a) => min * (1-a) + max * a;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Lerp (min * (1-a) + max * a).
        /// </summary>
        public static dvec3 Lerp(dvec3 min, dvec3 max, dvec3 a) => dvec3.Lerp(min, max, a);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Lerp (min * (1-a) + max * a).
        /// </summary>
        public static double Lerp(double min, double max, double a) => min * (1-a) + max * a;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()).
        /// </summary>
        public static dvec3 Smoothstep(dvec3 edge0, dvec3 edge1, dvec3 v) => dvec3.Smoothstep(edge0, edge1, v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()).
        /// </summary>
        public static double Smoothstep(double edge0, double edge1, double v) => ((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3();

        /// <summary>
        /// Returns a dvec3 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()).
        /// </summary>
        public static dvec3 Smootherstep(dvec3 edge0, dvec3 edge1, dvec3 v) => dvec3.Smootherstep(edge0, edge1, v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()).
        /// </summary>
        public static double Smootherstep(double edge0, double edge1, double v) => ((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5();

        /// <summary>
        /// Returns a dvec3 from component-wise application of Fma (a * b + c).
        /// </summary>
        public static dvec3 Fma(dvec3 a, dvec3 b, dvec3 c) => dvec3.Fma(a, b, c);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Fma (a * b + c).
        /// </summary>
        public static double Fma(double a, double b, double c) => a * b + c;

        /// <summary>
        /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
        /// </summary>
        public static dmat2x3 OuterProduct(dvec3 c, dvec2 r) => dvec3.OuterProduct(c, r);

        /// <summary>
        /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
        /// </summary>
        public static dmat3 OuterProduct(dvec3 c, dvec3 r) => dvec3.OuterProduct(c, r);

        /// <summary>
        /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
        /// </summary>
        public static dmat4x3 OuterProduct(dvec3 c, dvec4 r) => dvec3.OuterProduct(c, r);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Add (lhs + rhs).
        /// </summary>
        public static dvec3 Add(dvec3 lhs, dvec3 rhs) => dvec3.Add(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Add (lhs + rhs).
        /// </summary>
        public static double Add(double lhs, double rhs) => lhs + rhs;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sub (lhs - rhs).
        /// </summary>
        public static dvec3 Sub(dvec3 lhs, dvec3 rhs) => dvec3.Sub(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sub (lhs - rhs).
        /// </summary>
        public static double Sub(double lhs, double rhs) => lhs - rhs;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Mul (lhs * rhs).
        /// </summary>
        public static dvec3 Mul(dvec3 lhs, dvec3 rhs) => dvec3.Mul(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Mul (lhs * rhs).
        /// </summary>
        public static double Mul(double lhs, double rhs) => lhs * rhs;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Div (lhs / rhs).
        /// </summary>
        public static dvec3 Div(dvec3 lhs, dvec3 rhs) => dvec3.Div(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Div (lhs / rhs).
        /// </summary>
        public static double Div(double lhs, double rhs) => lhs / rhs;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Modulo (lhs % rhs).
        /// </summary>
        public static dvec3 Modulo(dvec3 lhs, dvec3 rhs) => dvec3.Modulo(lhs, rhs);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Modulo (lhs % rhs).
        /// </summary>
        public static double Modulo(double lhs, double rhs) => lhs % rhs;

        /// <summary>
        /// Returns a dvec3 from component-wise application of Degrees (Radians-To-Degrees Conversion).
        /// </summary>
        public static dvec3 Degrees(dvec3 v) => dvec3.Degrees(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Degrees (Radians-To-Degrees Conversion).
        /// </summary>
        public static double Degrees(double v) => (double)(v * 57.295779513082320876798154814105170332405472466564321d);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Radians (Degrees-To-Radians Conversion).
        /// </summary>
        public static dvec3 Radians(dvec3 v) => dvec3.Radians(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Radians (Degrees-To-Radians Conversion).
        /// </summary>
        public static double Radians(double v) => (double)(v * 0.0174532925199432957692369076848861271344287188854172d);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Acos ((double)Math.Acos((double)v)).
        /// </summary>
        public static dvec3 Acos(dvec3 v) => dvec3.Acos(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Acos ((double)Math.Acos((double)v)).
        /// </summary>
        public static double Acos(double v) => (double)Math.Acos((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Asin ((double)Math.Asin((double)v)).
        /// </summary>
        public static dvec3 Asin(dvec3 v) => dvec3.Asin(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Asin ((double)Math.Asin((double)v)).
        /// </summary>
        public static double Asin(double v) => (double)Math.Asin((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Atan ((double)Math.Atan((double)v)).
        /// </summary>
        public static dvec3 Atan(dvec3 v) => dvec3.Atan(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Atan ((double)Math.Atan((double)v)).
        /// </summary>
        public static double Atan(double v) => (double)Math.Atan((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Cos ((double)Math.Cos((double)v)).
        /// </summary>
        public static dvec3 Cos(dvec3 v) => dvec3.Cos(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Cos ((double)Math.Cos((double)v)).
        /// </summary>
        public static double Cos(double v) => (double)Math.Cos((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Cosh ((double)Math.Cosh((double)v)).
        /// </summary>
        public static dvec3 Cosh(dvec3 v) => dvec3.Cosh(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Cosh ((double)Math.Cosh((double)v)).
        /// </summary>
        public static double Cosh(double v) => (double)Math.Cosh((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Exp ((double)Math.Exp((double)v)).
        /// </summary>
        public static dvec3 Exp(dvec3 v) => dvec3.Exp(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Exp ((double)Math.Exp((double)v)).
        /// </summary>
        public static double Exp(double v) => (double)Math.Exp((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Log ((double)Math.Log((double)v)).
        /// </summary>
        public static dvec3 Log(dvec3 v) => dvec3.Log(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Log ((double)Math.Log((double)v)).
        /// </summary>
        public static double Log(double v) => (double)Math.Log((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Log2 ((double)Math.Log((double)v, 2)).
        /// </summary>
        public static dvec3 Log2(dvec3 v) => dvec3.Log2(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Log2 ((double)Math.Log((double)v, 2)).
        /// </summary>
        public static double Log2(double v) => (double)Math.Log((double)v, 2);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Log10 ((double)Math.Log10((double)v)).
        /// </summary>
        public static dvec3 Log10(dvec3 v) => dvec3.Log10(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Log10 ((double)Math.Log10((double)v)).
        /// </summary>
        public static double Log10(double v) => (double)Math.Log10((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Floor ((double)Math.Floor(v)).
        /// </summary>
        public static dvec3 Floor(dvec3 v) => dvec3.Floor(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Floor ((double)Math.Floor(v)).
        /// </summary>
        public static double Floor(double v) => (double)Math.Floor(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Ceiling ((double)Math.Ceiling(v)).
        /// </summary>
        public static dvec3 Ceiling(dvec3 v) => dvec3.Ceiling(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Ceiling ((double)Math.Ceiling(v)).
        /// </summary>
        public static double Ceiling(double v) => (double)Math.Ceiling(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Round ((double)Math.Round(v)).
        /// </summary>
        public static dvec3 Round(dvec3 v) => dvec3.Round(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Round ((double)Math.Round(v)).
        /// </summary>
        public static double Round(double v) => (double)Math.Round(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sin ((double)Math.Sin((double)v)).
        /// </summary>
        public static dvec3 Sin(dvec3 v) => dvec3.Sin(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sin ((double)Math.Sin((double)v)).
        /// </summary>
        public static double Sin(double v) => (double)Math.Sin((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sinh ((double)Math.Sinh((double)v)).
        /// </summary>
        public static dvec3 Sinh(dvec3 v) => dvec3.Sinh(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Sinh ((double)Math.Sinh((double)v)).
        /// </summary>
        public static double Sinh(double v) => (double)Math.Sinh((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Tan ((double)Math.Tan((double)v)).
        /// </summary>
        public static dvec3 Tan(dvec3 v) => dvec3.Tan(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Tan ((double)Math.Tan((double)v)).
        /// </summary>
        public static double Tan(double v) => (double)Math.Tan((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Tanh ((double)Math.Tanh((double)v)).
        /// </summary>
        public static dvec3 Tanh(dvec3 v) => dvec3.Tanh(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Tanh ((double)Math.Tanh((double)v)).
        /// </summary>
        public static double Tanh(double v) => (double)Math.Tanh((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Truncate ((double)Math.Truncate((double)v)).
        /// </summary>
        public static dvec3 Truncate(dvec3 v) => dvec3.Truncate(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Truncate ((double)Math.Truncate((double)v)).
        /// </summary>
        public static double Truncate(double v) => (double)Math.Truncate((double)v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Fract ((double)(v - Math.Floor(v))).
        /// </summary>
        public static dvec3 Fract(dvec3 v) => dvec3.Fract(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Fract ((double)(v - Math.Floor(v))).
        /// </summary>
        public static double Fract(double v) => (double)(v - Math.Floor(v));

        /// <summary>
        /// Returns a dvec3 from component-wise application of Trunc ((long)(v)).
        /// </summary>
        public static dvec3 Trunc(dvec3 v) => dvec3.Trunc(v);

        /// <summary>
        /// Returns a dvec3 from component-wise application of Trunc ((long)(v)).
        /// </summary>
        public static double Trunc(double v) => (long)(v);

        /// <summary>
        /// Returns the minimal component of this vector.
        /// </summary>
        public static double MinElement(dvec3 v) => v.MinElement;

        /// <summary>
        /// Returns the maximal component of this vector.
        /// </summary>
        public static double MaxElement(dvec3 v) => v.MaxElement;

        /// <summary>
        /// Returns the euclidean length of this vector.
        /// </summary>
        public static double Length(dvec3 v) => v.Length;

        /// <summary>
        /// Returns the squared euclidean length of this vector.
        /// </summary>
        public static double LengthSqr(dvec3 v) => v.LengthSqr;

        /// <summary>
        /// Returns the sum of all components.
        /// </summary>
        public static double Sum(dvec3 v) => v.Sum;

        /// <summary>
        /// Returns the euclidean norm of this vector.
        /// </summary>
        public static double Norm(dvec3 v) => v.Norm;

        /// <summary>
        /// Returns the one-norm of this vector.
        /// </summary>
        public static double Norm1(dvec3 v) => v.Norm1;

        /// <summary>
        /// Returns the two-norm (euclidean length) of this vector.
        /// </summary>
        public static double Norm2(dvec3 v) => v.Norm2;

        /// <summary>
        /// Returns the max-norm of this vector.
        /// </summary>
        public static double NormMax(dvec3 v) => v.NormMax;

        /// <summary>
        /// Returns the p-norm of this vector.
        /// </summary>
        public static double NormP(dvec3 v, double p) => v.NormP(p);

        /// <summary>
        /// Returns a copy of this vector with length one (undefined if this has zero length).
        /// </summary>
        public static dvec3 Normalized(dvec3 v) => v.Normalized;

        /// <summary>
        /// Returns a copy of this vector with length one (returns zero if length is zero).
        /// </summary>
        public static dvec3 NormalizedSafe(dvec3 v) => v.NormalizedSafe;

        /// <summary>
        /// Returns the inner product (dot product, scalar product) of the two vectors.
        /// </summary>
        public static double Dot(dvec3 lhs, dvec3 rhs) => dvec3.Dot(lhs, rhs);

        /// <summary>
        /// Returns the euclidean distance between the two vectors.
        /// </summary>
        public static double Distance(dvec3 lhs, dvec3 rhs) => dvec3.Distance(lhs, rhs);

        /// <summary>
        /// Returns the squared euclidean distance between the two vectors.
        /// </summary>
        public static double DistanceSqr(dvec3 lhs, dvec3 rhs) => dvec3.DistanceSqr(lhs, rhs);

        /// <summary>
        /// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result).
        /// </summary>
        public static dvec3 Reflect(dvec3 I, dvec3 N) => dvec3.Reflect(I, N);

        /// <summary>
        /// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result).
        /// </summary>
        public static dvec3 Refract(dvec3 I, dvec3 N, double eta) => dvec3.Refract(I, N, eta);

        /// <summary>
        /// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N).
        /// </summary>
        public static dvec3 FaceForward(dvec3 N, dvec3 I, dvec3 Nref) => dvec3.FaceForward(N, I, Nref);

        /// <summary>
        /// Returns the outer product (cross product, vector product) of the two vectors.
        /// </summary>
        public static dvec3 Cross(dvec3 l, dvec3 r) => dvec3.Cross(l, r);

        /// <summary>
        /// Returns a dvec3 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
        /// </summary>
        public static dvec3 Random(Random random, dvec3 minValue, dvec3 maxValue) => dvec3.Random(random, minValue, maxValue);

        /// <summary>
        /// Returns a dvec3 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
        /// </summary>
        public static double Random(Random random, double minValue, double maxValue) => (double)random.NextDouble() * (maxValue - minValue) + minValue;

        /// <summary>
        /// Returns a dvec3 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
        /// </summary>
        public static dvec3 RandomUniform(Random random, dvec3 minValue, dvec3 maxValue) => dvec3.RandomUniform(random, minValue, maxValue);

        /// <summary>
        /// Returns a dvec3 with independent and identically distributed uniform values between 'minValue' and 'maxValue'.
        /// </summary>
        public static double RandomUniform(Random random, double minValue, double maxValue) => (double)random.NextDouble() * (maxValue - minValue) + minValue;

        /// <summary>
        /// Returns a dvec3 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
        /// </summary>
        public static dvec3 RandomNormal(Random random, dvec3 mean, dvec3 variance) => dvec3.RandomNormal(random, mean, variance);

        /// <summary>
        /// Returns a dvec3 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
        /// </summary>
        public static double RandomNormal(Random random, double mean, double variance) => (double)(Math.Sqrt((double)variance) * Math.Cos(2 * Math.PI * random.NextDouble()) * Math.Sqrt(-2.0 * Math.Log(random.NextDouble()))) + mean;

        /// <summary>
        /// Returns a dvec3 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
        /// </summary>
        public static dvec3 RandomGaussian(Random random, dvec3 mean, dvec3 variance) => dvec3.RandomGaussian(random, mean, variance);

        /// <summary>
        /// Returns a dvec3 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance.
        /// </summary>
        public static double RandomGaussian(Random random, double mean, double variance) => (double)(Math.Sqrt((double)variance) * Math.Cos(2 * Math.PI * random.NextDouble()) * Math.Sqrt(-2.0 * Math.Log(random.NextDouble()))) + mean;

    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Anaphalis aureopunctata Lingelsh. & Borza var. plantaginifolia Y.L.Chen

### Remarks
null


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
declare class IoErlenmeyerFlask extends React.Component<IconBaseProps> { }
export = IoErlenmeyerFlask;