text:
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _three = require('three');

var _three2 = _interopRequireDefault(_three);

var _MeshDescriptor2 = require('./MeshDescriptor');

var _MeshDescriptor3 = _interopRequireDefault(_MeshDescriptor2);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var LineDescriptor = function (_MeshDescriptor) {
  _inherits(LineDescriptor, _MeshDescriptor);

  function LineDescriptor() {
    _classCallCheck(this, LineDescriptor);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(LineDescriptor).apply(this, arguments));
  }

  _createClass(LineDescriptor, [{
    key: 'construct',
    value: function construct(props) {
      var geometry = props.hasOwnProperty('geometry') ? props.geometry : undefined;
      var material = props.hasOwnProperty('material') ? props.material : undefined;

      var mesh = new _three2.default.Line(geometry, material);

      if (!geometry) {
        mesh.geometry.dispose();
        mesh.geometry = undefined;
      }

      if (!material) {
        mesh.material.dispose();
        mesh.material = undefined;
      }

      return mesh;
    }
  }]);

  return LineDescriptor;
}(_MeshDescriptor3.default);

module.exports = LineDescriptor;


text:
"""A Feed forward neural network using TensorFlow Core APIs.
It implements a binary classifier for Census Income Dataset using both single
and distributed node cluster.
"""

import argparse
import json
import os
import threading

import model

import tensorflow as tf

from tensorflow.python.ops import variables
from tensorflow.python.ops import lookup_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.saved_model import signature_constants as sig_constants

tf.logging.set_verbosity(tf.logging.INFO)

class EvaluationRunHook(tf.train.SessionRunHook):
  """EvaluationRunHook performs continuous evaluation of the model.

  Args:
    checkpoint_dir (string): Dir to store model checkpoints
    metric_dir (string): Dir to store metrics like accuracy and auroc
    graph (tf.Graph): Evaluation graph
    eval_frequency (int): Frequency of evaluation every n train steps
    eval_steps (int): Evaluation steps to be performed
  """
  def __init__(self,
               checkpoint_dir,
               metric_dict,
               graph,
               eval_frequency,
               eval_steps=None,
               **kwargs):

    self._eval_steps = eval_steps
    self._checkpoint_dir = checkpoint_dir
    self._kwargs = kwargs
    self._eval_every = eval_frequency
    self._latest_checkpoint = None
    self._checkpoints_since_eval = 0
    self._graph = graph

    # With the graph object as default graph
    # See https://www.tensorflow.org/api_docs/python/tf/Graph#as_default
    # Adds ops to the graph object
    with graph.as_default():
      value_dict, update_dict = tf.contrib.metrics.aggregate_metric_map(
          metric_dict)

      # Op that creates a Summary protocol buffer by merging summaries
      self._summary_op = tf.summary.merge([
          tf.summary.scalar(name, value_op)
          for name, value_op in value_dict.iteritems()
      ])

      # Saver class add ops to save and restore
      # variables to and from checkpoint
      self._saver = tf.train.Saver()

      # Creates a global step to contain a counter for
      # the global training step
      self._gs = tf.contrib.framework.get_or_create_global_step()

      self._final_ops_dict = value_dict
      self._eval_ops = update_dict.values()

    # MonitoredTrainingSession runs hooks in background threads
    # and it doesn't wait for the thread from the last session.run()
    # call to terminate to invoke the next hook, hence locks.
    self._eval_lock = threading.Lock()
    self._checkpoint_lock = threading.Lock()
    self._file_writer = tf.summary.FileWriter(
        os.path.join(checkpoint_dir, 'eval'), graph=graph)

  def after_run(self, run_context, run_values):
    # Always check for new checkpoints in case a single evaluation
    # takes longer than checkpoint frequency and _eval_every is >1
    self._update_latest_checkpoint()

    if self._eval_lock.acquire(False):
      try:
        if self._checkpoints_since_eval > self._eval_every:
          self._checkpoints_since_eval = 0
          self._run_eval()
      finally:
        self._eval_lock.release()

  def _update_latest_checkpoint(self):
    """Update the latest checkpoint file created in the output dir."""
    if self._checkpoint_lock.acquire(False):
      try:
        latest = tf.train.latest_checkpoint(self._checkpoint_dir)
        if not latest == self._latest_checkpoint:
          self._checkpoints_since_eval += 1
          self._latest_checkpoint = latest
      finally:
        self._checkpoint_lock.release()

  def end(self, session):
    """Called at then end of session to make sure we always evaluate."""
    self._update_latest_checkpoint()

    with self._eval_lock:
      self._run_eval()

  def _run_eval(self):
    """Run model evaluation and generate summaries."""
    coord = tf.train.Coordinator(clean_stop_exception_types=(
        tf.errors.CancelledError, tf.errors.OutOfRangeError))

    with tf.Session(graph=self._graph) as session:
      # Restores previously saved variables from latest checkpoint
      self._saver.restore(session, self._latest_checkpoint)

      session.run([
          tf.tables_initializer(),
          tf.local_variables_initializer()
      ])
      tf.train.start_queue_runners(coord=coord, sess=session)
      train_step = session.run(self._gs)

      tf.logging.info('Starting Evaluation For Step: {}'.format(train_step))
      with coord.stop_on_exception():
        eval_step = 0
        while not coord.should_stop() and (self._eval_steps is None or
                                           eval_step < self._eval_steps):
          summaries, final_values, _ = session.run(
              [self._summary_op, self._final_ops_dict, self._eval_ops])
          if eval_step % 100 == 0:
            tf.logging.info("On Evaluation Step: {}".format(eval_step))
          eval_step += 1

      # Write the summaries
      self._file_writer.add_summary(summaries, global_step=train_step)
      self._file_writer.flush()
      tf.logging.info(final_values)

def run(target,
        cluster_spec,
        is_chief,
        train_steps,
        eval_steps,
        job_dir,
        train_files,
        eval_files,
        train_batch_size,
        eval_batch_size,
        learning_rate,
        eval_frequency,
        first_layer_size,
        num_layers,
        scale_factor,
        num_epochs,
        export_format):

  """Run the training and evaluation graph.
  Args:
    target (string): Tensorflow server target
    is_chief (bool): Boolean flag to specify a chief server
    train_steps (int): Maximum number of training steps
    eval_steps (int): Number of steps to run evaluation for at each checkpoint.
      if eval_steps is None, evaluation will run for 1 epoch.
    job_dir (string): Output dir for checkpoint and summary
    train_files (string): List of CSV files to read train data
    eval_files (string): List of CSV files to read eval data
    train_batch_size (int): Batch size for training
    eval_batch_size (int): Batch size for evaluation
    learning_rate (float): Learning rate for Gradient Descent
    eval_frequency (int): Run evaluation frequency every n training steps.
      Do not evaluate too frequently otherwise you will
      pay for performance and do not evaluate too in-frequently
      otherwise you will not know how soon to stop training.
      Use default values to start with
    first_layer_size (int): Size of the first DNN layer
    num_layers (int): Number of hidden layers in the DNN
    scale_factor (float): Decay rate for the size of hidden layers
    num_epochs (int): Maximum number of training data epochs on which to train
    export_format (str): One of 'JSON', 'CSV' or 'EXAMPLE'. The input format
      for the outputed saved_model binary.
  """

  # Calculate the number of hidden units
  hidden_units = [
      max(2, int(first_layer_size * scale_factor**i))
      for i in range(num_layers)
  ]

  # If the server is chief which is `master`
  # In between graph replication Chief is one node in
  # the cluster with extra responsibility and by default
  # is worker task zero. We have assigned master as the chief.
  #
  # See https://youtu.be/la_M6bCV91M?t=1203 for details on
  # distributed TensorFlow and motivation about chief.
  if is_chief:
    tf.logging.info("Created DNN hidden units {}".format(hidden_units))
    evaluation_graph = tf.Graph()
    with evaluation_graph.as_default():

      # Features and label tensors
      features, labels = model.input_fn(
          eval_files,
          num_epochs=None if eval_steps else 1,
          batch_size=eval_batch_size,
          shuffle=False
      )
      # Accuracy and AUROC metrics
      # model.model_fn returns the dict when EVAL mode
      metric_dict = model.model_fn(
          model.EVAL,
          features.copy(),
          labels,
          hidden_units=hidden_units,
          learning_rate=learning_rate
      )

    hooks = [EvaluationRunHook(
        job_dir,
        metric_dict,
        evaluation_graph,
        eval_frequency,
        eval_steps=eval_steps,
    )]
  else:
    hooks = []

  # Create a new graph and specify that as default
  with tf.Graph().as_default():
    # Placement of ops on devices using replica device setter
    # which automatically places the parameters on the `ps` server
    # and the `ops` on the workers
    #
    # See:
    # https://www.tensorflow.org/api_docs/python/tf/train/replica_device_setter
    with tf.device(tf.train.replica_device_setter(cluster=cluster_spec)):

      # Features and label tensors as read using filename queue
      features, labels = model.input_fn(
          train_files,
          num_epochs=num_epochs,
          batch_size=train_batch_size
      )

      # Returns the training graph and global step tensor
      train_op, global_step_tensor = model.model_fn(
          model.TRAIN,
          features.copy(),
          labels,
          hidden_units=hidden_units,
          learning_rate=learning_rate
      )

    # Creates a MonitoredSession for training
    # MonitoredSession is a Session-like object that handles
    # initialization, recovery and hooks
    # https://www.tensorflow.org/api_docs/python/tf/train/MonitoredTrainingSession
    with tf.train.MonitoredTrainingSession(master=target,
                                           is_chief=is_chief,
                                           checkpoint_dir=job_dir,
                                           hooks=hooks,
                                           save_checkpoint_secs=20,
                                           save_summaries_steps=50) as session:
      # Global step to keep track of global number of steps particularly in
      # distributed setting
      step = global_step_tensor.eval(session=session)

      # Run the training graph which returns the step number as tracked by
      # the global step tensor.
      # When train epochs is reached, session.should_stop() will be true.
      while (train_steps is None or
             step < train_steps) and not session.should_stop():
        step, _ = session.run([global_step_tensor, train_op])

    # Find the filename of the latest saved checkpoint file
    latest_checkpoint = tf.train.latest_checkpoint(job_dir)

    # Only perform this if chief
    if is_chief:
      build_and_run_exports(latest_checkpoint,
                            job_dir,
                            model.SERVING_INPUT_FUNCTIONS[export_format],
                            hidden_units)

def main_op():
  init_local = variables.local_variables_initializer()
  init_tables = lookup_ops.tables_initializer()
  return control_flow_ops.group(init_local, init_tables)

