text:
import io
import os
import re
import operator
import sys
import base64
import time

from IOST_Prepare              import IOST_Prepare
from IOST_Config               import *
from IOST_AboutDialog          import *
from IOST_WRun                 import *
from IOST_Basic                import *
from IOST_LoadConfigFileDialog import *

import gtk
import gobject
import gtk.glade

from IOST_WMain_StationInfo    import *
from IOST_WMain_LoadConfigFile import *
from IOST_WMain_I2C            import *
from IOST_WMain_SPI            import *
from IOST_WMain_UART           import *
from IOST_WMain_USB            import *
from IOST_WMain_SATA           import *
from IOST_WMain_PCIE           import *
from IOST_WMain_ETH            import *
from IOST_WMain_AutoMail       import *
from IOST_WMain_CTRL           import *

#======================================================================
class IOST_WMain(IOST_Config,
IOST_WMain_StationInfo,
IOST_WMain_LoadConfigFile,
IOST_WMain_I2C,
IOST_WMain_SPI,
IOST_WMain_UART,
IOST_WMain_USB,
IOST_WMain_SATA,
IOST_WMain_PCIE,
IOST_WMain_ETH,
IOST_WMain_CTRL,
IOST_WMain_AutoMail,
IOST_AboutDialog,
IOST_LoadConfigFileDialog,
IOST_WRun):
    def __init__(self, glade_filename, window_name, config_data, config_objs):
        """
        """
        # self.IOST_WMain_Config = config_data
        if os.path.isfile(glade_filename):
            self.IOST_WMain_GladeFile = glade_filename
        else:
            self.IOST_WMain_GladeDir = os.path.dirname(sys.argv[0])
            self.IOST_WMain_GladeFile = os.path.join(self.IOST_GladeDir, glade_filename)

        IOST_Config.__init__(self)

        self.ConfigData = config_data
        self.ConfigObjs = config_objs

        #------------------------------------
        # Get WMain window from glade file
        self.GetWMain_Obj(self.IOST_WMain_GladeFile, window_name)

        #------------------------------------
        IOST_WMain_StationInfo.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetStationInfo_Obj("IOST_WMain")
        self.InitStationInfo_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_LoadConfigFile.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetLoadConfigFile_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_I2C.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetI2C_Obj("IOST_WMain")
        self.InitI2C_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_SPI.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetSPI_Obj("IOST_WMain")
        self.InitSPI_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_UART.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetUART_Obj("IOST_WMain")
        self.InitUART_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_USB.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetUSB_Obj("IOST_WMain")
        self.InitUSB_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_SATA.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetSATA_Obj("IOST_WMain")
        self.InitSATA_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_PCIE.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetPCIE_Obj("IOST_WMain")
        self.InitPCIE_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_ETH.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetETH_Obj("IOST_WMain")
        self.InitETH_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_AutoMail.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetAutoMail_Obj("IOST_WMain")
        self.InitAutoMail_Obj("IOST_WMain")

        #------------------------------------
        IOST_WMain_CTRL.__init__(self, self.IOST_WMain_GladeFile, "IOST_WMain", self.IOST_WMain_Builder)
        self.GetCTRL_Obj("IOST_WMain")

        #------------------------------------
        self.IOST_WMain_Show()

    #----------------------------------------------------------------------
    def GetWMain_Obj(self, glade_filename, window_name):
        """
        """
        self.IOST_WMain_Builder = gtk.Builder()
        self.IOST_WMain_Builder.add_from_file(glade_filename)
        self.IOST_WMain_Builder.connect_signals(self)

        self.ConfigObjs[window_name]["WMain_Obj"] = self.IOST_WMain_Builder.get_object(window_name)

    #----------------------------------------------------------------------
    def IOST_WMain_Show(self):
        self.ConfigObjs["IOST_WMain"]["WMain_Obj"].show()

    #----------------------------------------------------------------------
    def on_IOST_Wmain_MenuHelp_About_activate(self, object, data=None):
        IOST_AboutDialog.__init__(self, self.IOST_WMain_GladeFile, self.ConfigObjs["IOST_WHelpAbout"]["WHelpAbout_Name"],
                                  self.IOST_WMain_Builder)
        IOST_AboutDialog.Run(self, "IOST_WHelpAbout")

    #----------------------------------------------------------------------
    """
    def on_IOST_WMain_destroy(self, object, data=None):
        pass
    """

    #----------------------------------------------------------------------
    def IOST_WMain_Confirm_Exit(self, object, event, data=None):
        "Display a Diaglog confirm to exit Main Window"

        Basic = IOST_Basic()
        # IOST_Basic=IOST_Basic()
        Response = Basic.MsgConfirm('Close the IOST Main Window')

        return Response

    #----------------------------------------------------------------------
    def on_IOST_WMain_MenuFile_Quit_activate(self, object, data=None):
        "Exit with from File -> Exit"
        Response = self.IOST_WMain_Confirm_Exit(object, object, data)
        if Response == gtk.RESPONSE_OK:
            gtk.main_quit()

    #----------------------------------------------------------------------
    def on_IOST_WMain_delete_event(self, object, event, data=None):
        ""
        Response = self.IOST_WMain_Confirm_Exit(object, event, data)
        if Response == gtk.RESPONSE_OK:
            gtk.main_quit()
            return False
        else:
            return True

    #----------------------------------------------------------------------
    def on_IOST_WMain_destroy_event(self, object, data=None):
        ""
        Response = self.IOST_WMain_Confirm_Exit(object, event, data)
        if Response == gtk.RESPONSE_OK:
            gtk.main_quit()

    #----------------------------------------------------------------------
    def delete_event(self, widget, data=None):
        "Exit by delete even"
        pass
        # return False
        # gtk.main_quit()

#======================================================================


text:
'use strict';

var utils = require('../../src/utils');

describe('Response utils', function () {

  var res = {
    success: {
      statusCode: 200,
      body: {
        data: {
          foo: 'bar'
        }
      }
    },
    error: {
      statusCode: 400,
      body: {
        error: {
          message: 'err'
        }
      }
    }
  };

  describe('#parse', function () {

    it('returns the response body', function () {
      expect(utils.parse.call(null, res.success, {})).to.equal(res.success.body);
    });

    it('can extract a deep property from the body', function () {
      expect(utils.parse.call(null, res.success, {
        dataProperty: 'data'
      })).to.equal(res.success.body.data);
    });

  });

  describe('#catch', function () {

    describe('response.statusCode < 400', function () {

      it('is a no-op', function () {
        expect(utils.catch.bind(null, res.success, {})).to.not.throw();
      });

    });

    describe('utils.statusCode > 399', function () {

      it('throws a ResponseError', function () {
        expect(utils.catch.bind(null, res.error, {})).to.throw(utils.ResponseError);
      });

      it('appends the statusCode to the error', function () {
        expect(utils.catch.bind(null, res.error, {})).to.throw(sinon.match.has('statusCode', 400));
      });

      it('appends the body to the error', function () {
        expect(utils.catch.bind(null, res.error, {})).to.throw(sinon.match.has('body', res.error.body));
      });

      it('can deep extract an error message using dot notation', function () {
        expect(utils.catch.bind(null, res.error, {errorProperty: 'error.message'})).to.throw('err');
      });

      it('falls back to a statusCode dictionary name', function () {
        expect(utils.catch.bind(null, res.error, {})).to.throw('Bad Request');
      });

    });

  });

});

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * GENERATED CODE WARNING
 * Generated by gapic-generator-php from the file
 * https://github.com/googleapis/googleapis/blob/master/google/cloud/compute/v1/compute.proto
 * Updates to the above are reflected here through a refresh process.
 */

namespace Google\Cloud\Compute\V1\Enums\RouterBgpPeer;

/**
 * AdvertiseMode contains string constants that represent the names of each value
 * in the google.cloud.compute.v1.RouterBgpPeer.AdvertiseMode descriptor.
 */
class AdvertiseMode
{
    const UNDEFINED_ADVERTISE_MODE = 'UNDEFINED_ADVERTISE_MODE';

    const CUSTOM = 'CUSTOM';

    const DEFAULT = 'DEFAULT';
}


text:
package com.hazelcast.internal.metrics;

import com.hazelcast.internal.metrics.collectors.MetricsCollector;