def build_and_run_exports(latest, job_dir, serving_input_fn, hidden_units):
  """Given the latest checkpoint file export the saved model.

  Args:
    latest (string): Latest checkpoint file
    job_dir (string): Location of checkpoints and model files
    name (string): Name of the checkpoint to be exported. Used in building the
      export path.
    hidden_units (list): Number of hidden units
    learning_rate (float): Learning rate for the SGD
  """

  prediction_graph = tf.Graph()
  exporter = tf.saved_model.builder.SavedModelBuilder(
      os.path.join(job_dir, 'export'))
  with prediction_graph.as_default():
    features, inputs_dict = serving_input_fn()
    prediction_dict = model.model_fn(
        model.PREDICT,
        features.copy(),
        None,  # labels
        hidden_units=hidden_units,
        learning_rate=None  # learning_rate unused in prediction mode
    )
    saver = tf.train.Saver()

    inputs_info = {
        name: tf.saved_model.utils.build_tensor_info(tensor)
        for name, tensor in inputs_dict.iteritems()
    }
    output_info = {
        name: tf.saved_model.utils.build_tensor_info(tensor)
        for name, tensor in prediction_dict.iteritems()
    }
    signature_def = tf.saved_model.signature_def_utils.build_signature_def(
        inputs=inputs_info,
        outputs=output_info,
        method_name=sig_constants.PREDICT_METHOD_NAME
    )

  with tf.Session(graph=prediction_graph) as session:
    session.run([tf.local_variables_initializer(), tf.tables_initializer()])
    saver.restore(session, latest)
    exporter.add_meta_graph_and_variables(
        session,
        tags=[tf.saved_model.tag_constants.SERVING],
        signature_def_map={
            sig_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature_def
        },
        legacy_init_op=main_op()
    )

  exporter.save()

def dispatch(*args, **kwargs):
  """Parse TF_CONFIG to cluster_spec and call run() method
  TF_CONFIG environment variable is available when running using
  gcloud either locally or on cloud. It has all the information required
  to create a ClusterSpec which is important for running distributed code.
  """

  tf_config = os.environ.get('TF_CONFIG')

  # If TF_CONFIG is not available run local
  if not tf_config:
    return run(target='', cluster_spec=None, is_chief=True, *args, **kwargs)

  tf_config_json = json.loads(tf_config)

  cluster = tf_config_json.get('cluster')
  job_name = tf_config_json.get('task', {}).get('type')
  task_index = tf_config_json.get('task', {}).get('index')

  # If cluster information is empty run local
  if job_name is None or task_index is None:
    return run(target='', cluster_spec=None, is_chief=True, *args, **kwargs)

  cluster_spec = tf.train.ClusterSpec(cluster)
  server = tf.train.Server(cluster_spec,
                           job_name=job_name,
                           task_index=task_index)

  # Wait for incoming connections forever
  # Worker ships the graph to the ps server
  # The ps server manages the parameters of the model.
  #
  # See a detailed video on distributed TensorFlow
  # https://www.youtube.com/watch?v=la_M6bCV91M
  if job_name == 'ps':
    server.join()
    return
  elif job_name in ['master', 'worker']:
    return run(server.target, cluster_spec, is_chief=(job_name == 'master'),
               *args, **kwargs)

if __name__ == "__main__":
  parser = argparse.ArgumentParser()
  parser.add_argument('--train-files',
                      required=True,
                      type=str,
                      help='Training files local or GCS', nargs='+')
  parser.add_argument('--eval-files',
                      required=True,
                      type=str,
                      help='Evaluation files local or GCS', nargs='+')
  parser.add_argument('--job-dir',
                      required=True,
                      type=str,
                      help="""\
                      GCS or local dir for checkpoints, exports, and
                      summaries. Use an existing directory to load a
                      trained model, or a new directory to retrain""")
  parser.add_argument('--train-steps',
                      type=int,
                      help='Maximum number of training steps to perform.')
  parser.add_argument('--eval-steps',
                      help="""\
                      Number of steps to run evalution for at each checkpoint.
                      If unspecified, will run for 1 full epoch over training
                      data""",
                      default=None,
                      type=int)
  parser.add_argument('--train-batch-size',
                      type=int,
                      default=40,
                      help='Batch size for training steps')
  parser.add_argument('--eval-batch-size',
                      type=int,
                      default=40,
                      help='Batch size for evaluation steps')
  parser.add_argument('--learning-rate',
                      type=float,
                      default=0.003,
                      help='Learning rate for SGD')
  parser.add_argument('--eval-frequency',
                      default=50,
                      help='Perform one evaluation per n steps')
  parser.add_argument('--first-layer-size',
                      type=int,
                      default=256,
                      help='Number of nodes in the first layer of DNN')
  parser.add_argument('--num-layers',
                      type=int,
                      default=2,
                      help='Number of layers in DNN')
  parser.add_argument('--scale-factor',
                      type=float,
                      default=0.25,
                      help="""\
                      Rate of decay size of layer for Deep Neural Net.
                      max(2, int(first_layer_size * scale_factor**i)) \
                      """)
  parser.add_argument('--num-epochs',
                      type=int,
                      help='Maximum number of epochs on which to train')
  parser.add_argument('--export-format',
                      type=str,
                      choices=[model.JSON, model.CSV, model.EXAMPLE],
                      default=model.JSON,
                      help="""\
                      Desired input format for the exported saved_model
                      binary.""")
  parser.add_argument('--verbosity',
                      choices=[
                          'DEBUG',
                          'ERROR',
                          'FATAL',
                          'INFO',
                          'WARN'
                      ],
                      default='INFO',
                      help='Set logging verbosity')
  parse_args, unknown = parser.parse_known_args()
  # Set python level verbosity
  tf.logging.set_verbosity(parse_args.verbosity)
  # Set C++ Graph Execution level verbosity
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(
      tf.logging.__dict__[parse_args.verbosity] / 10)
  del parse_args.verbosity

  if unknown:
    tf.logging.warn('Unknown arguments: {}'.format(unknown))

  dispatch(**parse_args.__dict__)

redpajama_set_name: RedPajamaGithub


text:
import React from "react"
import { render, screen } from "@testing-library/react"
import Homepage from "./Homepage"
import { MockAuthProvider } from "common/utils/testing"

describe("features/Home/Homepage", () => {
  describe("initial render", () => {
    it("should display user greeting when logged in", () => {
      render(
        <MockAuthProvider mocks={[]}>
          <Homepage />
        </MockAuthProvider>,
      )
      expect(screen.getByText(/Hello, Art Vandelay!/)).toBeInTheDocument()
    })
  })
})


text:
<?php

echo rex_view::title($this->i18n('title'));
include rex_be_controller::getCurrentPageObject()->getSubPath();


text:
#if !defined(FUSION_INCLUDE_DEREF)
#define FUSION_INCLUDE_DEREF

#include <boost/fusion/support/config.hpp>
#include <boost/fusion/iterator/deref.hpp>

#endif


text:
"""Metawolf session settables."""

from typing import Any

class SessionSettable:
  """SessionSettable represents a settable attribute for a given session.

  Attributes:
    session_id (str): The session ID this settable belongs to.
    recipe (str): The recipe this settable belongs to.
    name (str): The name of the settable.
    description (str): A description for the settable.
    value_type (Any): The type of the settable's value.
    optional (bool): True if the settable's value is optional.
  """
  def __init__(
      self,
      session_id: str,
      recipe: str,
      name: str,
      description: str,
      value_type: Any,
      optional: bool = False
  ) -> None:
    """Initialize the settable.

    Args:
      session_id (str): The session ID this settable belongs to.
      recipe (str): The recipe this settable belongs to.
      name (str): The name of the settable.
      description (str): A description for the settable.
      value_type (Any): Type that this Settable accepts.
      optional (bool): Optional. True if this is an optional settable.
    """
    self.session_id = session_id
    self.recipe = recipe
    self.name = name
    self.description = description
    self.type = value_type
    self.optional = optional
    self._value = None

  def SetSessionID(self, session_id: str) -> None:
    """Set the settable' session ID.

    Args:
      session_id (str): The session ID for the settable.
    """
    self.session_id = session_id

  def IsOptional(self) -> bool:
    """Return whether or not this is an optional settable."""
    return self.optional

  def SetValue(self, value: Any) -> None:
    """Set the settable' value.

    Args:
      value (Any): The value for the settable.
    """
    self._value = value

  def GetValue(self) -> Any:
    """Return the settable' value."""
    return self._value


text:
from webob import exc

from nova.api.openstack import common
from nova.api.openstack.compute.schemas import server_metadata
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import compute
from nova import exception
from nova.i18n import _
from nova.policies import server_metadata as sm_policies