import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * The MetricsRegistry is a registry of various Hazelcast/JVM internal
 * information to help out with debugging, performance or stability issues.
 * Each HazelcastInstance has one local MetricsRegistry instance.
 *

 * A MetricsRegistry can contain many {@link Probe} instances. A probe is
 * registered under a name, and can be read by creating a {@link Gauge}, see
 * {@link #newLongGauge(String)}.
 *

 * The metrics registry doesn't interpret the name in any way, it is treated as
 * is. For example, {@code [tag1=foo,tag2=bar]} and {@code [tag2=bar,tag1=foo]}
 * will be treated as two different metrics even though they have same tags and
 * values. Clients making use of the metrics can use the tags. For backwards
 * compatibility, the name does not have to be enclosed in {@code []}.
 *
 *
Duplicate Registrations
 The MetricsRegistry is lenient regarding
 * duplicate registrations of probes. So if there is an existing probe for a
 * given name and a new probe with the same name is registered, the old probe
 * is overwritten. The reason to be lenient is that the MetricRegistry should
 * not throw exception. Of course, there will be a log warning.
 *
 *
Performance
 The MetricRegistry is designed for low overhead probes.
 * So once a probe is registered, there is no overhead for the provider of the
 * probe data. The provider could have for example a volatile long field and
 * increment this using a lazy-set. As long as the MetricRegistry can
 * frequently read out this field, the MetricRegistry is perfectly happy with
 * such low overhead probes. So it is up to the provider of the probe how much
 * overhead is required.
 *
 *
Static and dynamic metrics
 The MetricRegistry collects metrics
 * from static and dynamic metrics sources, these metrics are referred to as
 * static and dynamic metrics.
 *

 * The static metrics are the ones that are registered once and cannot be
 * removed during the lifetime of the given Hazelcast instance. These are
 * typically system metrics either Hazelcast or JVM/OS ones.
 *

 * The dynamic metrics are collected dynamically during each collection cycle
 * via the {@link DynamicMetricsProvider} interface. Typical examples for the
 * dynamic metrics are the metrics exposed by the distributed data structures
 * that can be created and destroyed dynamically.
 *

 * The MetricsRegistry doesn't cache the dynamic metrics, therefore the dynamic
 * metrics don't increase the heap live set. In exchange, they may allocate
 * during the collection cycle. It is therefore the responsibility of the
 * dynamic metric sources to keep allocation low.
 */
public interface MetricsRegistry {

    /**
     * Returns the minimum ProbeLevel this MetricsRegistry is recording.
     */
    ProbeLevel minimumLevel();

    /**
     * Creates a {@link LongGauge} for a given metric name.
     *
     * If no gauge exists for the name, it will be created but no probe is set.
     * The reason to do so is that you don't want to depend on the order of
     * registration. Perhaps you want to read out e.g. operations.count gauge,
     * but the OperationService has not started yet and the metric is not yet
     * available. Another cause is that perhaps a probe is not registered, but
     * the metric is created. For example when experimenting with a new
     * implementation, e.g. a new OperationService implementation, that doesn't
     * provide the operation.count probe.
     *
     * Multiple calls with the same name return different Gauge instances; so
     * the Gauge instance is not cached. This is done to prevent memory leaks.
     *
     * @param name the name of the metric.
     * @return the created LongGauge.
     * @throws NullPointerException if name is null.
     */
    LongGauge newLongGauge(String name);

    /**
     * Creates a {@link DoubleGauge} for a given metric name.
     *
     * @param name name of the metric
     * @return the create DoubleGauge
     * @throws NullPointerException if name is null.
     * @see #newLongGauge(String)
     */
    DoubleGauge newDoubleGauge(String name);

    /**
     * Gets a set of all current probe names.
     *
     * The returned set is immutable and is a snapshot of the names. So the
     * reader gets a stable view on the names.
     *
     * @return set of all current names.
     */
    Set<String> getNames();

    /**
     * Scans the source object for any fields/methods that have been annotated
     * with {@link Probe} annotation, and registers these fields/methods as
     * static probe instances.
     *

     * If a probe is called 'queueSize' and the namePrefix is 'operations',
     * then the name of the probe instance is 'operations.queueSize'.
     *

     * If a probe with the same name already exists, then the probe is replaced.
     *

     * If an object has no @Probe annotations, the call is ignored.
     *
     * @param source     the object to scan.
     * @param namePrefix the name prefix.
     * @throws NullPointerException     if namePrefix or source is null.
     * @throws IllegalArgumentException if the source contains a Probe
     *      annotation on a field/method of unsupported type.
     */
    <S> void registerStaticMetrics(S source, String namePrefix);

    /**
     * Scans the source object for any fields/methods that have been annotated
     * with {@link Probe} annotation, and registers these fields/methods as
     * static probe instances.
     *

     * If a probe is called 'queueSize' and the namePrefix is 'operations',
     * then the name of the probe instance is 'operations.queueSize'.
     *

     * If a probe with the same name already exists, then the probe is replaced.
     *

     * If an object has no @Probe annotations, the call is ignored.
     *
     * @param descriptor the metric descriptor.
     * @param source the object to scan.
     * @throws NullPointerException     if namePrefix or source is null.
     * @throws IllegalArgumentException if the source contains a Probe
     *                                  annotation on a field/method of unsupported type.
     */
    <S> void registerStaticMetrics(MetricDescriptor descriptor, S source);

    /**
     * Registers dynamic metrics sources that collect metrics in each metrics
     * collection cycle.
     *
     * @param metricsProvider The object that provides dynamic metrics
     */
    void registerDynamicMetricsProvider(DynamicMetricsProvider metricsProvider);

    /**
     * Deregisters the given dynamic metrics provider. The metrics collection
     * cycles after this call will not call the given metrics provider until
     * it is registered again.
     *
     * @param metricsProvider The metrics provider to deregister
     */
    void deregisterDynamicMetricsProvider(DynamicMetricsProvider metricsProvider);

    /**
     * Registers a probe.
     *
     * If a probe for the given name exists, it will be overwritten.
     *
     * @param source   the object that the probe function to be used with
     * @param name     the name of the probe
     * @param level    the ProbeLevel
     * @param unit     the unit
     * @param function the probe function
     * @throws NullPointerException if source, name, level or probe is null.
     */
    <S> void registerStaticProbe(S source, MetricDescriptor descriptor, String name, ProbeLevel level, ProbeUnit unit,
                                 ProbeFunction function);

    /**
     * Registers a probe.
     *
     * If a probe for the given name exists, it will be overwritten.
     *
     * @param source   the object that the probe function to be used with
     * @param name     the name of the probe.
     * @param level    the ProbeLevel
     * @param function the probe
     * @throws NullPointerException if source, name, level or probe is null.
     */
    <S> void registerStaticProbe(S source, String name, ProbeLevel level, LongProbeFunction<S> function);

    /**
     * Registers a probe.
     *
     * If a probe for the given name exists, it will be overwritten.
     *
     * @param source the object that the probe function to be used with
     * @param name   the name of the probe.
     * @param level  the ProbeLevel
     * @param unit   the unit
     * @param probe  the probe
     * @throws NullPointerException if source, name, level or probe is null.
     */
    <S> void registerStaticProbe(S source, String name, ProbeLevel level, ProbeUnit unit, LongProbeFunction<S> probe);

    /**
     * Registers a probe.
     *
     * If a probe for the given name exists, it will be overwritten.
     *
     * @param source the object that the probe function to be used with
     * @param name   the name of the probe.
     * @param level  the ProbeLevel
     * @param unit   the unit
     * @param probe  the probe
     * @throws NullPointerException if source, name, level or probe is null.
     */
    <S> void registerStaticProbe(S source, MetricDescriptor descriptor, String name, ProbeLevel level, ProbeUnit unit,
                                 LongProbeFunction<S> probe);

    /**
     * Registers a probe.
     *
     * If a probe for the given name exists, it will be overwritten.
     *
     * @param source   the object that the probe function to be used with
     * @param name  the name of the probe
     * @param level the ProbeLevel
     * @param probe the probe
     * @throws NullPointerException if source, name, level or probe is null.
     */
    <S> void registerStaticProbe(S source, String name, ProbeLevel level, DoubleProbeFunction<S> probe);

    /**
     * Registers a probe.
     *
     * If a probe for the given name exists, it will be overwritten.
     *
     * @param source the object that the probe function to be used with
     * @param name   the name of the probe
     * @param level  the ProbeLevel
     * @param unit   the unit
     * @param probe  the probe
     * @throws NullPointerException if source, name, level or probe is null.
     */
    <S> void registerStaticProbe(S source, String name, ProbeLevel level, ProbeUnit unit, DoubleProbeFunction<S> probe);

    /**
     * Registers a probe.
     *
     * If a probe for the given name exists, it will be overwritten.
     *
     * @param source the object that the probe function to be used with
     * @param name   the name of the probe
     * @param level  the ProbeLevel
     * @param unit   the unit
     * @param probe  the probe
     * @throws NullPointerException if source, name, level or probe is null.
     */
    <S> void registerStaticProbe(S source, MetricDescriptor descriptor, String name, ProbeLevel level, ProbeUnit unit,
                                 DoubleProbeFunction<S> probe);

    /**
     * Schedules a publisher to be executed at a fixed rate.
     *
     * Probably this method will be removed in the future, but we need a mechanism
     * for complex gauges that require some calculation to provide their values.
     *
     * @param publisher the published task that needs to be executed
     * @param period    the time between executions
     * @param timeUnit  the time unit for period
     * @param probeLevel the ProbeLevel publisher it publishing on. This is needed to prevent scheduling
     *                   publishers if their probe level isn't sufficient.
     * @throws NullPointerException if publisher or timeUnit is null.
     * @return the ScheduledFuture that can be used to cancel the task, or null if nothing got scheduled.
     */
    ScheduledFuture<?> scheduleAtFixedRate(Runnable publisher, long period, TimeUnit timeUnit, ProbeLevel probeLevel);

    /**
     * Collects the content of the MetricsRegistry.
     *
     * @param collector the collector that consumes the metrics collected
     * @throws NullPointerException if collector is null.
     */
    void collect(MetricsCollector collector);

    /**
     * For each object that implements {@link StaticMetricsProvider} the
     * {@link StaticMetricsProvider#provideStaticMetrics(MetricsRegistry)} is called.
     *
     * @param providers the array of objects to initialize.
     */
    void provideMetrics(Object... providers);

    /**
     * Creates a new {@link MetricDescriptor}.
     */
    MetricDescriptor newMetricDescriptor();

}


text:
const env = require('node-env-file');
env(__dirname + '/.env');

const AbbottFramework = require('../').AbbottFramework;
const IntentFlowHandler = require('../').IntentFlowHandler;
const logger = require('../').logging();

var abbottConfig = {
  botName: 'abbott-gchats-sample',
  botFirendlyName: 'Abbott Google Chats Sample',
  port: process.env.PORT || 3000,
  platforms: {
    gchats: {
      verify_token: process.env.GCHATS_VERIFY_TOKEN || '[YOUR_ABBOTT_VERIFY_TOKEN]',
      chats_regex: process.env.GCHATS_CHATS_REGEX || '[GOOGLE_CHATS_REGEX]'
    }
  },
  nlp: {
    apiai: {
      token: process.env.NLP_DIALOGFLOW_TOKEN || '[YOUR_API.AI_DEVELOPER_TOKEN]'
    }
  }
};

try {
  const abbottFramework = new AbbottFramework(abbottConfig);

  abbottFramework.start()
    .then(() => {
      logger.info('BOT Initialized!');
    })
    .catch((err) => logger.error(err));
}
catch (err) {
  logger.error(err);
  process.exit(1);
}


text:
<?xml version="1.0"?>
<properties>
  <Files/>
  <LastModified>20060717205901</LastModified>
  <Properties/>
  <RecentChanges/>
  <Refactor/>
  <Suite/>
  <Versions/>
  <WhereUsed/>
</properties>


text:
<head>
  <title>John Wong</title>
  <meta content="John Wong" name="author">

  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.7.2/jquery.fullPage.css" />
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.7.2/jquery.fullPage.min.js"></script>

</head>


text:
namespace mtl { namespace vector {

// Model of VectorExpression
template <class E1, class E2>
struct vec_vec_plus_asgn_expr
  : public vec_vec_aop_expr< E1, E2, mtl::sfunctor::plus_assign<typename E1::value_type, typename E2::value_type> >
{
    typedef vec_vec_aop_expr< E1, E2, mtl::sfunctor::plus_assign<typename E1::value_type, typename E2::value_type> > base;
    vec_vec_plus_asgn_expr( E1& v1, E2 const& v2 )
      : base( v1, v2 )
    {}
};

} } // Namespace mtl::vector

#endif


text:
// Note: This include ordering is important!
#include "VRVRPNTrackerDevice.h"

#include <vrpn_Tracker.h>
#include <quat.h>

#include <math/VRMath.h>

#include <iostream>
using namespace std;

namespace MinVR {

#ifndef VRPN_CALLBACK
#define VRPN_CALLBACK
#endif

// Callback function for VRPN, void* pointer points to a VRPNTrackerDevice
void VRPN_CALLBACK trackerHandler(void *thisPtr, const vrpn_TRACKERCB info)
{
    double rotraw[16];
    q_to_ogl_matrix(rotraw, info.quat);
    float rotrawf[16];
    for (int i=0; i<16; i++) {
        rotrawf[i] = (float)rotraw[i];
    }
    VRMatrix4 vrpnEvent(rotrawf);
    vrpnEvent(0,3) = info.pos[0];
    vrpnEvent(1,3) = info.pos[1];
    vrpnEvent(2,3) = info.pos[2];

	VRVRPNTrackerDevice* device = ((VRVRPNTrackerDevice*)thisPtr);
	device->processEvent(vrpnEvent, info.sensor);
}

VRVRPNTrackerDevice::VRVRPNTrackerDevice(
	const std::string              &vrpnTrackerDeviceName,
	const std::vector<std::string> &eventsToGenerate,
	const double                   &trackerUnitsToRoomUnitsScale,
	const VRMatrix4                &deviceToRoom,
	const std::vector<VRMatrix4>   &propToTracker,
	const std::vector<VRMatrix4>   &finalOffset,
	const bool                     &waitForNewReportInPoll,
	const bool                     &convertLHtoRH,
	const bool                     &ignoreZeroes)
{
	_eventNames                   = eventsToGenerate;
	_trackerUnitsToRoomUnitsScale = trackerUnitsToRoomUnitsScale;
	_deviceToRoom                 = deviceToRoom;
	_propToTracker                = propToTracker;
	_finalOffset                  = finalOffset;
	_waitForNewReport             = waitForNewReportInPoll;
	_convertLHtoRH                = convertLHtoRH;
	_ignoreZeroes                 = ignoreZeroes;
	_printSensor0                 = false;

	_vrpnDevice = new vrpn_Tracker_Remote(vrpnTrackerDeviceName.c_str());
	if (!_vrpnDevice)
	{
		std::stringstream ss;
		ss << "Can't create VRPN Remote Tracker with name " + vrpnTrackerDeviceName;
		std::cout << ss.str() << std::endl;
		//MinVR::Logger::getInstance().assertMessage(_vrpnDevice, ss.str().c_str());
	}
	_vrpnDevice->register_change_handler(this, trackerHandler);
}

VRVRPNTrackerDevice::~VRVRPNTrackerDevice()
{
}

/**
The tracker reports the transformation that would transform stuff
in tracker space to device space (that is, to the space relative to
the origin of the tracking device).  First we change the units on
the translation part of this since we usually work in feet and most
tracking systems report mesurements in some metric system.  Then we
have a transformation in feet relative to the device.  We multiply
by a transformation that transforms stuff in device space to IS3D
room space.  You can think of this as what rotation, then
translation would move the origin of RoomSpace to the origin of
tracking device.  This is the deviceToRoom coordinate frame.
*/
void VRVRPNTrackerDevice::processEvent(const VRMatrix4 &vrpnEvent, int sensorNum)
{

    if ((_ignoreZeroes) && (vrpnEvent.getColumn(3) == VRVector3(0,0,0))) {
    	return;
	}
	_newReportFlag = true;

	// first, adjust units of trackerToDevice.  after this, everything
	// is in RoomSpace units (typically feet for VRG3D).
	VRMatrix4 trackerToDevice = vrpnEvent;

	// convert a left handed coordinate system to a right handed one
	// not sure if this actually works..
	if (_convertLHtoRH) {
		/*** This is code from syzygy..
		CoordinateFrame switchMat(Matrix3(1,0,0, 0,0,1, 0,-1,0), Vector3::zero());
		CoordinateFrame transMat(switchMat.inverse() * vrpnEvent.translation);
		CoordinateFrame rotMat(vrpnEvent.rotation, Vector3::zero());
		trackerToDevice = transMat * switchMat.inverse() * rotMat * switchMat;
		***/

		// This code is based on the article "Conversion of Left-Handed
		// Coordinates to Right-Handed Coordinates" by David Eberly,
		// available online:
		// http://www.geometrictools.com/Documentation/LeftHandedToRightHanded.pdf
		trackerToDevice(2,3) = -trackerToDevice(2,3);

		trackerToDevice(0,2) = -trackerToDevice(0,2);
		trackerToDevice(1,2) = -trackerToDevice(1,2);
        trackerToDevice(2,0) = -trackerToDevice(2,0);
		trackerToDevice(2,1) = -trackerToDevice(2,1);
	}

	trackerToDevice(0,3) *= _trackerUnitsToRoomUnitsScale;
	trackerToDevice(1,3) *= _trackerUnitsToRoomUnitsScale;
	trackerToDevice(2,3) *= _trackerUnitsToRoomUnitsScale;

	VRMatrix4 eventRoom = _finalOffset[sensorNum] * _deviceToRoom * trackerToDevice * _propToTracker[sensorNum];

	if ((_printSensor0) && (sensorNum == 0)) {
        VRVector3 translation = eventRoom.getColumn(3);
		std::cout << translation << std::endl;
	}

	VRDataIndex di;
    std::string name = getEventName(sensorNum) + "_Move";
	di.addData(name + "/Transform", eventRoom);
    _pendingEvents.push(di.serialize(name));
}

std::string VRVRPNTrackerDevice::getEventName(int trackerNumber)
{
  if (trackerNumber >= (int)_eventNames.size())
		return std::string("VRPNTrackerDevice_Unknown_Event");
	else
		return _eventNames[trackerNumber];
}

void VRVRPNTrackerDevice::appendNewInputEventsSinceLastCall(VRDataQueue *inputEvents)
{
  // If this poll routine isn't called fast enough then the UDP buffer can fill up and
  // the most recent tracker records will be dropped, introducing lag in the system.
  // A workaround suggested by the VRPN website is to keep calling mainloop() until you
  // get a new tracker report.  This should only really be an issue if your framerate
  // is low.
  if (_waitForNewReport) {
    _newReportFlag = false;
    while (!_newReportFlag) {
      _vrpnDevice->mainloop();
    }
  }
  else {
    _vrpnDevice->mainloop();
  }

  while (_pendingEvents.notEmpty()) {
    inputEvents->push(_pendingEvents.getSerializedObject());
    _pendingEvents.pop();
  }
}

VRInputDevice*
VRVRPNTrackerDevice::create(VRMainInterface *vrMain, VRDataIndex *config, const std::string &nameSpace) {
  std::string devNameSpace = nameSpace;

  std::string vrpnName = config->getValue("VRPNDeviceName", devNameSpace);
  std::vector<std::string> eventsToGenerate = config->getValue("EventsToGenerate", devNameSpace);
  double scale = config->getValue("TrackerUnitsToRoomUnitsScale", devNameSpace);
  VRMatrix4 d2r = config->getValue("DeviceToRoom", devNameSpace);
  d2r = d2r.orthonormal();
  bool wait = ((int)config->getValue("WaitForNewReportInPoll", nameSpace)) == 1;
  bool convert = ((int)config->getValue("ConvertLHtoRH", nameSpace)) == 1;
  bool ignore = ((int)config->getValue("IgnoreZeroes", nameSpace)) == 1;

  std::vector<VRMatrix4> p2t;
  std::vector<VRMatrix4> fo;
  for (size_t  i = 0; i < eventsToGenerate.size(); i++) {
	  std::string trackerNameSpace = config->validateNameSpace(nameSpace) + eventsToGenerate[i] + "/";

    VRMatrix4 m = config->getValue("PropToTracker", trackerNameSpace);
    m = m.orthonormal();
    p2t.push_back(m);
    m = config->getValue("FinalOffset", trackerNameSpace);
    m = m.orthonormal();
    fo.push_back(m);
  }

  VRInputDevice *dev = new VRVRPNTrackerDevice(vrpnName, eventsToGenerate, scale,
                                               d2r, p2t, fo, wait, convert, ignore);
  return dev;
}

} // end namespace


text:
<?php

namespace Emsa\User;

use \LRC\Form\BaseModel;

class User extends BaseModel
{
    public $id;
    public $username;
    public $email;
    public $password;
    // public $deleted;

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        $this->setValidation([
            'username' => [
                [
                    'rule' => 'required',
                    'message' => 'Användarnamn måste anges.'
                ],
                [
                    'rule' => 'forbidden-characters',
                    'value' => '&<>\"\'',
                    'message' => 'Otillåtna tecken använda. Följande tecken är icke tillåtna: & < > \' "'
                ],
                [
                    'rule' => 'maxlength',
                    'value' => 50,
                    'message' => 'Användarnamnet får vara maximalt 50 tecken långt.'
                ],
            ],
            'email' => [
                [
                    'rule' => 'required',
                    'message' => 'Epostadress måste anges.'
                ],
                [
                    'rule' => 'email',
                    'message' => 'Epostadress är angiven i fel format.'
                ],
                [
                    'rule' => 'forbidden-characters',
                    'value' => '&<>\"\'',
                    'message' => 'Otillåtna tecken använda. Följande tecken är icke tillåtna: & < > \' "'
                ],
                [
                    'rule' => 'maxlength',
                    'value' => 50,
                    'message' => 'Epostadressen får vara maximalt 50 tecken lång.'
                ],
            ],
            'password' => [
                [
                    'rule' => 'required',
                    'message' => 'Lösenord måste anges.'
                ],
                // [
                //     'rule' => 'forbidden-characters',
                //     'value' => '&<>\"\'',
                //     'message' => 'Otillåtna tecken använda. Följande tecken är icke tillåtna: & < > \' "'
                // ],
            ],
        ]);
    }

    /**
     * Hash password.
     *
     * @return void
     */
    public function hashPassword()
    {
        if ($this->password) {
            $this->password = password_hash($this->password, PASSWORD_DEFAULT);
        }
    }

    /**
     * Verify the acronym and the password, if successful the object contains
     * all details from the database row.
     *
     * @param string $inputPassword the password to use.
     *
     * @return boolean true if passwords match, else false.
     */
    public function verifyPassword($inputPassword)
    {
        return password_verify($inputPassword, $this->password);
    }

    /**
     * Check if user is an admin
     * @return bool true if user exists, otherwise false
     */
    public function isAdmin()
    {
        return ($this->username === "admin");
    }
}


text:
package org.wso2.carbon.device.mgt.mobile.windows.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
import org.wso2.carbon.device.mgt.extensions.license.mgt.registry.RegistryBasedLicenseManager;
import org.wso2.carbon.device.mgt.mobile.windows.exception.WindowsDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.windows.impl.dao.AbstractMobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.windows.impl.dao.MobileDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.mobile.windows.impl.dao.WindowsDAOFactory;
import org.wso2.carbon.device.mgt.mobile.windows.impl.dto.MobileDevice;
import org.wso2.carbon.device.mgt.mobile.windows.impl.util.MobileDeviceManagementUtil;
import org.wso2.carbon.device.mgt.mobile.windows.impl.util.WindowsPluginConstants;
import org.wso2.carbon.device.mgt.mobile.windows.impl.util.WindowsPluginUtils;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class WindowsDeviceManager implements DeviceManager {

    private AbstractMobileDeviceManagementDAOFactory daoFactory;
    private LicenseManager licenseManager;
    private FeatureManager featureManager = new WindowsFeatureManager();
    private static final Log log = LogFactory.getLog(WindowsDeviceManagementService.class);

    public WindowsDeviceManager() {
        this.daoFactory = new WindowsDAOFactory();
        this.licenseManager = new RegistryBasedLicenseManager();

        License defaultLicense = WindowsPluginUtils.getDefaultLicense();

        try {
            if (licenseManager.getLicense(WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS,
                    WindowsPluginConstants.LANGUAGE_CODE_ENGLISH_US) == null) {
                licenseManager.addLicense(WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS, defaultLicense);
            }
            featureManager.addSupportedFeaturesToDB();
        } catch (LicenseManagementException e) {
            log.error("Error occurred while adding default license for Windows devices", e);
        } catch (DeviceManagementException e) {
            log.error("Error occurred while adding supported device features for Windows platform", e);
        }
    }

    @Override
    public FeatureManager getFeatureManager() {
        return featureManager;
    }

    @Override
    public boolean saveConfiguration(PlatformConfiguration tenantConfiguration)
            throws DeviceManagementException {
        boolean status;
        Resource resource;
        try {
            if (log.isDebugEnabled()) {
                log.debug("Persisting windows configurations in Registry");
            }
            String resourcePath = MobileDeviceManagementUtil.getPlatformConfigPath(
                    DeviceManagementConstants.
                            MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
            StringWriter writer = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.marshal(tenantConfiguration, writer);

            resource = MobileDeviceManagementUtil.getConfigurationRegistry().newResource();
            resource.setContent(writer.toString());
            resource.setMediaType(WindowsPluginConstants.MEDIA_TYPE_XML);
            MobileDeviceManagementUtil.putRegistryResource(resourcePath, resource);
            status = true;
        } catch (WindowsDeviceMgtPluginException e) {
            throw new DeviceManagementException(
                    "Error occurred while retrieving the Registry instance : " + e.getMessage(), e);
        } catch (RegistryException e) {
            throw new DeviceManagementException(
                    "Error occurred while persisting the Registry resource of Windows configuration : " + e.getMessage(), e);
        } catch (JAXBException e) {
            throw new DeviceManagementException(
                    "Error occurred while parsing the Windows configuration : " + e.getMessage(), e);
        }
        return status;
    }

    @Override
    public PlatformConfiguration getConfiguration() throws DeviceManagementException {
        Resource resource;
        try {
            String windowsTenantRegistryPath =
                    MobileDeviceManagementUtil.getPlatformConfigPath(DeviceManagementConstants.
                            MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS);
            resource = MobileDeviceManagementUtil.getRegistryResource(windowsTenantRegistryPath);
            if (resource != null) {
                JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                return (PlatformConfiguration) unmarshaller.unmarshal(
                        new StringReader(new String((byte[]) resource.getContent(), Charset.
                                forName(WindowsPluginConstants.CHARSET_UTF8))));
            }
            return null;
        } catch (WindowsDeviceMgtPluginException e) {
            throw new DeviceManagementException(
                    "Error occurred while retrieving the Registry instance : " + e.getMessage(), e);
        } catch (JAXBException e) {
            throw new DeviceManagementException(
                    "Error occurred while parsing the Windows configuration : " + e.getMessage(), e);
        } catch (RegistryException e) {
            throw new DeviceManagementException(
                    "Error occurred while retrieving the Registry resource of Windows configuration : " + e.getMessage(), e);
        }
    }

    @Override
    public boolean modifyEnrollment(Device device) throws DeviceManagementException {
        boolean status;
        MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device);
        try {
            if (log.isDebugEnabled()) {
                log.debug("Modifying the Windows device enrollment data");
            }
            WindowsDAOFactory.beginTransaction();
            status = daoFactory.getMobileDeviceDAO().updateMobileDevice(mobileDevice);
            WindowsDAOFactory.commitTransaction();
        } catch (MobileDeviceManagementDAOException e) {
            WindowsDAOFactory.rollbackTransaction();
            throw new DeviceManagementException("Error while updating the enrollment of the Windows device : " +
                    device.getDeviceIdentifier(), e);
        } finally {
            WindowsDAOFactory.closeConnection();
        }
        return status;
    }

    @Override
    public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
        //Here we don't have anything specific to do. Hence returning.
        return true;
    }

    @Override
    public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
        boolean isEnrolled = false;
        try {
            if (log.isDebugEnabled()) {
                log.debug("Checking the enrollment of Windows device : " + deviceId.getId());
            }
            MobileDevice mobileDevice =
                    daoFactory.getMobileDeviceDAO().getMobileDevice(deviceId.getId());
            if (mobileDevice != null) {
                isEnrolled = true;
            }
        } catch (MobileDeviceManagementDAOException e) {
            String msg = "Error while checking the enrollment status of Windows device : " +
                    deviceId.getId();
            throw new DeviceManagementException(msg, e);
        }
        return isEnrolled;
    }

    @Override
    public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
        return true;
    }

    @Override
    public boolean setActive(DeviceIdentifier deviceId, boolean status)
            throws DeviceManagementException {
        return true;
    }

    public List<Device> getAllDevices() throws DeviceManagementException {
        List<Device> devices = null;
        try {
            if (log.isDebugEnabled()) {
                log.debug("Fetching the details of all Windows devices");
            }
            WindowsDAOFactory.openConnection();
            List<MobileDevice> mobileDevices = daoFactory.getMobileDeviceDAO().getAllMobileDevices();
            if (mobileDevices != null) {
                devices = new ArrayList<>(mobileDevices.size());
                for (MobileDevice mobileDevice : mobileDevices) {
                    devices.add(MobileDeviceManagementUtil.convertToDevice(mobileDevice));
                }
            }
        } catch (MobileDeviceManagementDAOException e) {
            throw new DeviceManagementException("Error occurred while fetching all Windows devices", e);
        } finally {
            WindowsDAOFactory.closeConnection();
        }
        return devices;
    }

    @Override
    public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
        Device device = null;
        try {
            if (log.isDebugEnabled()) {
                log.debug("Getting the details of Windows device : '" + deviceId.getId() + "'");
            }
            WindowsDAOFactory.openConnection();
            MobileDevice mobileDevice = daoFactory.getMobileDeviceDAO().
                    getMobileDevice(deviceId.getId());
            device = MobileDeviceManagementUtil.convertToDevice(mobileDevice);
        } catch (MobileDeviceManagementDAOException e) {
            throw new DeviceManagementException(
                    "Error occurred while fetching the Windows device: '" + deviceId.getId() + "'", e);
        } finally {
            WindowsDAOFactory.closeConnection();
        }
        return device;
    }

    @Override
    public boolean updateDeviceProperties(DeviceIdentifier deviceIdentifier, List<Device.Property> list) throws DeviceManagementException {
        return false;
    }

    @Override
    public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
            throws DeviceManagementException {
        return true;
    }

    @Override
    public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
        return false;
    }

    @Override
    public boolean setStatus(DeviceIdentifier deviceIdentifier, String currentUser,
                             EnrolmentInfo.Status status) throws DeviceManagementException {
        return false;
    }

    @Override
    public License getLicense(String languageCode) throws LicenseManagementException {
        return licenseManager.getLicense(WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS, languageCode);
    }

    @Override
    public void addLicense(License license) throws LicenseManagementException {
        licenseManager.addLicense(WindowsDeviceManagementService.DEVICE_TYPE_WINDOWS, license);
    }

    @Override
    public boolean requireDeviceAuthorization() {
        return false;
    }

    @Override
    public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier,
                                    Device device) throws DeviceManagementException {
        return true;
    }

    @Override
    public boolean enrollDevice(Device device) throws DeviceManagementException {
        boolean status = false;
        MobileDevice mobileDevice = MobileDeviceManagementUtil.convertToMobileDevice(device);
        try {
            if (log.isDebugEnabled()) {
                log.debug("Enrolling a new windows device : " + device.getDeviceIdentifier());
            }
            boolean isEnrolled = this.isEnrolled(
                    new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
            if (isEnrolled) {
                this.modifyEnrollment(device);
            } else {
                WindowsDAOFactory.beginTransaction();
                status = daoFactory.getMobileDeviceDAO().addMobileDevice(mobileDevice);
                WindowsDAOFactory.commitTransaction();
            }
        } catch (MobileDeviceManagementDAOException e) {
            WindowsDAOFactory.rollbackTransaction();
            String msg =
                    "Error while enrolling the windows device : " + device.getDeviceIdentifier();
            throw new DeviceManagementException(msg, e);
        }
        return status;
    }

}