class ServerMetadataController(wsgi.Controller):
    """The server metadata API controller for the OpenStack API."""

    def __init__(self):
        self.compute_api = compute.API()
        super(ServerMetadataController, self).__init__()

    def _get_metadata(self, context, server_id):
        server = common.get_instance(self.compute_api, context, server_id)
        try:
            # NOTE(mikal): get_instance_metadata sometimes returns
            # InstanceNotFound in unit tests, even though the instance is
            # fetched on the line above. I blame mocking.
            meta = self.compute_api.get_instance_metadata(context, server)
        except exception.InstanceNotFound:
            msg = _('Server does not exist')
            raise exc.HTTPNotFound(explanation=msg)
        meta_dict = {}
        for key, value in meta.items():
            meta_dict[key] = value
        return meta_dict

    @extensions.expected_errors(404)
    def index(self, req, server_id):
        """Returns the list of metadata for a given instance."""
        context = req.environ['nova.context']
        context.can(sm_policies.POLICY_ROOT % 'index')
        return {'metadata': self._get_metadata(context, server_id)}

    @extensions.expected_errors((400, 403, 404, 409))
    # NOTE(gmann): Returns 200 for backwards compatibility but should be 201
    # as this operation complete the creation of metadata.
    @validation.schema(server_metadata.create)
    def create(self, req, server_id, body):
        metadata = body['metadata']
        context = req.environ['nova.context']
        context.can(sm_policies.POLICY_ROOT % 'create')
        new_metadata = self._update_instance_metadata(context,
                                                      server_id,
                                                      metadata,
                                                      delete=False)

        return {'metadata': new_metadata}

    @extensions.expected_errors((400, 403, 404, 409))
    @validation.schema(server_metadata.update)
    def update(self, req, server_id, id, body):
        context = req.environ['nova.context']
        context.can(sm_policies.POLICY_ROOT % 'update')
        meta_item = body['meta']
        if id not in meta_item:
            expl = _('Request body and URI mismatch')
            raise exc.HTTPBadRequest(explanation=expl)

        self._update_instance_metadata(context,
                                       server_id,
                                       meta_item,
                                       delete=False)

        return {'meta': meta_item}

    @extensions.expected_errors((400, 403, 404, 409))
    @validation.schema(server_metadata.update_all)
    def update_all(self, req, server_id, body):
        context = req.environ['nova.context']
        context.can(sm_policies.POLICY_ROOT % 'update_all')
        metadata = body['metadata']
        new_metadata = self._update_instance_metadata(context,
                                                      server_id,
                                                      metadata,
                                                      delete=True)

        return {'metadata': new_metadata}

    def _update_instance_metadata(self, context, server_id, metadata,
                                  delete=False):
        server = common.get_instance(self.compute_api, context, server_id)
        try:
            return self.compute_api.update_instance_metadata(context,
                                                             server,
                                                             metadata,
                                                             delete)

        except exception.InstanceUnknownCell as e:
            raise exc.HTTPNotFound(explanation=e.format_message())

        except exception.QuotaError as error:
            raise exc.HTTPForbidden(explanation=error.format_message())

        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())

        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error,
                    'update metadata', server_id)

    @extensions.expected_errors(404)
    def show(self, req, server_id, id):
        """Return a single metadata item."""
        context = req.environ['nova.context']
        context.can(sm_policies.POLICY_ROOT % 'show')
        data = self._get_metadata(context, server_id)

        try:
            return {'meta': {id: data[id]}}
        except KeyError:
            msg = _("Metadata item was not found")
            raise exc.HTTPNotFound(explanation=msg)

    @extensions.expected_errors((404, 409))
    @wsgi.response(204)
    def delete(self, req, server_id, id):
        """Deletes an existing metadata."""
        context = req.environ['nova.context']
        context.can(sm_policies.POLICY_ROOT % 'delete')
        metadata = self._get_metadata(context, server_id)

        if id not in metadata:
            msg = _("Metadata item was not found")
            raise exc.HTTPNotFound(explanation=msg)

        server = common.get_instance(self.compute_api, context, server_id)
        try:
            self.compute_api.delete_instance_metadata(context, server, id)

        except exception.InstanceUnknownCell as e:
            raise exc.HTTPNotFound(explanation=e.format_message())

        except exception.InstanceIsLocked as e:
            raise exc.HTTPConflict(explanation=e.format_message())

        except exception.InstanceInvalidState as state_error:
            common.raise_http_conflict_for_instance_invalid_state(state_error,
                    'delete metadata', server_id)


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

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Anolis factsheet on ARKive - Anolis cusuco</title>
        <link rel="canonical" href="http://www.arkive.org/anolis/anolis-cusuco/" />
		<link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" />
		<link rel="icon" href="/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Anolis (Anolis cusuco)

Synonyms:
Norops cusuco

Kingdom	Animalia

Phylum	Chordata

Class	Reptilia

Order	Squamata

Family	Polychrotidae

Genus	Anolis (1)

Anolis cusuco is classified as Endangered (EN) on the IUCN Red List (1).

Information on Anolis cusuco is being researched and written and will appear here shortly.

This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact:
arkive@wildscreen.org.uk

IUCN Red List (February, 2012)
http://www.iucnredlist.org


text:
package types

import (
	"container/heap"
	"errors"
	"io"
	"math/big"
	"sync/atomic"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/crypto"
	"github.com/ethereum/go-ethereum/rlp"
)

//go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go

var (
	ErrInvalidSig = errors.New("invalid transaction v, r, s values")
)

type Transaction struct {
	data txdata
	// caches
	hash atomic.Value
	size atomic.Value
	from atomic.Value
}

type txdata struct {
	AccountNonce uint64          `json:"nonce"    gencodec:"required"`
	Price        *big.Int        `json:"gasPrice" gencodec:"required"`
	GasLimit     uint64          `json:"gas"      gencodec:"required"`
	Recipient    *common.Address `json:"to"       rlp:"nil"` // nil means contract creation
	Amount       *big.Int        `json:"value"    gencodec:"required"`
	Payload      []byte          `json:"input"    gencodec:"required"`

	// Signature values
	V *big.Int `json:"v" gencodec:"required"`
	R *big.Int `json:"r" gencodec:"required"`
	S *big.Int `json:"s" gencodec:"required"`

	// This is only used when marshaling to JSON.
	Hash *common.Hash `json:"hash" rlp:"-"`
}

type txdataMarshaling struct {
	AccountNonce hexutil.Uint64
	Price        *hexutil.Big
	GasLimit     hexutil.Uint64
	Amount       *hexutil.Big
	Payload      hexutil.Bytes
	V            *hexutil.Big
	R            *hexutil.Big
	S            *hexutil.Big
}