text:
package org.jetbrains.plugins.scala
package lang
package psi
package impl
package base
package patterns

import com.intellij.lang.ASTNode
import com.intellij.psi._
import org.jetbrains.plugins.scala.lang.psi.api.ScalaElementVisitor
import org.jetbrains.plugins.scala.lang.psi.api.base.patterns._

/**
* @author Alexander Podkhalyuzin
* Date: 28.02.2008
*/

class ScTuplePatternImpl(node: ASTNode) extends ScalaPsiElementImpl (node) with ScTuplePattern {
  override def accept(visitor: PsiElementVisitor): Unit = {
    visitor match {
      case visitor: ScalaElementVisitor => super.accept(visitor)
      case _ => super.accept(visitor)
    }
  }

  override def toString: String = "TuplePattern"

  override def subpatterns: Seq[ScPattern] =  patternList match {
    case Some(l) => l.patterns
    case None => Seq.empty
  }
}


text:
package net.ebour.mytoolbox.vmware;

import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;

import java.util.*;
import java.util.logging.Level;

import static java.util.Arrays.asList;

/**
 * Created by ebour.
 */
public class VmwareClient
{
    private static final long WAIT_SLEEP_TIME_MS = 5000;

    private       ServiceInstance serviceInstance;
    private       VmwareServer    vmwareServer;

    public VmwareClient(final VmwareServer vmwareServer)
    {
        this.vmwareServer = vmwareServer;
    }

    public VMInfo shutdownVM(String vmName) throws Exception
    {
        VirtualMachine vm = findVM(vmName);
        new VmwTask.PowerOffVMTask(vm, vmName).waitForTask();

        return getVMInfo(vm);
    }

    public void destroyVM(String vmName) throws Exception
    {
        VirtualMachine vm = findVM(vmName);
        if(isVmStarted(vmName))
        {
            shutdownVM(vmName);
        }
        new VmwTask.DestroyVMTask(vm, vmName).waitForTask();
    }

    public VMPowerState getVmPowerState(String vmName) throws Exception
    {
        return getVMInfo(vmName).getPowerState();
    }

    public boolean isVmStarted(String vmName) throws Exception
    {
        return getVmPowerState(vmName) == VMPowerState.PoweredOn;
    }

    public VMInfo startVM(String vmName) throws Exception
    {
        VirtualMachine vm = findVM(vmName);
        new VmwTask.PowerOnVMTask(vm, vmName).waitForTask();
        waitForOSBoot(vm);

        return getVMInfo(vm);
    }

    public VMInfo createVM(String vmName, String template) throws Exception
    {
        VirtualMachine vm = findVM(vmName);
        ResourcePool resourcePool = findResourcePool(findDatacenter());

        new VmwTask.CreateVMTask(vm, resourcePool, findFolder(vmwareServer.getWorkingDir()), template, vmName).waitForTask();

        return startVM(vmName);
    }

    public VMInfo getVMInfo(final String vmName) throws Exception
    {
        VirtualMachine vm = findVM(vmName);
        return getVMInfo(vm);
    }

    private VMInfo getVMInfo(VirtualMachine vm) {
        // ipv4 address
        String ipv4Address = vm.getGuest().getIpAddress();
        if (isNullOrEmpty(ipv4Address)) {
            ipv4Address = "0.0.0.0";
        }

        // all addresses for enabled NICs both IPv4 and IPv6
        StringBuilder addr = new StringBuilder();
        try {
            for (int loop=1; loop<=5; loop++) {
                for (GuestNicInfo nic : vm.getGuest().getNet()) {
                    if (nic.isConnected()) {
                        try {
                            String[] ipAddrInfo = nic.getIpAddress();
                            for (String ipAddress : ipAddrInfo) {
                                if (ipAddress.matches(".*:.*.:.*"))
                                {
                                    if (ipAddress.startsWith("fe80")) { ; }
                                    else
                                    {
                                        if (addr.length() > 0)
                                        {
                                            addr.append(',');
                                        }
                                        addr.append(ipAddress);
                                    }
                                }
                            }
                        } catch (Exception e) { ; }

                    }
                }
                if (addr.length() == 0) {
//		        	System.out.println("Sleeping 1 min and check again");
                    Thread.sleep(60000);
                } else {
                    break;
                }
            }
        } catch (Exception e) { ; }

        String ipv6Addresses;
        if (addr.length() == 0)
        {
            ipv6Addresses = "::";
        }
        else
        {
            ipv6Addresses = addr.toString();
        }
        // hostname
        String hostname = vm.getGuest().getHostName();

        // domainname
        String domainName = "";
        if (vm.getGuest().getGuestFamily().contains("linux"))
        {
            GuestStackInfo[] stackInfo = vm.getGuest().getIpStack();
            if (stackInfo != null && stackInfo.length > 0)
            {
                NetDnsConfigInfo dnsConfig = stackInfo[0].getDnsConfig();
                domainName = dnsConfig.getDomainName();
            }
        }
        else if (vm.getGuest().getGuestFamily().contains("windows"))
        {
            for (GuestNicInfo nics : vm.getGuest().getNet())
            {
                if (nics.isConnected())
                {
                    try {
                        domainName = nics.getDnsConfig().getDomainName();
                        break;
                    } catch (Exception e) { ; }
                }
            }
        }

        if (domainName == null || domainName.isEmpty())
        {
            domainName = "";
        }

        return new VMInfo(vm.getName(), ipv4Address, getVMPowerState(vm), hostname, domainName, ipv6Addresses);
    }

    private VMPowerState getVMPowerState(VirtualMachine vm) {
        if (getPowerState(vm).equals(VirtualMachinePowerState.poweredOn)) {
            return VMPowerState.PoweredOn;
        } else if (getPowerState(vm).equals(VirtualMachinePowerState.poweredOff)) {
            return VMPowerState.PoweredOff;
        } else if (getPowerState(vm).equals(VirtualMachinePowerState.suspended)) {
            return VMPowerState.Suspended;
        }
        return VMPowerState.Unknown;
    }

    private boolean isPoweredOn(VirtualMachine vm) {
        return getPowerState(vm) == VirtualMachinePowerState.poweredOn;
    }

    private VirtualMachinePowerState getPowerState(VirtualMachine vm) {
        VirtualMachineRuntimeInfo runtimeInfo = vm.getRuntime();
        if (runtimeInfo == null) {
            return null;
        }
        return runtimeInfo.getPowerState();
    }

    private boolean isTemplate(VirtualMachine vm) {
        return isTemplate(vm, null);
    }

    private boolean isTemplate(VirtualMachine vm, VirtualMachineConfigInfo configInfo) {
        if (configInfo == null) {
            configInfo = vm.getConfig();
            if (configInfo == null) {
                return false;
            }
        }
        return configInfo.isTemplate();
    }

    private boolean isNullOrEmpty(String param) {
        if (param == null || param.length() == 0) {
            return true;
        }
        return false;
    }

    private void waitForOSBoot(VirtualMachine vm) {
        GuestInfo guest = vm.getGuest();
        while (isNullOrEmpty(guest.getIpAddress()) || guest.getNet() == null) {
            try {
                Thread.sleep(WAIT_SLEEP_TIME_MS);
            } catch (InterruptedException e) {
                ;
            }
            guest = vm.getGuest();
        }
    }

    private Datacenter findDatacenter()
            throws Exception
    {
        InventoryNavigator navigator = new InventoryNavigator(serviceInstance.getRootFolder());
        String datacenterName = vmwareServer.getDataCenter();
        Datacenter dataCenter = null;
        try
        {
            dataCenter = (Datacenter)navigator.searchManagedEntity("Datacenter", datacenterName);
        }
        catch (Exception e)
        {
            final String msg = String.format("VMWare exception finding data center '%s'", new Object[] { datacenterName });
            throw new Exception(msg);
        }
        return dataCenter;
    }

    private ResourcePool findResourcePool(Datacenter dataCenter)
            throws Exception
    {
        InventoryNavigator navigator = new InventoryNavigator(dataCenter);
        String resourcePoolName = vmwareServer.getResourcePool();
        ResourcePool resourcePool = null;
        try
        {
            resourcePool = (ResourcePool)navigator.searchManagedEntity("ResourcePool", resourcePoolName);
        }
        catch (Exception e)
        {
            final String msg = String.format("VMWare exception finding resource pool '%s'", new Object[] { resourcePoolName });
            throw new Exception(msg, e);
        }
        return resourcePool;
    }

    private VirtualMachine findVM(final String vmName)
            throws Exception
    {
        final InventoryNavigator navigator = new InventoryNavigator(serviceInstance.getRootFolder());
        VirtualMachine vm = null;
        try
        {
            vm = (VirtualMachine)navigator.searchManagedEntity("VirtualMachine", vmName);
        }
        catch (Exception e)
        {
            final String msg = String.format("VMWare exception finding VM '%s'", new Object[] { vmName });
            throw new Exception(msg, e);
        }
        if (vm == null)
        {
            final String msg = String.format("VM '%s' not found", new Object[] { vmName });
            throw new Exception(msg);
        }
        return vm;
    }

    public void login() throws Exception
    {
        try
        {
            this.serviceInstance = new ServiceInstance(vmwareServer.getUrl(), vmwareServer.getUser(), vmwareServer.getPassword(), true);
        }
        catch (Exception e)
        {
            final String msg = String.format("VMWare login failed for user '%s'", new Object[] { vmwareServer.getUser() });
            throw new Exception(msg, e);
        }

    }

    public Map<String, TimeSerie> getPerformanceData(final String hostname, final Calendar startTime, final Calendar endTime, int intervalInSec, final String... metricKeys) throws Exception
    {
        PerformanceManager performanceManager = serviceInstance.getPerformanceManager();

        VirtualMachine vm = findVm(hostname);

        final List<PerfMetricId> metrics = asList(performanceManager.queryAvailablePerfMetric(vm, startTime, endTime, intervalInSec));
        final int[] metricIds = new int[metrics.size()];
        for(int idx = 0; idx < metrics.size(); idx++)
        {
            final PerfMetricId metric = metrics.get(idx);
            metricIds[idx] = metric.getCounterId();
        }

        final List<PerfMetricId> perfMetricIds = new ArrayList<>();
        int idx = 0;
        final PerfCounterInfo[] perfCounterInfos = performanceManager.queryPerfCounter(metricIds);
        for(PerfCounterInfo perfCounterInfo : perfCounterInfos)
        {
            final String key = perfCounterInfo.getGroupInfo().getKey()
                    + "." + perfCounterInfo.getNameInfo().getKey()
                    + "." + perfCounterInfo.getRollupType().toString();
            for(String metricKey : metricKeys)
            {
                if(key.equalsIgnoreCase(metricKey))
                {
                    perfMetricIds.add(metrics.get(idx));
                    break;
                }
            }

            // System.out.println("metric key: " + perfCounterInfo.getRollupType().name() + "." + perfCounterInfo.getGroupInfo().getKey() + "." + perfCounterInfo.getNameInfo().getKey() + "." + perfCounterInfo.getUnitInfo().getKey() + "." + perfCounterInfo.getLevel());
            idx++;
        }

        PerfQuerySpec[] perfQuery = new PerfQuerySpec[]{new PerfQuerySpec()};

        perfQuery[0].entity = vm.getMOR();
        perfQuery[0].metricId = perfMetricIds.toArray(new PerfMetricId[perfMetricIds.size()]);
        perfQuery[0].maxSample = 100;
        perfQuery[0].startTime = startTime;
        perfQuery[0].endTime = endTime;
        perfQuery[0].intervalId = intervalInSec;
        perfQuery[0].format = "normal";

        PerfEntityMetricBase[] perfData = performanceManager.queryPerf(perfQuery);

        final Map<String, TimeSerie> series = new HashMap<>();
        for (int i = 0; perfData != null && i < perfData.length; i++)
        {
            final TimeSerie serie = new TimeSerie();

            PerfEntityMetricBase val = perfData[i];
            PerfEntityMetric pem = (PerfEntityMetric) val;
            PerfMetricSeries[] vals = pem.getValue(); // timestamps
            PerfSampleInfo[] infos = pem.getSampleInfo(); // values

            for (int j = 0; vals != null && j < vals.length; ++j)
            {
                PerfMetricIntSeries val1 = (PerfMetricIntSeries) vals[j];
                PerfCounterInfo perfCounterInfo = perfCounterInfos[findPerfMetricId(metrics, val1.getId())];

                final String key = perfCounterInfo.getGroupInfo().getKey()
                        + "." + perfCounterInfo.getNameInfo().getKey()
                        + "." + perfCounterInfo.getRollupType().toString();

                if(!series.containsKey(key))
                {
                    series.put(key, serie);
                }

                long[] longs = val1.getValue(); // a value
                for (int k = 0; k < longs.length; k++)
                {
                    serie.add(String.valueOf(infos[k].getTimestamp().getTime().getTime()), String.valueOf(longs[k]));
                }
            }
        }

        return series;
    }