func NewTransaction(nonce uint64, to common.Address, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *Transaction {
	return newTransaction(nonce, &to, amount, gasLimit, gasPrice, data)
}

func NewContractCreation(nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *Transaction {
	return newTransaction(nonce, nil, amount, gasLimit, gasPrice, data)
}

func newTransaction(nonce uint64, to *common.Address, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *Transaction {
	if len(data) > 0 {
		data = common.CopyBytes(data)
	}
	d := txdata{
		AccountNonce: nonce,
		Recipient:    to,
		Payload:      data,
		Amount:       new(big.Int),
		GasLimit:     gasLimit,
		Price:        new(big.Int),
		V:            new(big.Int),
		R:            new(big.Int),
		S:            new(big.Int),
	}
	if amount != nil {
		d.Amount.Set(amount)
	}
	if gasPrice != nil {
		d.Price.Set(gasPrice)
	}

	return &Transaction{data: d}
}

// ChainId returns which chain id this transaction was signed for (if at all)
func (tx *Transaction) ChainId() *big.Int {
	return deriveChainId(tx.data.V)
}

// Protected returns whether the transaction is protected from replay protection.
func (tx *Transaction) Protected() bool {
	return isProtectedV(tx.data.V)
}

func isProtectedV(V *big.Int) bool {
	if V.BitLen() <= 8 {
		v := V.Uint64()
		return v != 27 && v != 28
	}
	// anything not 27 or 28 is considered protected
	return true
}

// EncodeRLP implements rlp.Encoder
func (tx *Transaction) EncodeRLP(w io.Writer) error {
	return rlp.Encode(w, &tx.data)
}

// DecodeRLP implements rlp.Decoder
func (tx *Transaction) DecodeRLP(s *rlp.Stream) error {
	_, size, _ := s.Kind()
	err := s.Decode(&tx.data)
	if err == nil {
		tx.size.Store(common.StorageSize(rlp.ListSize(size)))
	}

	return err
}

// MarshalJSON encodes the web3 RPC transaction format.
func (tx *Transaction) MarshalJSON() ([]byte, error) {
	hash := tx.Hash()
	data := tx.data
	data.Hash = &hash
	return data.MarshalJSON()
}

// UnmarshalJSON decodes the web3 RPC transaction format.
func (tx *Transaction) UnmarshalJSON(input []byte) error {
	var dec txdata
	if err := dec.UnmarshalJSON(input); err != nil {
		return err
	}

	withSignature := dec.V.Sign() != 0 || dec.R.Sign() != 0 || dec.S.Sign() != 0
	if withSignature {
		var V byte
		if isProtectedV(dec.V) {
			chainID := deriveChainId(dec.V).Uint64()
			V = byte(dec.V.Uint64() - 35 - 2*chainID)
		} else {
			V = byte(dec.V.Uint64() - 27)
		}
		if !crypto.ValidateSignatureValues(V, dec.R, dec.S, false) {
			return ErrInvalidSig
		}
	}

	*tx = Transaction{data: dec}
	return nil
}

func (tx *Transaction) Data() []byte       { return common.CopyBytes(tx.data.Payload) }
func (tx *Transaction) Gas() uint64        { return tx.data.GasLimit }
func (tx *Transaction) GasPrice() *big.Int { return new(big.Int).Set(tx.data.Price) }
func (tx *Transaction) Value() *big.Int    { return new(big.Int).Set(tx.data.Amount) }
func (tx *Transaction) Nonce() uint64      { return tx.data.AccountNonce }
func (tx *Transaction) CheckNonce() bool   { return true }

// To returns the recipient address of the transaction.
// It returns nil if the transaction is a contract creation.
func (tx *Transaction) To() *common.Address {
	if tx.data.Recipient == nil {
		return nil
	}
	to := *tx.data.Recipient
	return &to
}

// Hash hashes the RLP encoding of tx.
// It uniquely identifies the transaction.
func (tx *Transaction) Hash() common.Hash {
	if hash := tx.hash.Load(); hash != nil {
		return hash.(common.Hash)
	}
	v := rlpHash(tx)
	tx.hash.Store(v)
	return v
}

// Size returns the true RLP encoded storage size of the transaction, either by
// encoding and returning it, or returning a previsouly cached value.
func (tx *Transaction) Size() common.StorageSize {
	if size := tx.size.Load(); size != nil {
		return size.(common.StorageSize)
	}
	c := writeCounter(0)
	rlp.Encode(&c, &tx.data)
	tx.size.Store(common.StorageSize(c))
	return common.StorageSize(c)
}

// AsMessage returns the transaction as a core.Message.
//
// AsMessage requires a signer to derive the sender.
//
// XXX Rename message to something less arbitrary?
func (tx *Transaction) AsMessage(s Signer) (Message, error) {
	msg := Message{
		nonce:      tx.data.AccountNonce,
		gasLimit:   tx.data.GasLimit,
		gasPrice:   new(big.Int).Set(tx.data.Price),
		to:         tx.data.Recipient,
		amount:     tx.data.Amount,
		data:       tx.data.Payload,
		checkNonce: true,
	}

	var err error
	msg.from, err = Sender(s, tx)
	return msg, err
}

// WithSignature returns a new transaction with the given signature.
// This signature needs to be in the [R || S || V] format where V is 0 or 1.
func (tx *Transaction) WithSignature(signer Signer, sig []byte) (*Transaction, error) {
	r, s, v, err := signer.SignatureValues(tx, sig)
	if err != nil {
		return nil, err
	}
	cpy := &Transaction{data: tx.data}
	cpy.data.R, cpy.data.S, cpy.data.V = r, s, v
	return cpy, nil
}

// Cost returns amount + gasprice * gaslimit.
func (tx *Transaction) Cost() *big.Int {
	total := new(big.Int).Mul(tx.data.Price, new(big.Int).SetUint64(tx.data.GasLimit))
	total.Add(total, tx.data.Amount)
	return total
}

func (tx *Transaction) RawSignatureValues() (*big.Int, *big.Int, *big.Int) {
	return tx.data.V, tx.data.R, tx.data.S
}

// Transactions is a Transaction slice type for basic sorting.
type Transactions []*Transaction

// Len returns the length of s.
func (s Transactions) Len() int { return len(s) }

// Swap swaps the i'th and the j'th element in s.
func (s Transactions) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

// GetRlp implements Rlpable and returns the i'th element of s in rlp.
func (s Transactions) GetRlp(i int) []byte {
	enc, _ := rlp.EncodeToBytes(s[i])
	return enc
}

// TxDifference returns a new set which is the difference between a and b.
func TxDifference(a, b Transactions) Transactions {
	keep := make(Transactions, 0, len(a))

	remove := make(map[common.Hash]struct{})
	for _, tx := range b {
		remove[tx.Hash()] = struct{}{}
	}

	for _, tx := range a {
		if _, ok := remove[tx.Hash()]; !ok {
			keep = append(keep, tx)
		}
	}

	return keep
}

// TxByNonce implements the sort interface to allow sorting a list of transactions
// by their nonces. This is usually only useful for sorting transactions from a
// single account, otherwise a nonce comparison doesn't make much sense.
type TxByNonce Transactions

func (s TxByNonce) Len() int           { return len(s) }
func (s TxByNonce) Less(i, j int) bool { return s[i].data.AccountNonce < s[j].data.AccountNonce }
func (s TxByNonce) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

// TxByPrice implements both the sort and the heap interface, making it useful
// for all at once sorting as well as individually adding and removing elements.
type TxByPrice Transactions

func (s TxByPrice) Len() int           { return len(s) }
func (s TxByPrice) Less(i, j int) bool { return s[i].data.Price.Cmp(s[j].data.Price) > 0 }
func (s TxByPrice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }

func (s *TxByPrice) Push(x interface{}) {
	*s = append(*s, x.(*Transaction))
}

func (s *TxByPrice) Pop() interface{} {
	old := *s
	n := len(old)
	x := old[n-1]
	*s = old[0 : n-1]
	return x
}

// TransactionsByPriceAndNonce represents a set of transactions that can return
// transactions in a profit-maximizing sorted order, while supporting removing
// entire batches of transactions for non-executable accounts.
type TransactionsByPriceAndNonce struct {
	txs    map[common.Address]Transactions // Per account nonce-sorted list of transactions
	heads  TxByPrice                       // Next transaction for each unique account (price heap)
	signer Signer                          // Signer for the set of transactions
}

// NewTransactionsByPriceAndNonce creates a transaction set that can retrieve
// price sorted transactions in a nonce-honouring way.
//
// Note, the input map is reowned so the caller should not interact any more with
// if after providing it to the constructor.
func NewTransactionsByPriceAndNonce(signer Signer, txs map[common.Address]Transactions) *TransactionsByPriceAndNonce {
	// Initialize a price based heap with the head transactions
	heads := make(TxByPrice, 0, len(txs))
	for from, accTxs := range txs {
		heads = append(heads, accTxs[0])
		// Ensure the sender address is from the signer
		acc, _ := Sender(signer, accTxs[0])
		txs[acc] = accTxs[1:]
		if from != acc {
			delete(txs, from)
		}
	}
	heap.Init(&heads)

	// Assemble and return the transaction set
	return &TransactionsByPriceAndNonce{
		txs:    txs,
		heads:  heads,
		signer: signer,
	}
}

// Peek returns the next transaction by price.
func (t *TransactionsByPriceAndNonce) Peek() *Transaction {
	if len(t.heads) == 0 {
		return nil
	}
	return t.heads[0]
}

// Shift replaces the current best head with the next one from the same account.
func (t *TransactionsByPriceAndNonce) Shift() {
	acc, _ := Sender(t.signer, t.heads[0])
	if txs, ok := t.txs[acc]; ok && len(txs) > 0 {
		t.heads[0], t.txs[acc] = txs[0], txs[1:]
		heap.Fix(&t.heads, 0)
	} else {
		heap.Pop(&t.heads)
	}
}

// Pop removes the best transaction, *not* replacing it with the next one from
// the same account. This should be used when a transaction cannot be executed
// and hence all subsequent ones should be discarded from the same account.
func (t *TransactionsByPriceAndNonce) Pop() {
	heap.Pop(&t.heads)
}

// Message is a fully derived transaction and implements core.Message
//
// NOTE: In a future PR this will be removed.
type Message struct {
	to         *common.Address
	from       common.Address
	nonce      uint64
	amount     *big.Int
	gasLimit   uint64
	gasPrice   *big.Int
	data       []byte
	checkNonce bool
}

func NewMessage(from common.Address, to *common.Address, nonce uint64, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte, checkNonce bool) Message {
	return Message{
		from:       from,
		to:         to,
		nonce:      nonce,
		amount:     amount,
		gasLimit:   gasLimit,
		gasPrice:   gasPrice,
		data:       data,
		checkNonce: checkNonce,
	}
}

func (m Message) From() common.Address { return m.from }
func (m Message) To() *common.Address  { return m.to }
func (m Message) GasPrice() *big.Int   { return m.gasPrice }
func (m Message) Value() *big.Int      { return m.amount }
func (m Message) Gas() uint64          { return m.gasLimit }
func (m Message) Nonce() uint64        { return m.nonce }
func (m Message) Data() []byte         { return m.data }
func (m Message) CheckNonce() bool     { return m.checkNonce }


text:
VERSION = (0, 2, 0, 'pbs', '')
__version__ = '.'.join(map(str, VERSION))

def get_version():
    version = '%s.%s' % (VERSION[0], VERSION[1])
    if VERSION[2]:
        version = '%s.%s' % (version, VERSION[2])
    if VERSION[3:] == ('alpha', 0):
        version = '%s pre-alpha' % version
    else:
        if VERSION[3] != 'final':
            version = '%s %s %s' % (version, VERSION[3], VERSION[4])
    return version

# patch settings
try:
    from conf import patch_settings
    from django.conf import settings
    patch_settings()
except ImportError:
    """
    This exception means that either the application is being built, or is
    otherwise installed improperly. Both make running patch_settings
    irrelevant.
    """
    pass
except AttributeError:
    """
    Same as Above
    """
    pass


text:
package com.karateca.ddescriber.dialog;

import com.karateca.ddescriber.model.TestFindResult;
import com.karateca.ddescriber.model.TestState;
import com.karateca.ddescriber.model.TreeNode;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Andres Dominguez.
 */
class CustomTreeCellRenderer extends DefaultTreeCellRenderer {

  private static final Color GREEN_BG_COLOR = new Color(182, 232, 172);
  private static final Color GREEN_FG_COLOR = new Color(57, 194, 70);
  private static final Color RED_BG_COLOR = new Color(232, 117, 107);
  private static final Color RED_FG_COLOR = new Color(194, 41, 39);
  private final Map<TestState, NodeSettings> colorMap = new HashMap<TestState, NodeSettings>();

  private class NodeSettings {
    final Color bgColor;
    final Color fgColor;
    final Icon icon;

    private NodeSettings(Color bgColor, Color fgColor, Icon icon) {
      this.bgColor = bgColor;
      this.fgColor = fgColor;
      this.icon = icon;
    }

    public void paintNode() {
      setBackgroundNonSelectionColor(bgColor);
      setBackgroundSelectionColor(fgColor);
      setIcon(icon);
    }
  }

  public CustomTreeCellRenderer() {
    Color defaultBgSelColor = getBackgroundSelectionColor();
    Color defaultNonSelColor = getBackgroundNonSelectionColor();
    NodeSettings defaultColor = new NodeSettings(defaultNonSelColor, defaultBgSelColor, DialogIcons.itGrayIcon);

    colorMap.put(TestState.Excluded, new NodeSettings(RED_BG_COLOR, RED_FG_COLOR, DialogIcons.itRedIcon));
    colorMap.put(TestState.Included, new NodeSettings(GREEN_BG_COLOR, GREEN_FG_COLOR, DialogIcons.itGreenIcon));
    colorMap.put(TestState.NotModified, defaultColor);
    colorMap.put(TestState.RolledBack, defaultColor);
  }

  @Override
  public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    Component component = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;

    // Ignore non test nodes.
    if (!(node.getUserObject() instanceof TestFindResult)) {
      return component;
    }

    TreeNode treeNode = (TreeNode) node;
    TestFindResult findResult = treeNode.getNodeValue();

    getNodeSettings(findResult).paintNode();

    if (findResult.isDescribe()) {
      setIcon(DialogIcons.descIcon);
    }

    setText(findResult.toString());

    return component;
  }

  private NodeSettings getNodeSettings(TestFindResult testFindResult) {
    TestState pendingState = testFindResult.getPendingChangeState();
    TestState originalState = testFindResult.getTestState();

    if (pendingState == TestState.RolledBack &&
        (originalState == TestState.Included || originalState == TestState.Excluded)) {
      return colorMap.get(TestState.NotModified);
    }

    if (pendingState == TestState.Included || pendingState == TestState.Excluded) {
      return colorMap.get(pendingState);
    }

    return colorMap.get(originalState);
  }
}


text:
class AddJobDateToJobs < ActiveRecord::Migration
  def change
    add_column :jobs, :job_date, :datetime
  end
end


text:
<?php
/**
 * Memcache & MySQL PHP Session Handler
 *
 * original author Jakub Matějka <jakub@keboola.com>
 * @see http://pureform.wordpress.com/2009/04/08/memcache-mysql-php-session-handler/
 */
class Kwf_Util_SessionHandler
{
    /**
     * @var int
     */
    protected $_lifeTime;

    /**
     * @var Memcache
     */
    private $_memcache;

    /**
     * @var string
     */
    private $_initSessionData;

    /**
     * interval for session expiration update in the DB
     * @var int
     */
    protected $_refreshTime;

    public static function init()
    {
        ini_set('session.gc_probability', '1'); //always enable gc, is disabled on debian systems where gc is done by a cronjob
        ini_set('session.gc_divisor', '1000');

        $h = new self();
        session_set_save_handler(
            array($h, 'open'),
            array($h, 'close'),
            array($h, 'read'),
            array($h, 'write'),
            array($h, 'destroy'),
            array($h, 'gc')
        );

        // this ensures to write down and close the session when destroying the handler object
        register_shutdown_function("session_write_close");
    }

    /**
     * opening of the session - mandatory arguments won't be needed
     *
     * @param string $savePath
     * @param string $sessionName
     * @return bool
     */
    public function open($savePath, $sessionName)
    {
        if (!isset($this->_lifeTime)) $this->_lifeTime = intval(ini_get("session.gc_maxlifetime"));
        if (!isset($this->_refreshTime)) $this->_refreshTime = ceil($this->_lifeTime / 3);

        $this->_initSessionData = null;

        $this->_memcache = new Memcache();
        if (Kwf_Config::getValue('aws.simpleCacheCluster')) {
            $servers = Kwf_Util_Aws_ElastiCache_CacheClusterEndpoints::getCached(Kwf_Config::getValue('aws.simpleCacheCluster'));
        } else if (Kwf_Cache_Simple::$memcacheHost) {
            $servers = array(
                array(
                    'host' => Kwf_Cache_Simple::$memcacheHost,
                    'port' => Kwf_Cache_Simple::$memcachePort
                )
            );
        } else {
            throw new Kwf_Exception("no memcache configured");
        }
        foreach ($servers as $s) {
            if (version_compare(phpversion('memcache'), '2.1.0') == -1 || phpversion('memcache')=='2.2.4') { // < 2.1.0
                $this->_memcache->addServer($s['host'], $s['port'], true, 1, 1, 1);
            } else if (version_compare(phpversion('memcache'), '3.0.0') == -1) { // < 3.0.0
                $this->_memcache->addServer($s['host'], $s['port'], true, 1, 1, 1, true, null, 10000);
            } else {
                $this->_memcache->addServer($s['host'], $s['port'], true, 1, 1, 1);
            }
        }

        return true;
    }

    /**
     * closing the session
     *
     * @return bool
     */
    public function close()
    {
        $this->_initSessionData = null;
        return true;
    }

    /**
     * reading of the session data
     * if the data couldn't be found in the Memcache, we try to load it from the DB
     * we have to update the time of data expiration in the db using _updateDbExpiration()
     * the life time in Memcache is updated automatically by write operation
     *
     * @param string $sessionId
     * @return string
     */
    function read($sessionId)
    {
        $this->_initSessionData = '';
        $d = $this->_memcache->get(Kwf_Cache_Simple::getUniquePrefix().'sess-'.$sessionId);
        if ($d === false) {
            Kwf_Benchmark::count('sessionhdl', 'load from db');
            //the record could not be found in the Memcache, loading from the db
            $this->_initSessionData = Kwf_Registry::get('db')->query("SELECT data FROM kwf_sessions WHERE sessionId=?", $sessionId)->fetchColumn();
            if ($this->_initSessionData) {
                //record found in the db, cache in memcache
                self::_updateDbExpiration($sessionId);
            } else {
                //record not in the db
                $this->_initSessionData = '';
            }
        } else {
            $expiration = $d['expiration'];
            if ($expiration+$this->_refreshTime < time()) {
                //expired; nothing to do
            } else {
                $this->_initSessionData = $d['data'];
                //if we didn't write into the db for at least
                //$this->_refreshTime (5 minutes), we need to refresh the expiration time in the db
                $ttl = $expiration - time();
                if ($ttl < $this->_refreshTime) {
                    self::_updateDbExpiration($sessionId);
                }
            }
        }
        return $this->_initSessionData;
    }

    /**
     * update of the expiration time of the db record
     *
     * @param string $sessionId
     */
    private function _updateDbExpiration($sessionId)
    {
        Kwf_Benchmark::count('sessionhdl', '_updateDbExpiration');
        $expiration = $this->_lifeTime + time();
        Kwf_Registry::get('db')->query("UPDATE kwf_sessions SET expiration=? WHERE sessionId=?", array($expiration, $sessionId));

        //we store the time of the new expiration into the Memcache
        $this->_memcacheSet($sessionId, $this->_initSessionData);
    }

    private function _memcacheSet($sessionId, $data)
    {
        $d = array(
            'data' => $data,
            'expiration' => $this->_lifeTime + time()
        );
        $this->_memcache->set(
            Kwf_Cache_Simple::getUniquePrefix().'sess-'.$sessionId,
            $d,
            false,
            time() + $this->_lifeTime + $this->_refreshTime
        );
    }

    /**
     * cache write - this is called when the script is about to finish, or when session_write_close() is called
     * data are written only when something has changed
     *
     * @param string $sessionId
     * @param string $data
     * @return bool
     */
    public function write($sessionId, $data)
    {
        $t = microtime(true);
        $expiration = $this->_lifeTime + time();

        //we store time of the db record expiration in the Memcache
        if ($this->_initSessionData !== $data) {
            Kwf_Registry::get('db')->query("REPLACE INTO kwf_sessions (sessionId, expiration, data) VALUES(?, ?, ?)", array($sessionId, $expiration, $data));
            $this->_memcacheSet($sessionId, $data);
        }
        Kwf_Benchmark::count('sessionhdl', 'read: '.((microtime(true)-$t)*1000).'ms');
        return true;
    }

    /**
     * destroy of the session
     *
     * @param string $sessionId
     * @return bool
     */
    public function destroy($sessionId)
    {
        $this->_memcache->delete(Kwf_Cache_Simple::getUniquePrefix().'sess-'.$sessionId);
        $this->_memcache->delete(Kwf_Cache_Simple::getUniquePrefix().'sess-db-'.$sessionId);
        Kwf_Registry::get('db')->query("DELETE FROM kwf_sessions WHERE sessionId=?", $sessionId);
        return true;
    }

    /**
     * called by the garbage collector
     *
     * @param int $maxlifetime
     * @return bool
     */
    public function gc($maxlifetime)
    {
        foreach (Kwf_Registry::get('db')->query("SELECT sessionId FROM kwf_sessions WHERE expiration < ?", time())->fetchAll() as $r) {
            $this->destroy($r['sessionId']);
        }
        return true;
    }
}


text:
#include "syshdrs.h"
#ifdef PRAGMA_HDRSTOP
#	pragma hdrstop
#endif

int
FTPUmask(const FTPCIPtr cip, const char *const umsk)
{
	if (cip == NULL)
		return (kErrBadParameter);
	if (strcmp(cip->magic, kLibraryMagic))
		return (kErrBadMagic);
	if ((umsk == NULL) || (umsk[0] == '\0'))
		return (kErrBadParameter);
	if (FTPCmd(cip, "SITE UMASK %s", umsk) == 2)
		return (kNoErr);
	cip->errNo = kErrUmaskFailed;
	return (kErrUmaskFailed);
}	/* FTPUmask */


text:
Ti=Obligations of the {_operator}

1.sec=Personal {_data} will be {_processed} on the basis of {_processing} corresponding to Article 6(a) of the GDPR, i.e. consent collected under the conditions of Article 7 of the GDPR and free, informed and unequivocal.

2.sec=The {_operator} undertakes to ensure that the consent of the {_data_subject}s whose {_data} has been collected for {_processing} is respected. To this end, the {_operator} guarantees that the partners will only access {_data} for which the {_data_subject} has given his or her consent, in compliance with the sole purposes set out in this {_contract} by the partners.

3.0.sec=Consequently, the {_operator} has an obligation to :

3.1.sec=obtain the consent of the persons whose {_data} will be collected and used in accordance with the GDPR; and to inform the {_data_subject}s that this consent will be used as a basis for the circulation of their {_data} to the partners for the purposes and uses and access to said {_data} mentioned above;

3.2.sec=transmit the consent documents to the partners and give them access so that they can check the validity of the consents before {_processing} the {_data} collected;

3.3.sec=allow access only to {_data} whose circulation has been authorised under the terms of this {_contract};

3.4.sec=collect consents only for the purposes specified under the terms of this {_contract};

3.5.sec=establish and maintain proof and record of consents and partner access to {_data}, as well as proof and record of partner verification of consents with the {_operator};

3.6.sec=provide the partners with a technical protocol and the means required to make the {_data} available in accordance with the consents collected ;

3.7.sec=be fully transparent about the technical means it uses to manage consent and access to {_data} ;

3.8.0.sec=to respect the state of the art standards guaranteeing person-centred use of {_data} ;

3.8.1.sec=encryption of consent {_data}

3.8.2.sec=electronic signature of consent documents

3.8.3.sec=secure transfer of consent

3.8.4.sec=single key authentication

3.8.=[G/Z/ol-bullet/s4]

3.9.sec=to make every effort to acquire official and relevant certifications on the protection of privacy;

3.10.sec=to enable {_data_subject}s to give and revoke their consent from a single interface, independent of the partners.

3.=[G/Z/ol/s10]

=[G/Z/ol/s3]


text:
title: Responsive Navigation
description: Our three Menu patterns form like Voltron into one responsive Menu plugin, which allows you to switch between patterns at different screen sizes.
video: 'dmKun75_9oc'
js:
  - js/foundation.responsiveMenu.js
  - js/foundation.responsiveToggle.js
---

## Responsive Menu

The Menu has some responsive CSS classes built in, which allow you to re-orient a menu on different screen sizes.

   Watch this part in video

```html_example
<ul class="vertical medium-horizontal menu">
  <li><a href="#0"><i class="fi-list"></i> <span>One</span></a></li>
  <li><a href="#0"><i class="fi-list"></i> <span>Two</span></a></li>
  <li><a href="#0"><i class="fi-list"></i> <span>Three</span></a></li>
  <li><a href="#0"><i class="fi-list"></i> <span>Four</span></a></li>
</ul>
```

---

The Menu can be augmented with one of three different plugins—dropdown menu, drilldown menu, or accordion menu. However, these patterns tend to work best on specific screen sizes.

With our responsive Menu plugin, you can apply a default pattern to a Menu, and then change that pattern on other screen sizes.

Some Menu Combination (but not limited) to are

- [Drilldown Dropdown Menu](#drilldown-dropdown-menu)
- [Accordion Dropdown Menu](#accordion-dropdown-menu)
- [Drilldown Accordion Menu](#drilldown-accordion-menu)

#### Drilldown Dropdown Menu

A drilldown menu works well on mobile, but on larger screens, you may want to convert that same menu into a dropdown. Here's an example that does just that:

   Watch this part in video

```html_example
<ul class="vertical medium-horizontal menu" data-responsive-menu="drilldown medium-dropdown">
  <li>
    <a href="#">Item 1</a>
    <ul class="vertical menu">
      <li>
        <a href="#">Item 1A</a>
        <ul class="vertical menu">
          <li><a href="#">Item 1A</a></li>
          <li><a href="#">Item 1B</a></li>
          <li><a href="#">Item 1C</a></li>
          <li><a href="#">Item 1D</a></li>
          <li><a href="#">Item 1E</a></li>
        </ul>
      </li>
      <li><a href="#">Item 1B</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Item 2</a>
    <ul class="vertical menu">
      <li><a href="#">Item 2A</a></li>
      <li><a href="#">Item 2B</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Item 3</a>
    <ul class="vertical menu">
      <li><a href="#">Item 3A</a></li>
      <li><a href="#">Item 3B</a></li>
    </ul>
  </li>
</ul>
```

    Bug(v6.3.1): There is a bug within drilldown-dropdown menu combo. If you set up a responsive menu with drilldown on small, then dropdown for medium up, and resize to small and then back to medium the dropdowns will not work. The bug can be reproduced here

    Good News: The Bug will be fixed with the upcoming foundation release. If you are specifically using v6.3.1, we recommend to use this below patch to fix this.

```javascript
// Patch for a Bug in v6.3.1
$(window).on('changed.zf.mediaquery', function() {
  $('.is-dropdown-submenu.invisible').removeClass('invisible');
});
```

#### Accordion Dropdown Menu

Same like drilldowns, an accordion menu works well on mobile, but on larger screens, you may want to convert that same menu into a dropdown. Here's an example for the same:

```html_example
<ul class="vertical medium-horizontal menu" data-responsive-menu="accordion medium-dropdown">
  <li>
    <a href="#">Item 1</a>
    <ul class="vertical menu">
      <li>
        <a href="#">Item 1A</a>
        <ul class="vertical menu">
          <li><a href="#">Item 1A</a></li>
          <li><a href="#">Item 1B</a></li>
          <li><a href="#">Item 1C</a></li>
          <li><a href="#">Item 1D</a></li>
          <li><a href="#">Item 1E</a></li>
        </ul>
      </li>
      <li><a href="#">Item 1B</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Item 2</a>
    <ul class="vertical menu">
      <li><a href="#">Item 2A</a></li>
      <li><a href="#">Item 2B</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Item 3</a>
    <ul class="vertical menu">
      <li><a href="#">Item 3A</a></li>
      <li><a href="#">Item 3B</a></li>
    </ul>
  </li>
</ul>
```

#### Drilldown Accordion Menu

Just like foundation docs itself (see left sidenav), an accordion menu is great for a sidenav of a website on desktop, but for mobile, You might need Drilldown menu.

```html_example
<ul class="vertical menu" data-responsive-menu="drilldown medium-accordion" style="max-width: 250px;">
  <li>
    <a href="#">Item 1</a>
    <ul class="vertical menu">
      <li>
        <a href="#">Item 1A</a>
        <ul class="vertical menu">
          <li><a href="#">Item 1A</a></li>
          <li><a href="#">Item 1B</a></li>
          <li><a href="#">Item 1C</a></li>
          <li><a href="#">Item 1D</a></li>
          <li><a href="#">Item 1E</a></li>
        </ul>
      </li>
      <li><a href="#">Item 1B</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Item 2</a>
    <ul class="vertical menu">
      <li><a href="#">Item 2A</a></li>
      <li><a href="#">Item 2B</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Item 3</a>
    <ul class="vertical menu">
      <li><a href="#">Item 3A</a></li>
      <li><a href="#">Item 3B</a></li>
    </ul>
  </li>
</ul>
```

---

## Responsive Toggle

In Foundation 5, the top bar combined this menu toggling concept into one plugin. We now have a separate, optional component you can use in tandem with the responsive plugin. It's called the title bar, and it allows you to quickly setup a menu toggle on mobile. The title bar hides itself on larger screens.

To set it up, first give your menu a unique ID. (You don't even need to use Menu! Any element will work.) Next, add a title bar with the class `.title-bar` and the attribute `data-responsive-toggle`. The value of `data-responsive-toggle` should be the ID of the menu you're toggling. Lastly, add `data-toggle` to the element that will trigger the toggle. The value of `data-toggle` should also be the ID of the menu you're toggling.

By default, the title bar will be visible on small screens, and the Menu hides. At the medium breakpoint, the title bar disappears, and the menu is always visible. This breakpoint can be changed with the `data-hide-for` attribute in HTML, or the `hideFor` setting in JavaScript.

 Watch this part in video

Scale your browser down to see the toggle happen.

```html_example
<div class="title-bar" data-responsive-toggle="example-menu" data-hide-for="medium">
  <button class="menu-icon" type="button" data-toggle="example-menu"></button>
  <div class="title-bar-title">Menu</div>
</div>

<div class="top-bar" id="example-menu">
  <div class="top-bar-left">
    <ul class="dropdown menu" data-dropdown-menu>
      <li class="menu-text">Site Title</li>
      <li>
        <a href="#">One</a>
        <ul class="menu vertical">
          <li><a href="#">One</a></li>
          <li><a href="#">Two</a></li>
          <li><a href="#">Three</a></li>
        </ul>
      </li>
      <li><a href="#">Two</a></li>
      <li><a href="#">Three</a></li>
    </ul>
  </div>
  <div class="top-bar-right">
    <ul class="menu">
      <li><input type="search" placeholder="Search"></li>
      <li><button type="button" class="button">Search</button></li>
    </ul>
  </div>
</div>
```

---

## Responsive Toggle with animation

To use animations from the Motion UI library, include the data-animate="someAnimationIn someAnimationOut" attribute.

Scale your browser down to see the toggle happen.

```html_example
<div class="title-bar" data-responsive-toggle="example-animated-menu" data-hide-for="medium">
  <button class="menu-icon" type="button" data-toggle></button>
  <div class="title-bar-title">Menu</div>
</div>

<div class="top-bar" id="example-animated-menu" data-animate="hinge-in-from-top spin-out">
  <div class="top-bar-left">
    <ul class="dropdown menu" data-dropdown-menu>
      <li class="menu-text">Site Title</li>
      <li>
        <a href="#">One</a>
        <ul class="menu vertical">
          <li><a href="#">One</a></li>
          <li><a href="#">Two</a></li>
          <li><a href="#">Three</a></li>
        </ul>
      </li>
      <li><a href="#">Two</a></li>
      <li><a href="#">Three</a></li>
    </ul>
  </div>
</div>
```

---

### Preventing FOUC

Before the JavaScript on your page loads, you'll be able to see both the mobile and desktop element at once for a brief second. This is known as a [flash of unstyled content](https://en.wikipedia.org/wiki/Flash_of_unstyled_content). There's not an easy way for the framework to handle this for you, but you can add some extra CSS to account for it.

If we reference the above example, `.title-bar` is our mobile element and `.top-bar` is our desktop element. So before the JavaScript loads, we want only the right element for that screen size to be visible.

```css
.no-js .top-bar {
  display: none;
}

@media screen and (min-width: 40em) {
  .no-js .top-bar {
    display: block;
  }

  .no-js .title-bar {
    display: none;
  }
}
```

If you're using Sass, you can write it like this:

```scss
.no-js {
  @include breakpoint(small only) {
    .top-bar {
      display: none;
    }
  }

  @include breakpoint(medium) {
    .title-bar {
      display: none;
    }
  }
}
```


text:
using System;
using System.Collections;

namespace System.DirectoryServices.AccountManagement
{
    // This enum tracks the load state of our principal side data cache.
    // NotSet = default value,
    // Loaded = Value from store was set into cache date, Data in cache matches data in store.
    // Changed = User has modifed the cache value but is has not been pushed to the store yet
    internal enum LoadState
    {
        NotSet = 0,
        Loaded,
        Changed
    }

    // These are the default options used when a user does not specify a context option to connect to the store.
    internal static class DefaultContextOptions
    {
        internal static ContextOptions MachineDefaultContextOption = ContextOptions.Negotiate;
        internal static ContextOptions ADDefaultContextOption = ContextOptions.Negotiate | ContextOptions.Signing | ContextOptions.Sealing;
    }

    internal class LdapConstants
    {
        public static int LDAP_SSL_PORT = 636;
        public static int LDAP_PORT = 389;
        internal static DateTime defaultUtcTime = new DateTime(1601, 1, 1, 0, 0, 0);
        private LdapConstants() { }
    }
    // The string constants used internally to specify each property
    internal class PropertyNames
    {
        private PropertyNames() { }
        // Principal
        internal const string PrincipalDisplayName = "Principal.DisplayName";
        internal const string PrincipalDescription = "Principal.Description";
        internal const string PrincipalSamAccountName = "Principal.SamAccountName";
        internal const string PrincipalUserPrincipalName = "Principal.UserPrincipalName";
        internal const string PrincipalGuid = "Principal.Guid";
        internal const string PrincipalSid = "Principal.Sid";
        internal const string PrincipalIdentityClaims = "Principal.IdentityClaims";
        internal const string PrincipalDistinguishedName = "Principal.DistinguishedName";
        internal const string PrincipalStructuralObjectClass = "Principal.StructuralObjectClass";
        internal const string PrincipalName = "Principal.Name";
        internal const string PrincipalExtensionCache = "Principal.ExtensionCache";

        // AuthenticablePrincipal
        internal const string AuthenticablePrincipalEnabled = "AuthenticablePrincipal.Enabled";
        internal const string AuthenticablePrincipalCertificates = "AuthenticablePrincipal.Certificates";

        // Group
        internal const string GroupIsSecurityGroup = "GroupPrincipal.IsSecurityGroup";
        internal const string GroupGroupScope = "GroupPrincipal.GroupScope";
        internal const string GroupMembers = "GroupPrincipal.Members";

        // User
        internal const string UserGivenName = "UserPrincipal.GivenName";
        internal const string UserMiddleName = "UserPrincipal.MiddleName";
        internal const string UserSurname = "UserPrincipal.Surname";
        internal const string UserEmailAddress = "UserPrincipal.EmailAddress";
        internal const string UserVoiceTelephoneNumber = "UserPrincipal.VoiceTelephoneNumber";
        internal const string UserEmployeeID = "UserPrincipal.EmployeeId";

        // Computer
        internal const string ComputerServicePrincipalNames = "ComputerPrincipal.ServicePrincipalNames";

        // AccountInfo
        internal const string AcctInfoPrefix = "AuthenticablePrincipal.AccountInfo";
        internal const string AcctInfoAcctLockoutTime = "AuthenticablePrincipal.AccountInfo.AccountLockoutTime";
        internal const string AcctInfoLastLogon = "AuthenticablePrincipal.AccountInfo.LastLogon";
        internal const string AcctInfoPermittedWorkstations = "AuthenticablePrincipal.AccountInfo.PermittedWorkstations";
        internal const string AcctInfoPermittedLogonTimes = "AuthenticablePrincipal.AccountInfo.PermittedLogonTimes";
        internal const string AcctInfoExpirationDate = "AuthenticablePrincipal.AccountInfo.AccountExpirationDate";
        internal const string AcctInfoSmartcardRequired = "AuthenticablePrincipal.AccountInfo.SmartcardLogonRequired";
        internal const string AcctInfoDelegationPermitted = "AuthenticablePrincipal.AccountInfo.DelegationPermitted";
        internal const string AcctInfoBadLogonCount = "AuthenticablePrincipal.AccountInfo.BadLogonCount";
        internal const string AcctInfoHomeDirectory = "AuthenticablePrincipal.AccountInfo.HomeDirectory";
        internal const string AcctInfoHomeDrive = "AuthenticablePrincipal.AccountInfo.HomeDrive";
        internal const string AcctInfoScriptPath = "AuthenticablePrincipal.AccountInfo.ScriptPath";
        // This property is not publicly exposed but is used be a ReadOnlySearchFilter.
        internal const string AcctInfoExpiredAccount = "AuthenticablePrincipal.AccountInfoExpired";

        // PasswordInfo
        internal const string PwdInfoPrefix = "AuthenticablePrincipal.PasswordInfo";
        internal const string PwdInfoLastPasswordSet = "AuthenticablePrincipal.PasswordInfo.LastPasswordSet";
        internal const string PwdInfoLastBadPasswordAttempt = "AuthenticablePrincipal.PasswordInfo.LastBadPasswordAttempt";
        internal const string PwdInfoPasswordNotRequired = "AuthenticablePrincipal.PasswordInfo.PasswordNotRequired";
        internal const string PwdInfoPasswordNeverExpires = "AuthenticablePrincipal.PasswordInfo.PasswordNeverExpires";
        internal const string PwdInfoCannotChangePassword = "AuthenticablePrincipal.PasswordInfo.UserCannotChangePassword";
        internal const string PwdInfoAllowReversiblePasswordEncryption = "AuthenticablePrincipal.PasswordInfo.AllowReversiblePasswordEncryption";

        // these two are not publicly exposed properties, but are used internally to track ResetPassword/ExpirePasswordNow
        // operations against unpersisted principals, so that they can be performed once the principal has been Saved
        // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Not a password.")]
        internal const string PwdInfoPassword = "AuthenticablePrincipal.PasswordInfo.Password";
        internal const string PwdInfoExpireImmediately = "AuthenticablePrincipal.PasswordInfo.ExpireImmediately";
    }

    // Given an internal property name (from PropertyNames), returns the external form of the name for use in error-reporting
    internal class PropertyNamesExternal
    {
        private PropertyNamesExternal() { }

        private static int s_acctInfoPrefixLength = PropertyNames.AcctInfoPrefix.Length;
        private static int s_pwdInfoPrefixLength = PropertyNames.PwdInfoPrefix.Length;

        internal static string GetExternalForm(string propertyName)
        {
            if (propertyName.StartsWith(PropertyNames.AcctInfoPrefix, StringComparison.Ordinal))
            {
                return "AuthenticablePrincipal" + propertyName.Substring(s_acctInfoPrefixLength);
            }
            else if (propertyName.StartsWith(PropertyNames.PwdInfoPrefix, StringComparison.Ordinal))
            {
                return "AuthenticablePrincipal" + propertyName.Substring(s_pwdInfoPrefixLength);
            }
            else
            {
                return propertyName;
            }
        }
    }

    // The list of properties considered referential (they refer to or contain Principal objects)
    //
    // At present, referential properties are the following:
    //
    //  Group.Members
    //
    internal class ReferentialProperties
    {
        private ReferentialProperties() { }

        // Maps from Type of the Principal object --> ArrayList of the object's referential property names
        // (expressed as strings from the PropertyNames class)
        internal static readonly Hashtable Properties;

        static ReferentialProperties()
        {
            Properties = new Hashtable();

            // Referential properties for groups
            ArrayList groupList = new ArrayList(1);
            groupList.Add(PropertyNames.GroupMembers);

            Properties[typeof(GroupPrincipal)] = groupList;

            // Referential properties for users
            // None at this time.

            // Referential properties for computers
            // None at this time.
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
 ~ Licensed to the Apache Software Foundation (ASF) under one
 ~ or more contributor license agreements.  See the NOTICE file
 ~ distributed with this work for additional information
 ~ regarding copyright ownership.  The ASF licenses this file
 ~ to you under the Apache License, Version 2.0 (the
 ~ "License"); you may not use this file except in compliance
 ~ with the License.  You may obtain a copy of the License at
 ~
 ~    http://www.apache.org/licenses/LICENSE-2.0
 ~
 ~ Unless required by applicable law or agreed to in writing,
 ~ software distributed under the License is distributed on an
 ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 ~ KIND, either express or implied.  See the License for the
 ~ specific language governing permissions and limitations
 ~ under the License.
 -->
<project basedir="." default="build" name="property-snitch">
    <property environment="env"/>
    <property name="debuglevel" value="source,lines,vars"/>

    <property name="cassandra.dir" value="../.."/>
    <property name="cassandra.lib" value="${cassandra.dir}/lib"/>
    <property name="cassandra.classes" value="${cassandra.dir}/build/classes"/>
    <property name="build.src" value="${basedir}/src/java"/>
    <property name="build.dir" value="${basedir}/build"/>
    <property name="build.classes" value="${build.dir}/classes"/>
    <property name="javadoc.dir" value="${build.dir}/javadoc"/>
    <property name="final.name" value="cassandra-propsnitch"/>

    <!--
	 Add all the dependencies.
    -->
    <path id="cassandra.classpath">
        <pathelement location="${build.classes}"/>
        <pathelement location="${cassandra.classes}"/>
        <fileset dir="${cassandra.lib}">
          <include name="**/*.jar" />
        </fileset>
    </path>

    <!--
	Setup the output directories.
    -->
    <target name="init">
        <mkdir dir="${build.classes}"/>
    </target>

    <target name="clean">
        <delete dir="${build.dir}" />
        <delete dir="${build.classes}" />
    </target>

    <!--
	The build target builds all the .class files
    -->
    <target depends="init" name="build">
        <echo message="${ant.project.name}: ${ant.file}"/>
        <javac debug="true" debuglevel="${debuglevel}" destdir="${build.classes}">
            <src path="${build.src}"/>
            <classpath refid="cassandra.classpath"/>
        </javac>
    </target>

    <!--
	The jar target makes cassandra.jar output.
    -->
    <target name="jar" depends="build">
      <mkdir dir="${build.classes}/META-INF"/>
      <jar jarfile="${build.dir}/${final.name}.jar"
           basedir="${build.classes}">
      </jar>
    </target>

</project>


text:
<?php

namespace Respect\Validation\Rules\SubdivisionCode;

use Respect\Validation\Rules\AbstractSearcher;

/**
 * Validator for Northern Mariana Islands subdivision code.
 *
 * ISO 3166-1 alpha-2: MP
 *
 * @link http://www.geonames.org/MP/administrative-division-northern-mariana-islands.html
 */
class MpSubdivisionCode extends AbstractSearcher
{
    public $haystack = [
        'N', // Northern Islands
        'R', // Rota
        'S', // Saipan
        'T', // Tinian
    ];

    public $compareIdentical = true;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/temples/logan-utah#logan-temple-770701" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">logan-temple-770701</uri-title>
      <source>logan-temple-770701</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>logan</subject>
          <subject>utah</subject>
          <subject>temples</subject>
          <subject>lit up</subject>
          <subject>lights</subject>
          <subject>evening</subject>
          <subject>night</subject>
          <subject>flag</subject>
          <subject>exterior</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/temples/logan-utah/logan-temple-770701-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/temples/logan-utah/logan-temple-770701-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>135 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/logan-utah/logan-temple-770701-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>187 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/logan-utah/logan-temple-770701-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>412 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/logan-utah/logan-temple-770701-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>682 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/temples/logan-utah/logan-temple-770701-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="logan-temple-770701" locale="eng" uri="/media-library/images/temples/logan-utah#logan-temple-770701" status="publish" site="ldsorg" source="chq" words="129" tgp="0.451"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:12.550235-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
package hu.kazocsaba.robust;

import hu.kazocsaba.robust.RobustEstimator.Monitor;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * RECON robust estimator.
 * @see "Rahul Raguram and Jan-Michael Frahm: RECON: Scale-Adaptive Robust Estimation via Residual Consensus
 * (in International Conference on Computer Vision, November 2011)"
 * @param <D> the type of the data elements
 * @param <M> the type of the model
 * @author Kazó Csaba
 */
public final class Recon<D,M> extends RobustEstimator<D, M, Recon.Monitor<D, M>> {
	/** The maximal number the fitter is allowed to fail to generate a model from a minimal data set. */
	private int maxModelFailCount=1000;

	/**
	 * The minimal value required for the commonCount/totalCount for the chunks of the residual elements. In the
	 * article, this is alpha squared.
	 */
	double minOverlapFraction=.99*.99;

	/** The source of randomness. */
	private Random rnd=new Random();;

	/**
	 * Sets the (only) source of randomness used by the algorithm. This function can be used to ensure deterministic
	 * execution: if the configuration of {@code Recon} is not changed, and the same input is provided, then the
	 * behaviour of the algorithm will be exactly the same as long as the calls to {@code perform} are preceded by
	 * setting {@code Random} instances which produce identical sequences of numbers.
	 * @param random the source of randomness this {@code Recon} instance will use
	 */
	public void setRandom(Random random) {
		if (random == null) throw new NullPointerException();
		rnd = random;
	}

	private static class Residual implements Comparable<Residual> {
		public int index;
		public double error;

		public Residual(int index, double error) {
			this.index = index;
			this.error = error;
		}

		@Override
		public int compareTo(Residual o) {
			return Double.compare(error, o.error);
		}
	}

	private class ModelData {
		private List<Residual> residuals;
		private M model;
		private BitSet minimalSampleSet;

		public ModelData(M model, BitSet minimalSampleSet, Fitter<D, M> fitter, List<D> data) {
			this.model = model;
			this.minimalSampleSet = minimalSampleSet;

			residuals=new ArrayList<Residual>(data.size());

			for (int index=0; index<data.size(); index++)
				residuals.add(new Residual(index, fitter.getError(model, data.get(index))));
			Collections.sort(residuals);
		}

	}

	private class MatchingModelPair {
		private ModelData model1, model2;
		private BitSet commonData;

		public MatchingModelPair(ModelData model1, ModelData model2, BitSet commonData) {
			this.model1 = model1;
			this.model2 = model2;
			this.commonData = commonData;
		}

	}

	/**
	 * Monitor class for {@link Recon}.
	 *

	 * The algorithm iteratively generates minimal sample sets, then fits a model to them. For each of these steps,
	 * {@link #modelFromMinimalSampleSet(BitSet, Object)} is called with the model the fitter returned, possibly
	 * {@code null}.
	 *

	 * Then this new model is checked with each of the previously generated ones for alpha-consistency. If an existing
	 * model is found to be consistent with the new one, then {@link #modelPairConsistent(Object, Object, BitSet)} is
	 * called, otherwise {@link #modelPairNotConsistent(Object, Object, BitSet)}.
	 *
	 *

	 * The search terminates successfully when three mutually consistent models are found. This is indicated by a call to
	 * {@link Monitor#success(Object, BitSet)} with the common consistent data as the inlier set and the final model.
	 *

	 * This class and provides its functions with empty implementations, so that subclasses only need
	 * to implement the ones they are interested in.
	 * @param <D> the type of the data elements
	 * @param <M> the type of the model
	 */
	public static class Monitor<D,M> extends RobustEstimator.Monitor<D,M> {
		/**
		 * Called for each random minimal data set the algorithm generates, and the model which the fitter computes from
		 * it.
		 * @param samples the minimal sample set
		 * @param model the model computed by the fitter; may be {@code null}
		 */
		public void modelFromMinimalSampleSet(BitSet samples, M model) {}

		/**
		 * Called after a new model has been found consistent with a previous one.
		 * @param newModel the new model
		 * @param existingModel the existing model consistent with the new one
		 * @param consistentData bit set representing the data elements indicating consistency
		 */
		public void modelPairConsistent(M newModel, M existingModel, BitSet consistentData) {}
		/**
		 * Called after a new model has been found inconsistent with a previous one.
		 * @param newModel the new model
		 * @param existingModel the existing model (not consistent with the new one)
		 * @param consistentData bit set representing the data elements indicating consistency
		 */
		public void modelPairNotConsistent(M newModel, M existingModel, BitSet consistentData) {}
	}

	@Override
	public M perform(Fitter<D, M> fitter, List<D> data, Monitor<D, M> monitor) throws NoModelFoundException {
		{
			M bestModel=performCheck(fitter, data, monitor);
			if (bestModel!=null) return bestModel;
		}

		List<D> samples=new ArrayList<D>(data.size()/2);
		BitSet sampleMask=new BitSet(data.size());
		int modelFailCount=0; // the number of random sample sets which failed to yield a model

		Map<BitSet, ModelData> storedModelData=new HashMap<BitSet, ModelData>();
		Collection<MatchingModelPair> matchingModelPairs=new ArrayList<MatchingModelPair>();

		for (int tries=0; tries<200; tries++) {

			// generate a random sample set

			samples.clear();
			sampleMask.clear();
			while (samples.size()<fitter.getMinimalDataSetSize()) {
				int index=rnd.nextInt(data.size());
				if (!sampleMask.get(index)) {
					samples.add(data.get(index));
					sampleMask.set(index);
				}
			}

			if (storedModelData.containsKey(sampleMask))
				// we've already tried this sample set
				continue;

			// try to compute a model

			M model=fitter.computeModel(samples);
			if (monitor!=null)
				monitor.modelFromMinimalSampleSet(sampleMask, model);

			if (model==null) {
				modelFailCount++;
				if (modelFailCount==maxModelFailCount)
					throw new NoModelFoundException("Fitter failed to compute a model from a minimal data set too many times");
			} else {
				// compute and sort the residuals

				ModelData newModelData=new ModelData(model, (BitSet)sampleMask.clone(), fitter, data);

				// check previous models for overlap

				Map<ModelData, BitSet> matchingPreviousModels=new HashMap<ModelData, BitSet>(); // value is the common inlier set

				for (ModelData existingModelData: storedModelData.values()) {
					if (newModelData.minimalSampleSet.equals(existingModelData.minimalSampleSet)) {
						// these are from the same input sets, don't compare them
						continue;
					}
					checkAlphaConsistency(newModelData, existingModelData, matchingPreviousModels, monitor);
				}

				if (!matchingPreviousModels.isEmpty()) {
					/*
					 * At least one previous model was found which matches with the new one.
					 * We're trying to find a set of 3 mutually matching models. So we check all existing pairs to see if
					 * both match the current one.
					 */
					for (MatchingModelPair existingPair: matchingModelPairs) {
						if (matchingPreviousModels.containsKey(existingPair.model1) && matchingPreviousModels.containsKey(existingPair.model2)) {
							// There you go!
							BitSet commonBetweenNewAnd1=matchingPreviousModels.get(existingPair.model1);
							BitSet commonBetweenNewAnd2=matchingPreviousModels.get(existingPair.model2);

							BitSet commonBetweenAllThree=(BitSet)existingPair.commonData.clone();
							commonBetweenAllThree.and(commonBetweenNewAnd1);
							commonBetweenAllThree.and(commonBetweenNewAnd2);

							int maxCommonCount=Math.max(Math.max(commonBetweenNewAnd1.cardinality(), commonBetweenNewAnd2.cardinality()), existingPair.commonData.cardinality());
							int minCommonCount=Math.min(Math.min(commonBetweenNewAnd1.cardinality(), commonBetweenNewAnd2.cardinality()), existingPair.commonData.cardinality());

							if ((maxCommonCount-minCommonCount)/(double)maxCommonCount<=.05 &&
									commonBetweenAllThree.cardinality()>=.02*data.size()) {
								// Overlap is okey, we're done!

								List<D> commonData=new ArrayList<D>(commonBetweenAllThree.cardinality());
								for (int i=commonBetweenAllThree.nextSetBit(0); i>=0; i=commonBetweenAllThree.nextSetBit(i+1))
									commonData.add(data.get(i));
								M inlierModel=fitter.computeModel(commonData);
								if (inlierModel==null)
									inlierModel=model;
								if (monitor!=null)
									monitor.success(inlierModel, commonBetweenAllThree);
								return inlierModel;
							}
						}
					}
				}

				// store the stuff
				storedModelData.put(newModelData.minimalSampleSet, newModelData);
				for (Map.Entry<ModelData, BitSet> matchingModel: matchingPreviousModels.entrySet()) {
					matchingModelPairs.add(new MatchingModelPair(newModelData, matchingModel.getKey(), matchingModel.getValue()));
				}
			}
		}
		throw new NoModelFoundException("Maximum attempt count reached, no consensus");
	}
	/**
	 * This function checks two models for alpha-consistency, and if they are found to be consistent, stores the existing
	 * model and the corresponding consistent data set in the {@code matchingPreviousModel} map.
	 */
	private void checkAlphaConsistency(
			ModelData newModelData,
			ModelData existingModelData,
			Map<ModelData, BitSet> matchingPreviousModel,
			Monitor<D,M> monitor) {
		// check progressively greater chunks of the residuals, watch the overlap
		int dataSize=newModelData.residuals.size();

		BitSet seenInOneModel=new BitSet(dataSize);
		BitSet seenInBothModels=new BitSet(dataSize);
		int commonPointCount=0;
		boolean consistent=false;

		for (int n=0; n<dataSize; n++) {
			// chunk 0..n
			int residualIndex1=newModelData.residuals.get(n).index;
			int residualIndex2=existingModelData.residuals.get(n).index;
			if (residualIndex1==residualIndex2) {
				// the n-th element is the same
				seenInOneModel.set(residualIndex1);
				seenInBothModels.set(residualIndex1);
			} else {
				// different elements
				if (seenInOneModel.get(residualIndex1)) {
					// we've encountered the point from chunk 1 before, in chunk 2
					seenInBothModels.set(residualIndex1);
					commonPointCount++;
				} else {
					// n-th point of chunk 1 is new
					seenInOneModel.set(residualIndex1);
				}
				if (seenInOneModel.get(residualIndex2)) {
					// we've encountered the point from chunk 2 before, in chunk 1
					seenInBothModels.set(residualIndex2);
					commonPointCount++;
				} else {
					// n-th point of chunk 2 is new
					seenInOneModel.set(residualIndex2);
				}
			}

			// okey, chunk 0..n has been processed
			double chunkSize=n+1;
			if (commonPointCount/chunkSize>=minOverlapFraction) {
				if (chunkSize/dataSize<.9 && chunkSize/dataSize>.1) {
					// these two models match with regard to the residuals
					consistent=true;
					break;
				}
			}
		}
		if (consistent) {
			matchingPreviousModel.put(existingModelData, seenInBothModels);
			if (monitor!=null)
				monitor.modelPairConsistent(newModelData.model, existingModelData.model, seenInBothModels);
		} else {
			if (monitor!=null)
				monitor.modelPairNotConsistent(newModelData.model, existingModelData.model, null);
		}
	}

}


text:
'use strict';

function isObject(value: mixed) {
  return (
    value !== null &&
    Object.prototype.toString.call(value) === '[object Object]'
  );
}

/**
 * Simple recursive stringifier that handles basic objects (does not handle
 * corner cases such as circular references) and produces a JSON-like
 * serialization suitable for use as a cache key or other similar internal
 * book-keeping detail.
 *
 * Sample input:
 *
 *     var object = {
 *       top2: {
 *         middle: {
 *           inner: [1, 'foo', ['bar', 2]],
 *           other: false,
 *         },
 *       },
 *       top1: [
 *         {first: true},
 *         {first: false},
 *         'random',
 *       ],
 *       misc: true,
 *       extra: null,
 *     };
 *
 * Sample output (some whitespace added for clarity):
 *
 *    {
 *      extra:null,
 *      misc:true,
 *      top1:[0:{first:true},1:{first:false},2:"random"],
 *      top2:{middle:{inner:[0:1,1:"foo",2:[0:"bar",1:2]],other:false}}
 *    }
 */
function stableStringify(input: any): string {
  const inputIsArray = Array.isArray(input);
  const inputIsObject = isObject(input);
  if (inputIsArray || inputIsObject) {
    var keys = Object.keys(input);
    if (keys.length) {
      var result = [];
      keys.sort();

      for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var value = input[key];
        if (isObject(value) || Array.isArray(value)) {
          value = stableStringify(value);
        } else {
          value = JSON.stringify(value);
        }
        result.push(key + ':' + value);
      }

      if (inputIsArray) {
        return '[' + result.join(',') + ']';
      } else {
        return '{' + result.join(',') + '}';
      }
    }
  }
  return JSON.stringify(input);
}

module.exports = stableStringify;