    private int findPerfMetricId(final List<PerfMetricId> metrics, final PerfMetricId id) throws Exception
    {
        int pos = 0;
        for(PerfMetricId perfMetricId : metrics)
        {
            if(perfMetricId.counterId == id.counterId)
            {
                return pos;
            }
            pos ++;
        }
        throw new Exception("Unable to find PerfMetricId!");
    }

    public void logout()
    {
        serviceInstance.getServerConnection().logout();
    }

    private Folder findFolder(String folderName) throws Exception
    {
        return findFolder(serviceInstance.getRootFolder(), folderName);
    }

    private Folder findFolder(Folder folderRoot, String folderName) throws Exception
    {
        InventoryNavigator navigator = new InventoryNavigator(folderRoot);
        Folder folder = null;
        try
        {
            folder = (Folder)navigator.searchManagedEntity("Folder", folderName);
        }
        catch (Exception e)
        {
            String msg = String.format("VMWare exception finding folder '%s'", new Object[] { folderName });
            throw new Exception(msg);
        }
        return folder;
    }

    private Folder createFolder(Folder folderRoot, String folderName) throws Exception
    {
        try
        {
            return folderRoot.createFolder(folderName);
        }
        catch (Exception e)
        {
            String msg = String.format("VMWare exception creating folder '%s'", new Object[] { folderName });
            throw new Exception(msg);
        }
    }

    private VirtualMachine findVm(final String hostname) throws Exception
    {
        final InventoryNavigator navigator = new InventoryNavigator(serviceInstance.getRootFolder());
        final ManagedEntity[] vms = navigator.searchManagedEntities("VirtualMachine");
        VirtualMachine vm = null;
        try
        {
            for(ManagedEntity virtualMachine : vms)
            {
                if(virtualMachine instanceof VirtualMachine)
                {
                    final String vmHostname = ((VirtualMachine)virtualMachine).getGuest().getHostName();
                    System.out.println("vm: " + virtualMachine.getName());
                    if(vmHostname == null || vmHostname.isEmpty())
                    {
                        continue;
                    }
                    else if(vmHostname.contentEquals(hostname.trim()))
                    {
                        vm = (VirtualMachine) virtualMachine;
                        break;
                    }
                }
            }
        }
        catch (Exception e)
        {
            String msg = String.format("VMWare exception finding VM '%s'", new Object[] { hostname });
            throw new Exception(msg);
        }
        if (vm == null)
        {
            String msg = String.format("VM '%s' not found", new Object[] { hostname });
            throw new Exception(msg);
        }
        return vm;
    }
}


text:
<?php

namespace Sonata\PageBundle\Tests\Validator;

use Sonata\PageBundle\Validator\Constraints\UniqueUrl;
use Sonata\PageBundle\Validator\UniqueUrlValidator;

class UniqueUrlValidatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @group legacy
     */
    public function testValidateWithNoPageFound()
    {
        $site = $this->getMock('Sonata\PageBundle\Model\SiteInterface');

        $page = $this->getMock('Sonata\PageBundle\Model\PageInterface');
        $page->expects($this->exactly(2))->method('getSite')->will($this->returnValue($site));
        $page->expects($this->exactly(2))->method('isError')->will($this->returnValue(false));

        $manager = $this->getMock('Sonata\PageBundle\Model\PageManagerInterface');
        $manager->expects($this->once())->method('fixUrl');
        $manager->expects($this->once())->method('findBy')->will($this->returnValue(array($page)));

        $context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $context->expects($this->never())->method('addViolationAt');

        $validator = new UniqueUrlValidator($manager);
        $validator->initialize($context);

        $validator->validate($page, new UniqueUrl());
    }

    public function testValidateWithPageFound()
    {
        $site = $this->getMock('Sonata\PageBundle\Model\SiteInterface');

        $page = $this->getMock('Sonata\PageBundle\Model\PageInterface');
        $page->expects($this->exactly(2))->method('getSite')->will($this->returnValue($site));
        $page->expects($this->exactly(2))->method('isError')->will($this->returnValue(false));
        $page->expects($this->any())->method('getUrl')->will($this->returnValue('/salut'));

        $pageFound = $this->getMock('Sonata\PageBundle\Model\PageInterface');
        $pageFound->expects($this->any())->method('getUrl')->will($this->returnValue('/salut'));

        $manager = $this->getMock('Sonata\PageBundle\Model\PageManagerInterface');
        $manager->expects($this->once())->method('fixUrl');
        $manager->expects($this->once())->method('findBy')->will($this->returnValue(array($page, $pageFound)));

        $context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $context
            ->expects($this->once())
            ->method('addViolationAt')
            ->with($this->equalTo('url'), $this->equalTo('error.uniq_url'));

        $validator = new UniqueUrlValidator($manager);
        $validator->initialize($context);

        $validator->validate($page, new UniqueUrl());
    }

    public function testValidateWithRootUrlAndNoParent()
    {
        $site = $this->getMock('Sonata\PageBundle\Model\SiteInterface');

        $page = $this->getMock('Sonata\PageBundle\Model\PageInterface');
        $page->expects($this->exactly(2))->method('getSite')->will($this->returnValue($site));
        $page->expects($this->exactly(2))->method('isError')->will($this->returnValue(false));
        $page->expects($this->exactly(1))->method('getParent')->will($this->returnValue(null));
        $page->expects($this->any())->method('getUrl')->will($this->returnValue('/'));

        $pageFound = $this->getMock('Sonata\PageBundle\Model\PageInterface');
        $pageFound->expects($this->any())->method('getUrl')->will($this->returnValue('/'));

        $manager = $this->getMock('Sonata\PageBundle\Model\PageManagerInterface');
        $manager->expects($this->once())->method('fixUrl');
        $manager->expects($this->once())->method('findBy')->will($this->returnValue(array($page, $pageFound)));

        $context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $context
            ->expects($this->once())
            ->method('addViolationAt')
            ->with($this->equalTo('parent'), $this->equalTo('error.uniq_url.parent_unselect'));

        $validator = new UniqueUrlValidator($manager);
        $validator->initialize($context);

        $validator->validate($page, new UniqueUrl());
    }

    public function testValidateWithPageDynamic()
    {
        $site = $this->getMock('Sonata\PageBundle\Model\SiteInterface');

        $page = $this->getMock('Sonata\PageBundle\Model\PageInterface');
        $page->expects($this->once())->method('getSite')->will($this->returnValue($site));
        $page->expects($this->once())->method('isError')->will($this->returnValue(false));
        $page->expects($this->once())->method('isDynamic')->will($this->returnValue(true));
        $page->expects($this->any())->method('getUrl')->will($this->returnValue('/salut'));

        $manager = $this->getMock('Sonata\PageBundle\Model\PageManagerInterface');

        $context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $context->expects($this->never())->method('addViolationAt');

        $validator = new UniqueUrlValidator($manager);
        $validator->initialize($context);

        $validator->validate($page, new UniqueUrl());
    }
}


text:
//
//  SearchDetailsVC.m
//  CookBooks
//
//  Created by lanou3g on 15/10/13.
//  Copyright (c) 2015年 李彬彬. All rights reserved.
//

#import "SearchDetailsVC.h"
#import "UIImageView+WebCache.h"
#import "DetailsListHelpers.h"
#import "SearchViewController.h"
#import "MaterialModel.h"

@interface SearchDetailsVC ()

@property (nonatomic,strong)NSString *str;

@end

@implementation SearchDetailsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self header];
    self.tableView.showsVerticalScrollIndicator = NO;

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

}

// 区头
- (void)header
{
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 210)];
    imgView.backgroundColor = [UIColor colorWithWhite:0.890 alpha:1.000];
    [imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://pic.ecook.cn/web/%@.jpg!m3",_imgURL]]];
    self.tableView.tableHeaderView = imgView;
    [self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (section == 0) {
        return self.nameArr.count;
    }else{
        return self.stepArr.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return [self textHeight:_str] + 20;
    }
    return [self textHeight:_str] + 20;
}

- (CGFloat)textHeight:(NSString *)str{

    NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};

    CGRect rect = [str boundingRectWithSize:CGSizeMake(335, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];

    return rect.size.height;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    if (indexPath.section == 0) {
        // 材料
        NSDictionary *dict = self.nameArr[indexPath.row];
        NSString *name = dict[@"name"];
        cell.textLabel.text = name;
        _str = cell.textLabel.text;
        // 自动换行
        cell.textLabel.numberOfLines = 0;
        return cell;

    }else{
        // 步骤
        NSDictionary *dict = self.stepArr[indexPath.row];
        NSString *step = dict[@"details"];
        cell.textLabel.text = step;
        _str = cell.textLabel.text;
        // 自动换行
        cell.textLabel.numberOfLines = 0;
        return cell;
    }

}

// 区头设置
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return @"做法:";
    }
    return @"材料:";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 改变选中cell后状态
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];

}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

// 重写set
- (void)setImgURL:(NSString *)imgURL
{
    if (_imgURL == nil) {
        _imgURL = imgURL;
    }

}

- (NSMutableArray *)nameArr{
    if (_nameArr == nil) {
        _nameArr = [NSMutableArray new];
    }
    return _nameArr;
}

- (NSMutableArray *)stepArr
{
    if (_stepArr == nil) {
        _stepArr = [NSMutableArray new];
    }
    return _stepArr;
}
@end


text:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
// ReSharper disable All

namespace Com.Ericmas001.Userbase.Entities
{
    [Table("UserGroupTypes")]
    public class UserGroupType : IEntityWithId
    {
        public const string ADMIN_GRP = "Admin";

        [NotMapped]
        public int Id
        {
            get { return IdUserGroupType; }
            set { IdUserGroupType = value; }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public UserGroupType()
        {
            UserGroups = new HashSet<UserGroup>();
        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int IdUserGroupType { get; set; }

        [Required]
        [StringLength(100)]
        public string Name { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<UserGroup> UserGroups { get; set; }
    }
}


text:
package org.gnucash.android.test.unit.model;

import org.gnucash.android.model.PeriodType;
import org.gnucash.android.model.Recurrence;
import org.gnucash.android.model.ScheduledAction;
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import org.junit.Test;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Test scheduled actions
 */
public class ScheduledActionTest {

    @Test
    public void settingStartTime_shouldSetRecurrenceStart(){
        ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION);
        long startTime = getTimeInMillis(2014, 8, 26);
        scheduledAction.setStartTime(startTime);
        assertThat(scheduledAction.getRecurrence()).isNull();

        Recurrence recurrence = new Recurrence(PeriodType.MONTH);
        assertThat(recurrence.getPeriodStart().getTime()).isNotEqualTo(startTime);
        scheduledAction.setRecurrence(recurrence);
        assertThat(recurrence.getPeriodStart().getTime()).isEqualTo(startTime);

        long newStartTime = getTimeInMillis(2015, 6, 6);
        scheduledAction.setStartTime(newStartTime);
        assertThat(recurrence.getPeriodStart().getTime()).isEqualTo(newStartTime);
    }

    @Test
    public void settingEndTime_shouldSetRecurrenceEnd(){
        ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION);
        long endTime = getTimeInMillis(2014, 8, 26);
        scheduledAction.setEndTime(endTime);
        assertThat(scheduledAction.getRecurrence()).isNull();

        Recurrence recurrence = new Recurrence(PeriodType.MONTH);
        assertThat(recurrence.getPeriodEnd()).isNull();
        scheduledAction.setRecurrence(recurrence);
        assertThat(recurrence.getPeriodEnd().getTime()).isEqualTo(endTime);

        long newEndTime = getTimeInMillis(2015, 6, 6);
        scheduledAction.setEndTime(newEndTime);
        assertThat(recurrence.getPeriodEnd().getTime()).isEqualTo(newEndTime);
    }

    @Test
    public void settingRecurrence_shouldSetScheduledActionStartTime(){
        ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP);
        assertThat(scheduledAction.getStartTime()).isEqualTo(0);

        long startTime = getTimeInMillis(2014, 8, 26);
        Recurrence recurrence = new Recurrence(PeriodType.WEEK);
        recurrence.setPeriodStart(new Timestamp(startTime));
        scheduledAction.setRecurrence(recurrence);
        assertThat(scheduledAction.getStartTime()).isEqualTo(startTime);
    }

    @Test
    public void settingRecurrence_shouldSetEndTime(){
        ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP);
        assertThat(scheduledAction.getStartTime()).isEqualTo(0);

        long endTime = getTimeInMillis(2017, 8, 26);
        Recurrence recurrence = new Recurrence(PeriodType.WEEK);
        recurrence.setPeriodEnd(new Timestamp(endTime));
        scheduledAction.setRecurrence(recurrence);

        assertThat(scheduledAction.getEndTime()).isEqualTo(endTime);
    }

    /**
     * Checks that scheduled actions accurately compute the next run time based on the start date
     * and the last time the action was run
     */
    @Test
    public void testComputingNextScheduledExecution(){
        ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION);
        PeriodType periodType = PeriodType.MONTH;

        Recurrence recurrence = new Recurrence(periodType);
        recurrence.setMultiplier(2);
        DateTime startDate = new DateTime(2015, 8, 15, 12, 0);
        recurrence.setPeriodStart(new Timestamp(startDate.getMillis()));
        scheduledAction.setRecurrence(recurrence);

        assertThat(scheduledAction.computeNextCountBasedScheduledExecutionTime()).isEqualTo(startDate.getMillis());

        scheduledAction.setExecutionCount(3);
        DateTime expectedTime = new DateTime(2016, 2, 15, 12, 0);
        assertThat(scheduledAction.computeNextCountBasedScheduledExecutionTime()).isEqualTo(expectedTime.getMillis());
    }

    @Test
    public void testComputingTimeOfLastSchedule(){
        ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.TRANSACTION);
        PeriodType periodType = PeriodType.WEEK;
        Recurrence recurrence = new Recurrence(periodType);
        recurrence.setMultiplier(2);
        scheduledAction.setRecurrence(recurrence);
        DateTime startDate = new DateTime(2016, 6, 6, 9, 0);
        scheduledAction.setStartTime(startDate.getMillis());

        assertThat(scheduledAction.getTimeOfLastSchedule()).isEqualTo(-1L);

        scheduledAction.setExecutionCount(3);
        DateTime expectedDate = new DateTime(2016, 7, 4, 9, 0);
        assertThat(scheduledAction.getTimeOfLastSchedule()).isEqualTo(expectedDate.getMillis());

    }

    /**
     * Weekly actions scheduled to run on multiple days of the week should be due
     * in each of them in the same week.
     *
     * For an action scheduled on Mondays and Thursdays, we test that, if
     * the last run was on Monday, the next should be due on the Thursday
     * of the same week instead of the following week.
     */
    @Test
    public void multiDayOfWeekWeeklyActions_shouldBeDueOnEachDayOfWeekSet() {
        ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP);
        Recurrence recurrence = new Recurrence(PeriodType.WEEK);
        recurrence.setByDays(Arrays.asList(Calendar.MONDAY, Calendar.THURSDAY));
        scheduledAction.setRecurrence(recurrence);
        scheduledAction.setStartTime(new DateTime(2016, 6, 6, 9, 0).getMillis());
        scheduledAction.setLastRun(new DateTime(2017, 4, 17, 9, 0).getMillis()); // Monday

        long expectedNextDueDate = new DateTime(2017, 4, 20, 9, 0).getMillis(); // Thursday
        assertThat(scheduledAction.computeNextTimeBasedScheduledExecutionTime())
                .isEqualTo(expectedNextDueDate);
    }

    /**
     * Weekly actions scheduled with multiplier should skip intermediate
     * weeks and be due in the specified day of the week.
     */
    @Test
    public void weeklyActionsWithMultiplier_shouldBeDueOnTheDayOfWeekSet() {
        ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP);
        Recurrence recurrence = new Recurrence(PeriodType.WEEK);
        recurrence.setMultiplier(2);
        recurrence.setByDays(Collections.singletonList(Calendar.WEDNESDAY));
        scheduledAction.setRecurrence(recurrence);
        scheduledAction.setStartTime(new DateTime(2016, 6, 6, 9, 0).getMillis());
        scheduledAction.setLastRun(new DateTime(2017, 4, 12, 9, 0).getMillis()); // Wednesday

        // Wednesday, 2 weeks after the last run
        long expectedNextDueDate = new DateTime(2017, 4, 26, 9, 0).getMillis();
        assertThat(scheduledAction.computeNextTimeBasedScheduledExecutionTime())
                .isEqualTo(expectedNextDueDate);
    }

    /**
     * Weekly actions should return a date in the future when no
     * days of the week have been set in the recurrence.
     *
     * See ScheduledAction.computeNextTimeBasedScheduledExecutionTime()
     */
    @Test
    public void weeklyActionsWithoutDayOfWeekSet_shouldReturnDateInTheFuture() {
        ScheduledAction scheduledAction = new ScheduledAction(ScheduledAction.ActionType.BACKUP);
        Recurrence recurrence = new Recurrence(PeriodType.WEEK);
        recurrence.setByDays(Collections.<Integer>emptyList());
        scheduledAction.setRecurrence(recurrence);
        scheduledAction.setStartTime(new DateTime(2016, 6, 6, 9, 0).getMillis());
        scheduledAction.setLastRun(new DateTime(2017, 4, 12, 9, 0).getMillis());

        long now = LocalDateTime.now().toDate().getTime();
        assertThat(scheduledAction.computeNextTimeBasedScheduledExecutionTime()).isGreaterThan(now);
    }

    private long getTimeInMillis(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTimeInMillis();
    }

    //todo add test for computing the scheduledaction endtime from the recurrence count
}


text:
/**
 * Rigid constraints manager.
 * Handles distance constraints
 * @module behaviors/rigid-constraint-manager
 */
Physics.behavior('rigid-constraint-manager', function( parent ){

    var defaults = {

        // set a default target length
        targetLength: 20
    };

    return {

        /**
         * Initialization
         * @param  {Object} options Configuration object
         * @return {void}
         */
        init: function( options ){

            parent.init.call(this, options);

            Physics.util.extend(this.options, defaults, options);

            this._constraints = [];
        },

        /**
         * Connect to world. Automatically called when added to world by the setWorld method
         * @param  {Object} world The world to connect to
         * @return {void}
         */
        connect: function( world ){

            var intg = world.integrator();

            if ( intg && intg.name.indexOf('verlet') < 0 ){

                throw 'The rigid constraint manager needs a world with a "verlet" compatible integrator.';
            }

            world.subscribe('integrate:positions', this.resolve, this);
        },

        /**
         * Disconnect from world
         * @param  {Object} world The world to disconnect from
         * @return {void}
         */
        disconnect: function( world ){

            world.unsubscribe('integrate:positions', this.resolve);
        },

        /**
         * Remove all constraints
         * @return {self}
         */
        drop: function(){

            // drop the current constraints
            this._constraints = [];
            return this;
        },

        /**
         * Constrain two bodies to a target relative distance
         * @param  {Object} bodyA        First body
         * @param  {Object} bodyB        Second body
         * @param  {Number} targetLength (optional) Target length. defaults to target length specified in configuration options
         * @return {object}              The constraint object, which holds .bodyA and .bodyB references to the bodies, .id the string ID of the constraint, .targetLength the target length
         */
        constrain: function( bodyA, bodyB, targetLength ){

            var cst;

            if (!bodyA || !bodyB){

                return false;
            }

            this._constraints.push(cst = {
                id: Physics.util.uniqueId('rigid-constraint'),
                bodyA: bodyA,
                bodyB: bodyB,
                targetLength: targetLength || this.options.targetLength
            });

            return cst;
        },

        /**
         * Remove a constraint
         * @param  {Mixed} indexCstrOrId Either the constraint object, the constraint id, or the numeric index of the constraint
         * @return {self}
         */
        remove: function( indexCstrOrId ){

            var constraints = this._constraints
                ,isObj
                ;

            if (typeof indexCstrOrId === 'number'){

                constraints.splice( indexCstrOrId, 1 );
                return this;
            }

            isObj = Physics.util.isObject( indexCstrOrId );

            for ( var i = 0, l = constraints.length; i < l; ++i ){

                if ( (isObj && constraints[ i ] === indexCstrOrId) ||
                    ( !isObj && constraints[ i ].id === indexCstrOrId) ){

                    constraints.splice( i, 1 );
                    return this;
                }
            }

            return this;
        },

        /**
         * Resolve constraints
         * @return {void}
         */
        resolve: function(){

            var constraints = this._constraints
                ,scratch = Physics.scratchpad()
                ,A = scratch.vector()
                ,BA = scratch.vector()
                ,con
                ,len
                ,corr
                ,proportion
                ;

            for ( var i = 0, l = constraints.length; i < l; ++i ){

                con = constraints[ i ];

                // move constrained bodies to target length based on their
                // mass proportions
                A.clone( con.bodyA.state.pos );
                BA.clone( con.bodyB.state.pos ).vsub( A );
                len = BA.norm();
                corr = ( len - con.targetLength ) / len;

                BA.mult( corr );
                proportion = con.bodyB.mass / (con.bodyA.mass + con.bodyB.mass);

                if ( !con.bodyA.fixed ){

                    BA.mult( proportion );
                    con.bodyA.state.pos.vadd( BA );
                    BA.mult( 1 / proportion );
                }

                if ( !con.bodyB.fixed ){

                    BA.mult( 1 - proportion );
                    con.bodyB.state.pos.vsub( BA );
                }
            }

            scratch.done();
        },

        /**
         * Get an array of all constraints
         * @return {Array} The array of constraint objects
         */
        getConstraints: function(){

            return [].concat(this._constraints);
        }
    };
});


text:
from __future__ import absolute_import
import os
import errno
import threading
import time
import logging

from cpy2py.kernel import state
from cpy2py.twinterpreter import bootstrap
from cpy2py.ipyc import fifo_pipe

from .main_module import TwinMainModule
from . import exceptions
from .interpreter import Interpreter
from ._kernel import TwinKernelMaster

class TwinMaster(object):
    """
    Manager for a twinterpeter

    Spawns, configures and supervises the actual interpeter process. In order to
    use any twinterpeters, a corresponding TwinMaster must be created and its
    :py:meth:`TwinMaster.start` method called.

    :param executable: path to executable of secondary interpreter
    :type executable: str or None
    :param twinterpreter_id: identified for the twinterpreter
    :type twinterpreter_id: str or None
    :param kernel: the type of kernel to use to connect interpreters
    :param ipyc: the type of interprocess communication to use
    """
    _initialized = False

    #: singleton store `twinterpreter_id` => `master`
    _master_store = {}
    _store_mutex = threading.RLock()

    def __init__(
            self, executable=None, twinterpreter_id=None, kernel=None, main_module=True, run_main=None,
            restore_argv=False, ipyc=fifo_pipe.DuplexFifoIPyC
    ):
        # avoid duplicate initialisation of singleton
        with self._store_mutex:
            self._interpreter = Interpreter(executable or twinterpreter_id)
            self.twinterpreter_id = twinterpreter_id or os.path.basename(executable)
            if twinterpreter_id in self._master_store:
                raise RuntimeError('Attempt to overwrite existing Master for %r' % twinterpreter_id)
            self._master_store[self.twinterpreter_id] = self
            self.main_def = TwinMainModule(main_module, run_main, restore_argv)
            self._logger = logging.getLogger(
                '__cpy2py__.twin.%s_to_%s.master' % (state.TWIN_ID, self.twinterpreter_id)
            )
            self._process = None
            self._kernel_master = TwinKernelMaster(twin_id=self.twinterpreter_id, kernel=kernel, ipyc=ipyc, protocol=self._interpreter.pickle_protocol)

    @property
    def native(self):
        """Whether the master defines its own controlling scope"""
        return state.is_twinterpreter(self.twinterpreter_id)

    @property
    def is_alive(self):
        """Whether the twinterpeter process is alive"""
        if self._process is not None:
            try:
                os.kill(self._process.pid, 0)
            except OSError as err:
                if err.errno == errno.EPERM:  # not allowed to kill EXISTING process
                    return True
                if err.errno != errno.ESRCH:
                    raise
                # no such process anymore, cleanup
                self._cleanup()
                return False
            else:
                return True
        assert self._process is None and not self._kernel_master.alive,\
            "Client, Server and Process must have been realeased together"
        return False

    def start(self):
        """
        Start the twinterpeter if it is not alive

        :returns: whether the twinterpeter is alive
        """
        if self.native:
            return True
        if self._master_store.get(self.twinterpreter_id) is not self:
            raise RuntimeError("Attempt to start TwinMaster after destroying it")
        if not self.is_alive:
            self._logger.warning('<%s> Starting Twin [%s]', state.TWIN_ID, self.twinterpreter_id)
            self._process = self._interpreter.spawn(
                arguments=self._twin_args(),
                environment=self._twin_env()
            )
            time.sleep(0.1)  # sleep while child initializes
            if self._process.poll() is not None:
                raise exceptions.TwinterpreterProcessError(
                    'Twinterpreter process failed at start with %s' % self._process.poll()
                )
            self._kernel_master.accept()
            # finalize the twinterpreter
            state.TWIN_GROUP_STATE.run_finalizers(self.twinterpreter_id)
            self._logger.info('<%s> Initialized Twin [%s]', state.TWIN_ID, self.twinterpreter_id)
        else:
            self._logger.warning('<%s> Reusing Twin [%s]', state.TWIN_ID, self.twinterpreter_id)
        return self.is_alive

    def _twin_args(self):
        """Create the twin's CLI args"""
        twin_args = []
        # preserve -O
        if not __debug__:
            twin_args.append('-O')
        # bootstrap
        twin_args.extend((
                '-m', 'cpy2py.twinterpreter.bootstrap',
                '--peer-id', state.TWIN_ID,
                '--twin-id', self.twinterpreter_id,
                '--master-id', state.MASTER_ID,
                '--main-def', bootstrap.dump_main_def(self.main_def),
                '--cwd', os.getcwd(),
                ))
        twin_args.extend(self._kernel_master.cli_args)
        twin_args.append('--initializer')
        twin_args.extend(bootstrap.dump_initializer(state.TWIN_GROUP_STATE.initializers))
        return twin_args

    def _twin_env(self):
        """Create the twin's starting environment"""
        twin_env = os.environ.copy()
        twin_env['__CPY2PY_TWIN_ID__'] = self.twinterpreter_id
        twin_env['__CPY2PY_MASTER_ID__'] = state.MASTER_ID
        return twin_env

    def stop(self):
        """Terminate the twinterpreter"""
        self._cleanup()
        return self.is_alive

    def destroy(self):
        """Stop any twinterpreter and cleanup the master"""
        self.stop()
        del self._master_store[self.twinterpreter_id]
        self._logger.info('<%s> Destroyed Twin [%s]', state.TWIN_ID, self.twinterpreter_id)

    def _cleanup(self):
        """Try and close all connections"""
        self._kernel_master.shutdown()
        if self._process is not None:
            # allow twin to shut down before killing it outright
            shutdown_time = time.time()
            while self._process.poll() is None:
                time.sleep(0.1)
                if time.time() - shutdown_time > 5:
                    self._process.kill()
            if self._process.poll() is not None:
                self._process = None
                self._logger.info('<%s> Cleaned up Twin Process [%s]', state.TWIN_ID, self.twinterpreter_id)

    def execute(self, call, *call_args, **call_kwargs):
        """
        Invoke a callable

        :param call: callable to invoke
        :type call: callable
        :param call_args: positional arguments to `call`
        :param call_kwargs: keyword arguments to `call`
        :returns: result of `call(*call_args, **call_kwargs)`
        """
        if self.native:
            return call(*call_args, **call_kwargs)
        return self._kernel_master.client.request_dispatcher.dispatch_call(call, *call_args, **call_kwargs)

class AutoTwinMaster(TwinMaster):
    """
    Any :py:class:`TwinMaster` that is automatically created and started when no twin exists
    """
    def __init__(self, twinterpreter_id):
        with self._store_mutex:
            try:
                existing_master = self._master_store[twinterpreter_id]
            except KeyError:
                # explicitly supply safe defaults
                super(AutoTwinMaster, self).__init__(
                    executable=None, twinterpreter_id=twinterpreter_id,
                    kernel='async', ipyc=fifo_pipe.DuplexFifoIPyC,
                    main_module=True, run_main=False, restore_argv=True,
                )
                self.start()
            else:
                existing_master.start()


text:
class Ccc::SimplesecuritymanagerUser < ActiveRecord::Base

  self.primary_key = 'userID'
  self.table_name = 'simplesecuritymanager_user'

  has_one :sp_user, class_name: 'Ccc::SpUser'
  has_one :mpd_user, class_name: 'Ccc::MpdUser', foreign_key: :user_id, dependent: :destroy
  has_one :infobase_user, foreign_key: :user_id, class_name: 'Ccc::InfobaseUser', dependent: :destroy
  has_one :si_user, foreign_key: :ssm_id, class_name: 'Ccc::SiUser', foreign_key: 'ssm_id'
  has_one :pr_user, foreign_key: :ssm_id, class_name: 'Ccc::PrUser', dependent: :destroy, foreign_key: 'ssm_id'
  has_many :authentications, class_name: 'Ccc::Authentication', foreign_key: 'user_id'
  has_one :person, class_name: 'Ccc::Person', foreign_key: 'fk_ssmUserId'

  def merge(other)
    Ccc::SimplesecuritymanagerUser.connection.execute('SET foreign_key_checks = 0')

    Ccc::SimplesecuritymanagerUser.transaction do

      if !other.globallyUniqueID.blank? && self.globallyUniqueID.blank?
        self.globallyUniqueID = other.globallyUniqueID
        other.globallyUniqueID = nil
      end

      person.merge(other.person) if person && other.person

      # Authentications
      other.authentications.collect {|oa| oa.update_attribute(:user_id, id)}

      if other.mpd_user && mpd_user
        mpd_user.merge(other.mpd_user)
      elsif other.mpd_user
        other.mpd_user.update_attribute(:user_id, userID)
      end

      if other.infobase_user && infobase_user
        infobase_user.merge(other.infobase_user)

      elsif other.infobase_user
        other.infobase_user.update_attribute(:user_id, userID)
      end

      if other.pr_user && pr_user
        other.pr_user.destroy
      elsif other.pr_user
        other.pr_user.update_attribute(:ssm_id, userID)
      end

      if other.si_user && si_user
        other.si_user.destroy
      elsif other.si_user
        Ccc::SiUser.where(["ssm_id = ? or created_by_id = ?", other.userID, other.userID]).each do |ua|
          ua.update_attribute(:ssm_id, userID) if ua.ssm_id == other.userID
          ua.update_attribute(:created_by_id, personID) if ua.created_by_id == other.userID
        end
      end

      begin
        other.needs_merge = nil
        other.save(validate: false)
        self.needs_merge = nil
        save(validate: false)
      rescue ActiveRecord::ReadOnlyRecord

      end
    end

    Ccc::MergeAudit.create!(mergeable: self, merge_looser: other)
    other.reload
    other.destroy

    Ccc::SimplesecuritymanagerUser.connection.execute('SET foreign_key_checks = 1')

  end
end


text:
title: Oracle 1.1 Transaction
layout: report
date: 2016-10-08
task: 01_Instance Uebung_001
taskHref: http://griesmayer.com/?menu=Oracle&semester=Semester_3&topic=01_Transaction
subject: dbi
---
# Lösungen für die Aufgabenstellung befinden sich im Anhang!