text:
module Listen
  module QueueOptimizer
    private

    def _smoosh_changes(changes)
      # TODO: adapter could be nil at this point (shutdown)
      if _adapter_class.local_fs?
        cookies = changes.group_by do |_, _, _, _, options|
          (options || {})[:cookie]
        end
        _squash_changes(_reinterpret_related_changes(cookies))
      else
        smooshed = { modified: [], added: [], removed: [] }
        changes.each do |_, change, dir, rel_path, _|
          smooshed[change] << (dir + rel_path).to_s if smooshed.key?(change)
        end
        smooshed.tap { |s| s.each { |_, v| v.uniq! } }
      end
    end

    # groups changes into the expected structure expected by
    # clients
    def _squash_changes(changes)
      # We combine here for backward compatibility
      # Newer clients should receive dir and path separately
      changes = changes.map { |change, dir, path| [change, dir + path] }

      actions = changes.group_by(&:last).map do |path, action_list|
        [_logical_action_for(path, action_list.map(&:first)), path.to_s]
      end
      _log :info, "listen: raw changes: #{actions.inspect}"

      { modified: [], added: [], removed: [] }.tap do |squashed|
        actions.each do |type, path|
          squashed[type] << path unless type.nil?
        end
        _log :info, "listen: final changes: #{squashed.inspect}"
      end
    end

    def _logical_action_for(path, actions)
      actions << :added if actions.delete(:moved_to)
      actions << :removed if actions.delete(:moved_from)

      modified = actions.detect { |x| x == :modified }
      _calculate_add_remove_difference(actions, path, modified)
    end

    def _calculate_add_remove_difference(actions, path, default_if_exists)
      added = actions.count { |x| x == :added }
      removed = actions.count { |x| x == :removed }
      diff = added - removed

      # TODO: avoid checking if path exists and instead assume the events are
      # in order (if last is :removed, it doesn't exist, etc.)
      if path.exist?
        if diff > 0
          :added
        elsif diff.zero? && added > 0
          :modified
        else
          default_if_exists
        end
      else
        diff < 0 ? :removed : nil
      end
    end

    # remove extraneous rb-inotify events, keeping them only if it's a possible
    # editor rename() call (e.g. Kate and Sublime)
    def _reinterpret_related_changes(cookies)
      table = { moved_to: :added, moved_from: :removed }
      cookies.map do |_, changes|
        data = _detect_possible_editor_save(changes)
        if data
          to_dir, to_file = data
          [[:modified, to_dir, to_file]]
        else
          not_silenced = changes.reject do |type, _, _, path, _|
            _silenced?(Pathname(path), type)
          end
          not_silenced.map do |_, change, dir, path, _|
            [table.fetch(change, change), dir, path]
          end
        end
      end.flatten(1)
    end

    def _detect_possible_editor_save(changes)
      return unless changes.size == 2

      from_type = from_change = from = nil
      to_type = to_change = to_dir = to = nil

      changes.each do |data|
        case data[1]
        when :moved_from
          from_type, from_change, _, from, _ = data
        when :moved_to
          to_type, to_change, to_dir, to, _ = data
        else
          return nil
        end
      end

      return unless from && to

      # Expect an ignored moved_from and non-ignored moved_to
      # to qualify as an "editor modify"
      return unless _silenced?(Pathname(from), from_type)
      _silenced?(Pathname(to), to_type) ? nil : [to_dir, to]
    end
  end
end


text:
package com.sequenceiq.freeipa.audit.flow;

import java.util.List;
import java.util.Optional;

import javax.inject.Inject;

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.audit.model.AuditEventName;
import com.sequenceiq.cloudbreak.structuredevent.event.FlowDetails;
import com.sequenceiq.cloudbreak.structuredevent.event.cdp.CDPStructuredFlowEvent;
import com.sequenceiq.cloudbreak.structuredevent.service.audit.auditeventname.flow.CDPFlowOperationAuditEventNameConverter;
import com.sequenceiq.cloudbreak.structuredevent.service.audit.auditeventname.flow.CDPFlowResourceAuditEventConverter;

@Component("freeipaFlowAuditEventNameConverter")
public class FreeIpaFlowAuditEventNameConverter implements CDPFlowResourceAuditEventConverter {

    @Inject
    private List<CDPFlowOperationAuditEventNameConverter> converters;

    @Override
    public AuditEventName auditEventName(CDPStructuredFlowEvent structuredEvent) {
        Optional<CDPFlowOperationAuditEventNameConverter> converter = converters.stream()
                .filter(c -> c.isInit(structuredEvent) || c.isFailed(structuredEvent) || c.isFinal(structuredEvent))
                .findFirst();
        return converter.map(CDPFlowOperationAuditEventNameConverter::eventName).orElse(null);
    }

    @Override
    public boolean shouldAudit(CDPStructuredFlowEvent structuredEvent) {
        FlowDetails flow = structuredEvent.getFlow();
        return "INIT_STATE".equals(flow.getFlowState()) || "FINAL_STATE".equals(flow.getNextFlowState());
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace cpp_ex4 {
	// Forward declarations.--------------------------
	class StopMap;
	class StopMap_EastWestGreen;
	class StopMap_EastWestYellow;
	class StopMap_NorthSouthGreen;
	class StopMap_NorthSouthYellow;
	class StopMap_Default;
	class StoplightState;
	template<typename Derived> class StoplightContext;
	class Stoplight;

	// Class State.-----------------------------------
	class StoplightState : public statemap::State {
	public:
		StoplightState(const char *name, int no) : statemap::State(name, no) {};

		virtual void Entry(StoplightContext<Stoplight>&) {};
		virtual void Exit(StoplightContext<Stoplight>&) {};

		virtual void Timeout(StoplightContext<Stoplight>& context);
		virtual void Timeout(StoplightContext<Stoplight>& context, LightColors t);
	protected:
		virtual void Default(StoplightContext<Stoplight>& context);
	};

	// FSM map default state class.-------------------
	class StopMap_Default : public StoplightState {
	public:
		StopMap_Default (const char *name, int stateId) : StoplightState(name, stateId)	{}
	};

	// FSM map states class.--------------------------
	// --------------------------------------------------
	class StopMap_EastWestGreen:  public StopMap_Default {
	public:
		StopMap_EastWestGreen(const char* name, int no) : StopMap_Default(name, no) {}

		void Entry(StoplightContext<Stoplight>& context);

		void Timeout(StoplightContext<Stoplight>& context, LightColors t);
	};

	// --------------------------------------------------
	class StopMap_EastWestYellow:  public StopMap_Default {
	public:
		StopMap_EastWestYellow(const char* name, int no) : StopMap_Default(name, no) {}

		void Entry(StoplightContext<Stoplight>& context);

		void Timeout(StoplightContext<Stoplight>& context);
	};

	// --------------------------------------------------
	class StopMap_NorthSouthGreen:  public StopMap_Default {
	public:
		StopMap_NorthSouthGreen(const char* name, int no) : StopMap_Default(name, no) {}

		void Entry(StoplightContext<Stoplight>& context);

		void Timeout(StoplightContext<Stoplight>& context);
	};

	// --------------------------------------------------
	class StopMap_NorthSouthYellow:  public StopMap_Default {
	public:
		StopMap_NorthSouthYellow(const char* name, int no) : StopMap_Default(name, no) {}

		void Entry(StoplightContext<Stoplight>& context);

		void Timeout(StoplightContext<Stoplight>& context);
	};

	// FSM map class.---------------------------------
	class StopMap {
	public:
		StopMap();
		StopMap_EastWestGreen EastWestGreen;
		StopMap_EastWestYellow EastWestYellow;
		StopMap_NorthSouthGreen NorthSouthGreen;
		StopMap_NorthSouthYellow NorthSouthYellow;
	};

	// FSM context class -----------------------------
	template<typename Derived>
	class StoplightContext : public statemap::FSMContext, public StopMap {
	public:
		explicit
		StoplightContext() : FSMContext(StopMap::NorthSouthGreen) {};
		StoplightContext(const statemap::State& state) : FSMContext(state) {};

		void setStartState(const statemap::State& state) {
			setState(state);
		}

		virtual void enterStartState() {
		    getState().Entry(*this);
		    return;
		}

		Derived& getOwner() {
		    return (*static_cast<Derived*>(this));
		};

		const Derived& getOwner() const {
		    return (*static_cast<const Derived*>(this));
		};

		StoplightState& getState() const {
		    if (_state == nullptr) {
		        throw statemap::StateUndefinedException();
		    }
		     return (dynamic_cast<StoplightState&>(*_state));
		};

		void Timeout() {
		    setTransition("Timeout");
		    getState().Timeout(*this);
		    setTransition(nullptr);
		};
		void Timeout(LightColors t) {
		    setTransition("Timeout");
		    getState().Timeout(*this, t);
		    setTransition(nullptr);
		};
	};
}
#endif


text:
Copyright (c) 2015-2018 Blaine Rister et al., see LICENSE for details.

## Installing from binaries

You can install SIFT3D in one of two ways, from binaries or from source. The easiest way is to install from binaries. Simply visit our [releases](https://github.com/bbrister/SIFT3D/releases) page, download the appropriate installer for your system, and run it.

## Installing from source

*This is a difficult process on Windows, recommended only for advanced users.*

This program has been successfully compiled and executed on the following Windows platforms:
* Windows 10 64-bit, using [TDM-GCC](http://tdm-gcc.tdragon.net/) 5.10 and CMake 3.3.1
* Windows 8 64-bit, using the same
* Windows 7 64-bit, using the same

In addition, the compiled C libraries have been linked to on the following platforms:
* Windows 7 64-bit, using Visual Studio 2012

Please follow the instructions below to compile and install SIFT3D from source.

1. Install [CMake](http://www.cmake.org).

2. Install MinGW via [TDM-GCC](http://tdm-gcc.tdragon.net/)
	1. Download the installer
	2. Run the installer and remember to select the GCC packages C, C++, Fortran and OpenMP
		* OpenMP is for optional multithreading, the rest are mandatory

3. Use [gnumex](http://gnumex.sourceforge.net/documentation.html#L131) to hack Matlab to compile MEX files with MinGW. *This needed only for the Matlab toolbox. Non-Matlab users can skip this step.*
	1. Download and extract gnumex
	2. Run Matlab as an administrator
	3. Run the "gnumex" program from within Matlab
	4. Make sure the required paths are detected
	5. Generate the files
	6. Run "mex -setup" from within Matlab. If all goes well, GCC will show up as an option. Follow the prompt to set up MEX with GCC.

4. Install [LAPACK for Windows](http://icl.cs.utk.edu/lapack-for-windows/lapack/index.html#libraries). *(Note: Any other BLAS/LAPACK package should work as well. I have had success compiling* [OpenBlas](http://www.openblas.net/) *with MinGW and CMake.)*
	1. Download the binaries for MinGW and your verison of Windows (lapack.dll, blas.dll)
	2. Move lapack.dll and blas.dll to the TDM-GCC/bin directory

5. Install [zlib](http://zlib.net/).
	1. Download and extract the most recent version
	2. Use the CMake GUI to generate MinGW Makefiles
		1. Set the source folder to the location of zlib
		2. Generate -> MinGW Makefiles
	3. Compile and install with MinGW
		1. cd to the build directory
		2. "mingw32-make"
		3. "mingw32-make install" (may require administrator privileges)

6. Install [nifticlib](http://sourceforge.net/projects/niftilib/files/nifticlib/). *This step is needed only for NIFTI I/O. Users not needing to read and write NIFTI files can skip this step.*
	1. Download and extract the newest version
	2. Generate MinGW Makefiles with CMake
		1. Set the source folder to the location of nifticlib
		2. Generate -> MinGW Makefiles
                        * You may have to set the variable ZLIB_LIBRARY to the directory where zlib was installed.
	3. Compile and install with MinGW
		1. cd to build directory
		2. "mingw32-make"
		3. "mingw32-make install" (may require administrator privileges)

7. Install [DCMTK](http://www.dcmtk.org). *This step is needed only for DICOM I/O. Users not needing to read and write DICOM files can skip this step.*
	1. Download and extract the newest version. If there is a binary installer for your version of Windows, you can use that and skip the following sections. As of 10/06/2015, there is no binary for 64-bit Windows, so we compiled DCMTK from source. *Note: We could not compile DCMTK 3.6.0 on Windows with CMake and MinGW. Instead, we used a snapshot of version 3.6.1, retrieved on 09/24/2015.*
	2. Generate MinGW Makefiles with CMake
		1. Set the source folder to the location of DCMTK
		2. Generate -> MinGW Makefiles
	3. Compile and install with MinGW
		1. cd to build directory
		2. "mingw32-make"
		3. "mingw32-make install" (may require administrator privileges)

8. Install SIFT3D.
	1. Download this repository
	2. Generate MinGW Makefiles with CMake
		1. Navigate to SIFT3D
		2. Select "MinGW Makefiles"
                3. Configure
                4. Configuration may fail if CMake cannot find the dependencies. If so, set the appropriate variables and configure again.
                        1. If configuration fails due to zlib, check 'advanced' and set all ZLIB_* variables to the appropriate paths. For example, set ZLIB_LIBRARY (or ZLIB_LIBRARY_RELEASE) to libzlib.dll and ZLIB_INCLUDE_DIR to the include directory of your zlib installation.
		        2. If configuration fails due to DCMTK, set DCMTK_DIR to the install location of DCMTK.
		        3. If configuration fails due to NIFTI, set NIFTI_DIR to the install location of nifticlib.
		5. *Note: this step applies only to users compiling the optional Matlab toolbox.* Ensure that the Matlab libraries are .dll's and not .lib's. Manually edit the paths for Matlab_MEX_LIBRARY, Matlab_MX_LIBRARY, MWLAPACK_LIBRARY, and MWBLAS_LIBRARY, so that "libmex.lib" is changed to "libmex.dll", etc. This requires locating these files within your Matlab installation. Check the "bin" directories for .dll's.
		6. Generate -> MinGW Makefiles
	3. Compile and install with MinGW
		1. cd to the build directory
		2. "mingw32-make"
		3. "mingw32-make install" (may require administrator privileges)
### Packaging

To create your own binary package, set the BUILD_PACKAGE variable to ON in the CMake GUI. Then build the 'package' target using the Makefiles. For example,

        mingw32-make package

## Caveats

This program was originally developed for Unix-like platforms, so some features have been disabled in the Windows version.

* By default, the command line interface is not compiled on Windows systems. If you wish to compile it, you can set the CMake variable BUILD_CLI to ON. This is not officially supported, and the resulting executables may not function correctly. The good news is that you can still access SIFT3D through the C libraries and wrappers for other languages.

* There are problems writing .nii.gz files in Windows. Note that all other image formats still work, including .nii without gzip compression. From the Matlab wrapper function imWrite3D, we work around this issue by first writing the .nii file, then compressing with a Matlab function call. However, you may experience issues when writing a .nii.gz file from the C library function im_write.


text:
<?php

final class PhabricatorTimelineExample extends PhabricatorUIExample {

  public function getName() {
    return 'Timeline View';
  }

  public function getDescription() {
    return hsprintf(
      'Use <tt>PhabricatorTimelineView</tt> to comments and transactions.');
  }

  public function renderExample() {
    $request = $this->getRequest();
    $user = $request->getUser();

    $handle = PhabricatorObjectHandleData::loadOneHandle(
      $user->getPHID(),
      $user);

    $events = array();

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle('A major event.')
      ->appendChild('This is a major timeline event.');

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle('A minor event.');

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->appendChild('A major event with no title.');

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle('Another minor event.');

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle);

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle('Major Red Event')
      ->setIcon('love')
      ->appendChild('This event is red!')
      ->setColor(PhabricatorTransactions::COLOR_RED);

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle('Minor Red Event')
      ->setColor(PhabricatorTransactions::COLOR_RED);

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle('Minor Not-Red Event');

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle('Minor Red Event')
      ->setColor(PhabricatorTransactions::COLOR_RED);

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle('Minor Not-Red Event');

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle('Major Green Event')
      ->appendChild('This event is green!')
      ->setColor(PhabricatorTransactions::COLOR_GREEN);

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle(str_repeat('Long Text Title ', 64))
      ->appendChild(str_repeat('Long Text Body ', 64))
      ->setColor(PhabricatorTransactions::COLOR_ORANGE);

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle(str_repeat('LongTextEventNoSpaces', 1024))
      ->appendChild(str_repeat('LongTextNoSpaces', 1024))
      ->setColor(PhabricatorTransactions::COLOR_RED);

    $colors = array(
      PhabricatorTransactions::COLOR_RED,
      PhabricatorTransactions::COLOR_ORANGE,
      PhabricatorTransactions::COLOR_YELLOW,
      PhabricatorTransactions::COLOR_GREEN,
      PhabricatorTransactions::COLOR_SKY,
      PhabricatorTransactions::COLOR_BLUE,
      PhabricatorTransactions::COLOR_INDIGO,
      PhabricatorTransactions::COLOR_VIOLET,
      PhabricatorTransactions::COLOR_GREY,
      PhabricatorTransactions::COLOR_BLACK,
    );

    $events[] = id(new PhabricatorTimelineEventView())
      ->setUserHandle($handle)
      ->setTitle("Colorless")
      ->setIcon('lock');

    foreach ($colors as $color) {
      $events[] = id(new PhabricatorTimelineEventView())
        ->setUserHandle($handle)
        ->setTitle("Color '{$color}'")
        ->setIcon('lock')
        ->setColor($color);
    }

    $anchor = 0;
    foreach ($events as $event) {
      $event->setUser($user);
      $event->setDateCreated(time() + ($anchor * 60 * 8));
      $event->setAnchor(++$anchor);
    }

    $timeline = id(new PhabricatorTimelineView());
    foreach ($events as $event) {
      $timeline->addEvent($event);
    }

    return $timeline;
  }
}


text:
The scripts and data in this directory automate creation and configuration of a QingYuan cluster, including networking, DNS, nodes, and master components.

See the [getting-started guides](../docs/getting-started-guides) for examples of how to use the scripts.

*cloudprovider*/`config-default.sh` contains a set of tweakable definitions/parameters for the cluster.

The heavy lifting of configuring the VMs is done by [SaltStack](http://www.saltstack.com/).

[![Analytics](https://qingyuan-site.appspot.com/UA-36037335-10/GitHub/cluster/README.md?pixel)]()


text:
package de.unioninvestment.eai.portal.support.scripting;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.util.HashMap;
import java.util.Map;

import javax.management.MBeanServerConnection;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

public class JMXProviderTest {
	private JMXProvider jmxProvider;

	@Before
	public void setUp() {
		jmxProvider = new JMXProvider(this);
	}

	@Test
	public void shouldReturnJMXWrapperInstance() {
		ScriptJMXWrapper jmxWrapper = jmxProvider.doCall();

		assertThat(jmxWrapper, is(ScriptJMXWrapper.class));
	}

	@SuppressWarnings("rawtypes")
	@Test
	public void shouldReturnJMXWrapperInstanceForConnectionArgs() {
		ScriptJMXWrapper jmxWrapper = jmxProvider.doCall(new HashMap());
		assertThat(jmxWrapper, is(ScriptJMXWrapper.class));

		jmxWrapper = jmxProvider.doCall((Map) null);
		assertThat(jmxWrapper, is(ScriptJMXWrapper.class));
	}

	@Test
	public void shouldReturnJMXWrapperInstanceForURL() {
		ScriptJMXWrapper jmxWrapper = jmxProvider
				.doCall("service:jmx:rmi:///jndi/rmi://server:1090/jmxconnector");

		assertThat(jmxWrapper, is(ScriptJMXWrapper.class));

		jmxWrapper = jmxProvider.doCall((String) null);
		assertThat(jmxWrapper, is(ScriptJMXWrapper.class));
	}

	@Test
	public void shouldReturnJMXWrapperInstanceForServerAndPort() {
		ScriptJMXWrapper jmxWrapper = jmxProvider.doCall("server:1090");

		assertThat(jmxWrapper, is(ScriptJMXWrapper.class));
	}

	@Test
	public void shouldReturnJMXWrapperInstanceForMBeanServerConnection() {
		MBeanServerConnection mbeanServerConnectionMock = Mockito
				.mock(MBeanServerConnection.class);
		ScriptJMXWrapper jmxWrapper = jmxProvider
				.doCall(mbeanServerConnectionMock);

		assertThat(jmxWrapper, is(ScriptJMXWrapper.class));

		jmxWrapper = jmxProvider.doCall((MBeanServerConnection) null);
		assertThat(jmxWrapper, is(ScriptJMXWrapper.class));
	}
}


text:
(function()
{
    const Periodic = require( 'Periodic' );
    const Listener = require( 'Listener' );

    // Encoding helper functions
    function encode( floatIn )
    {
        return parseInt( floatIn * 1000 );
    }

    function decode( intIn )
    {
        return ( intIn * 0.001 );
    }

    class ExternalLights
    {
        constructor(name, deps)
        {
            deps.logger.debug( 'ExternalLights plugin loaded' );

            this.globalBus  = deps.globalEventLoop;
            this.cockpitBus = deps.cockpit;

            this.targetPower          = 0;
            this.targetPower_enc      = 0;
            this.mcuTargetPower_enc   = 0;

            var self = this;

            this.SyncTargetPower = new Periodic( 33, "timeout", function()
            {
                var synced = true;

                // Send target power to MCU until it responds with affirmation
                if( self.mcuTargetPower_enc !== self.targetPower_enc )
                {
                    synced = false;

                    // Encode floating point to integer representation
                    var command = 'elights_tpow(' + self.targetPower_enc + ')';

                    // Emit command to mcu
                    self.globalBus.emit( 'mcu.SendCommand', command );
                }

                if( synced )
                {
                    // No need to continue
                    self.SyncTargetPower.stop();
                }
            });

            this.listeners =
            {
                settings: new Listener( this.globalBus, 'settings-change.external-lights', true, function( settings )
                {
                    // Apply settings
                    self.settings = settings.lights;

                    // Emit settings update to cockpit
                    self.cockpitBus.emit( 'plugin.externalLights.settingsChange', self.settings );

                    // Enable MCU Status listener
                    self.listeners.mcuStatus.enable();

                    // Enable API
                    self.listeners.setTargetPower.enable();
                }),

                mcuStatus: new Listener( this.globalBus, 'mcu.status', false, function( data )
                {
                    // Current light power
                    if( 'elights_pow' in data )
                    {
                        // Convert from integer to float
                        var power = decode( parseInt( data.elights_pow ) );

                        // Emit on cockpit bus for UI purposes
                        self.cockpitBus.emit( 'plugin.externalLights.currentPower', power );
                    }

                    // Target light power
                    if( 'elights_tpow' in data )
                    {
                        // Save encoded version for sync validation purposes
                        self.mcuTargetPower_enc = parseInt( data.elights_tpow );

                        // Convert from integer to float
                        var power = decode( self.mcuTargetPower_enc );

                        // Emit the real target power on the cockpit bus for UI purposes
                        self.cockpitBus.emit( 'plugin.externalLights.targetPower', power );
                    }
                }),

                setTargetPower: new Listener( this.cockpitBus, 'plugin.externalLights.setTargetPower', false, function( powerIn )
                {
                    // Set new target Power
                    self.setTargetPower( powerIn );
                })
            }
        }

        setTargetPower( powerIn )
        {
            var self = this;

            // Validate input
            if( isNaN( powerIn ) )
            {
              // Ignore
              return;
            }

            // Apply limits
            if( powerIn > 1.0 )
            {
                self.targetPower = 1.0;
            }
            else if( powerIn < 0 )
            {
                self.targetPower = 0;
            }
            else
            {
                self.targetPower = powerIn;
            }

            self.targetPower_enc = encode( self.targetPower );

            // Start targetPower sync, if not already running
            self.SyncTargetPower.start();
        }

        start()
        {
          this.listeners.settings.enable();
        }

        stop()
        {
          this.listeners.settings.disable();
          this.listeners.mcuStatus.disable();
          this.listeners.setTargetPower.disable();
        }

        getSettingSchema()
        {
            //from http://json-schema.org/examples.html
            return [{
                'title': 'External Lights',
                'type': 'object',
                'id': 'external-lights',
                'managedBy': '_hidden',
                'properties': {},
                'required': []
            }];
        }
    }

    module.exports = function(name, deps)
    {
        if( process.env.PRODUCTID == "trident" )
        {
            deps.logger.debug( "External Lights Not supported on trident" );
            return {};
        }

        return new ExternalLights(name, deps);
    };
}());


text:
package wsa.fromwsdl.fault.client;

import junit.framework.TestCase;

/**
 * @author Arun Gupta
 */
public class AddNumbersClient extends TestCase {
    public AddNumbersClient(String name) {
        super(name);
    }

    private AddNumbersPortType createStub() throws Exception {
        return new AddNumbersService().getAddNumbersPort();
    }

    public void testAddNumbersDefaultAddNumbersAction() throws Exception {
        try {
            createStub().addNumbers(-10, 10);
            fail("AddNumbersFault_Exception must be thrown");
        } catch (AddNumbersFault_Exception ex)  {
            assertTrue(true);
        }
    }

    public void testAddNumbersDefaultTooBigNumbersAction() throws Exception {
        try {
            createStub().addNumbers(20, 20);
            fail("TooBigNumbersFault_Exception must be thrown");
        } catch (TooBigNumbersFault_Exception ex)  {
            assertTrue(true);
        }
    }

    public void testAddNumbers2ExplicitAddNumbersAction() throws Exception {
        try {
            createStub().addNumbers2(-10, 10);
            fail("AddNumbers2Fault must be thrown");
        } catch (AddNumbers2Fault ex)  {
            assertTrue(true);
        }
    }

    public void testAddNumbers2ExplicitTooBigNumbersAction() throws Exception {
        try {
            createStub().addNumbers2(20, 20);
            fail("TooBigNumbers2Fault must be thrown");
        } catch (TooBigNumbers2Fault ex)  {
            assertTrue(true);
        }
    }

    public void testAddNumbers3ExplicitAddNumbersAction() throws Exception {
        try {
            createStub().addNumbers3(-10, 10);
            fail("AddNumbers3Fault must be thrown");
        } catch (AddNumbers3Fault ex)  {
            assertTrue(true);
        }
    }

    public void testAddNumbers3DefaultTooBigNumbersAction() throws Exception {
        try {
            createStub().addNumbers3(20, 20);
            fail("TooBigNumbers3Fault must be thrown");
        } catch (TooBigNumbers3Fault ex)  {
            assertTrue(true);
        }
    }

    public void testAddNumbers4DefaultAddNumbersAction() throws Exception {
        try {
            createStub().addNumbers4(-10, 10);
            fail("AddNumbersFault must be thrown");
        } catch (AddNumbers4Fault ex)  {
            assertTrue(true);
        }
    }

    public void testAddNumbers4ExplicitTooBigNumbersAction() throws Exception {
        try {
            createStub().addNumbers4(20, 20);
            fail("TooBigNumbers4Fault must be thrown");
        } catch (TooBigNumbers4Fault ex)  {
            assertTrue(true);
        }
    }

    public void testAddNumbers5ExplicitAddNumbersAction() throws Exception {
        try {
            createStub().addNumbers5(-10, 20);
            fail("AddNumbers5Fault must be thrown");
        } catch (AddNumbers5Fault ex)  {
            assertTrue(true);
        }
    }

    public void testAddNumbers6EmptyAddNumbersAction() throws Exception {
        try {
            createStub().addNumbers6(-10, 20);
            fail("AddNumbers6Fault must be thrown");
        } catch (AddNumbers6Fault ex)  {
            assertTrue(true);
        }
    }
}


text:
package org.onosproject.store.consistent.impl;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import org.onosproject.store.service.AtomicValue;
import org.onosproject.store.service.AtomicValueEvent;
import org.onosproject.store.service.AtomicValueEventListener;
import org.onosproject.store.service.ConsistentMap;
import org.onosproject.store.service.MapEvent;
import org.onosproject.store.service.MapEventListener;
import org.onosproject.store.service.Serializer;
import org.onosproject.store.service.Versioned;

/**
 * Default implementation of AtomicValue.
 *
 * @param <V> value type
 */
public class DefaultAtomicValue<V> implements AtomicValue<V> {

    private final Set<AtomicValueEventListener<V>> listeners = new CopyOnWriteArraySet<>();
    private final ConsistentMap<String, byte[]> valueMap;
    private final String name;
    private final Serializer serializer;
    private final MapEventListener<String, byte[]> mapEventListener = new InternalMapEventListener();

    public DefaultAtomicValue(ConsistentMap<String, byte[]> valueMap,
            String name,
            Serializer serializer) {
        this.valueMap = valueMap;
        this.name = name;
        this.serializer = serializer;
    }

    @Override
    public boolean compareAndSet(V expect, V update) {
        if (expect == null) {
            if (update == null) {
                return true;
            }
            return valueMap.putIfAbsent(name, serializer.encode(update)) == null;
        } else {
            if (update == null) {
                return valueMap.remove(name, serializer.encode(expect));
            }
            return valueMap.replace(name, serializer.encode(expect), serializer.encode(update));
        }
    }

    @Override
    public V get() {
        Versioned<byte[]> rawValue = valueMap.get(name);
        return rawValue == null ? null : serializer.decode(rawValue.value());
    }

    @Override
    public V getAndSet(V value) {
        Versioned<byte[]> previousValue = value == null ?
                valueMap.remove(name) : valueMap.put(name, serializer.encode(value));
        return previousValue == null ? null : serializer.decode(previousValue.value());
    }

    @Override
    public void set(V value) {
        getAndSet(value);
    }

    @Override
    public void addListener(AtomicValueEventListener<V> listener) {
        synchronized (listeners) {
            if (listeners.add(listener)) {
                if (listeners.size() == 1) {
                    valueMap.addListener(mapEventListener);
                }
            }
        }
    }

    @Override
    public void removeListener(AtomicValueEventListener<V> listener) {
        synchronized (listeners) {
            if (listeners.remove(listener)) {
                if (listeners.size() == 0) {
                    valueMap.removeListener(mapEventListener);
                }
            }
        }
    }

    private class InternalMapEventListener implements MapEventListener<String, byte[]> {

        @Override
        public void event(MapEvent<String, byte[]> mapEvent) {
            V newValue = mapEvent.type() == MapEvent.Type.REMOVE ? null : serializer.decode(mapEvent.value().value());
            AtomicValueEvent<V> atomicValueEvent = new AtomicValueEvent<>(name, AtomicValueEvent.Type.UPDATE, newValue);
            listeners.forEach(l -> l.event(atomicValueEvent));
        }
    }
}


text:
public class Agent{
    private int agentNumber;
    private static int agentsCreated = 0;
    private String agentName;
    public Agent(String name){
        agentNumber = agentsCreated++;
        agentName = name;
    }

    public int getAgentNumber(){
        return agentNumber;
    }

    public String getName(){
        return agentName;
    }

    public int getAgentOffset(){
        //for now return agent number
        //something more sophisticated later
        return agentNumber;
    }
}


text:
AWS Resource encryption
-------------

## Permissions
A list of permission which is required for the CMK in order AEM OpenCloud can work properly.

Managed policies are used to replace grants to the CMK.
### Permission-Type B Full-Set
Permissions required for Permission-Type B Full-Set
#### CMK Permissions
Permissions which needs to be applied to the CMK
##### EBS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| `arn:aws:iam::AWS_ACCOUNT_ID:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling` | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | None | |
| `arn:aws:iam::AWS_ACCOUNT_ID:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling` | CreateGrant, ListGrants, RevokeGrant | GrantIsForAWSResource |

##### SNS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| `arn:aws:iam::AWS_ACCOUNT_ID:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling` | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | None | |
| `arn:aws:iam::AWS_ACCOUNT_ID:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling` | CreateGrant, ListGrants, RevokeGrant | GrantIsForAWSResource |
| `cloudwatch.amazonaws.com` | GenerateDataKey, Decrypt | Service permission | |
| `sns.amazonaws.com` | GenerateDataKey, Decrypt | Service permission | |

##### DynamoDB CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### Lambda CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None| None | |

##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None| None | |

#### managed-policy permissions
Only needed if managed-policies are used rather than permission grants. Make sure that the general permissions as described in **CMK Permissions** are defined to the CMK as described.
##### EBS encryption
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| EBS CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant | |

##### SNS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| SNS CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant | |

##### DynamoDB CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### Lambda CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| Lambda CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant |

##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| S3 CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant | |

### Permission-Type B Consolidated
Permissions required for Permission-Type B Consolidated
#### CMK Permissions
Permissions which needs to be applied to the CMK
#### EBS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

#### SNS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

#### DynamoDB CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

#### Lambda CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| None| None | |

##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None| None | |

#### managed-policy permissions
Only needed if managed-policies are used rather than permission grants. Make sure that the general permissions as described in **CMK Permissions** are defined to the CMK as described.
##### EBS encryption
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| EBS CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant | |

#### SNS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None | None | | |

##### DynamoDB CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### Lambda CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| S3 CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant | |

### Permission-Type B AEM Stack Manager
Permissions required for Permission-Type B AEM Stack Manager.
#### CMK Permissions
Permissions which needs to be applied to the CMK.
##### EBS CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### SNS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| `sns.amazonaws.com` | GenerateDataKey, Decrypt | Service permission |

##### DynamoDB CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### Lambda CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| None| None | |

##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None| None | |

#### managed-policy permissions
Only needed if managed-policies are used rather than permission grants. Make sure that the general permissions as described in **CMK Permissions** are defined to the CMK as described.
##### EBS encryption
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

#### SNS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| SNS CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant | |

##### DynamoDB CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| DynamoDB CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant | |

##### Lambda CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| Lambda CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant | |

##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| S3 CMK managed-policy | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo, RetireGrant, CreateGrant | |

### Permission-Type C Full-Set
Permissions required for Permission-Type C Full-Set.

Here are only described which permissions the CMK requires. You don't need to add each instance profile to the CMK you could also create managed-policies as described at [managed-policy permissions for permission-type B Full-Set](#managed-policy-permissions) and add it to eachinstance profile.

#### CMK Permissions
Permissions which needs to be applied to the CMK

##### EBS CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| publish_dispatcher.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| publish.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey, CreateGrant, ListGrants, RevokeGrant| |
| author.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| author_dispatcher.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| orchestrator.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| chaos_monkey.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| `arn:aws:iam::AWS_ACCOUNT_ID:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling` | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | None | |
| `arn:aws:iam::AWS_ACCOUNT_ID:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling` | CreateGrant, ListGrants, RevokeGrant | GrantIsForAWSResource |

##### SNS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| `arn:aws:iam::AWS_ACCOUNT_ID:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling` | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey |  |
| `arn:aws:iam::AWS_ACCOUNT_ID:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling` | CreateGrant, ListGrants, RevokeGrant | GrantIsForAWSResource |
| `cloudwatch.amazonaws.com` | GenerateDataKey, Decrypt | Service permission | |
| `sns.amazonaws.com` | GenerateDataKey, Decrypt | Service permission | |
| orchestrator.instance_profile | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo |  |
| stack_manager.lambda_service_role_arn | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo |  |

##### DynamoDB CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### Lambda CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| stack_manager.lambda_service_role_arn | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo |  |

##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| publish_dispatcher.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| publish.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| author.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| author_dispatcher.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| orchestrator.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |
| chaos_monkey.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |

### Permission-Type C Consolidated
Permissions required for Permission-Type C Consolidated

Here are only described which permissions the CMK requires. You don't need to add the instance profile to the CMK you could also create managed-policies as described at [managed-policy permissions for permission-type B Consolidated](#managed-policy-permissions-2) and add it to the instance profile.

#### CMK Permissions
Permissions which needs to be applied to the CMK
##### EBS CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| author_publish_dispatcher.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |

##### SNS CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### DynamoDB CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### Lambda CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| author_publish_dispatcher.instance_profile | Encrypt, Decrypt, ReEncrypt*, GenerateDataKey*, DescribeKey | |

### Permission-Type C AEM Stack Manager
Permissions required for Permission-Type C AEM Stack Manager

Here are only described which permissions the CMK requires. You don't need to add the instance profile to the CMK you could also create managed-policies as described at [managed-policy permissions for permission-type B AEM Stack Manager](#managed-policy-permissions-2) and add it to the instance profile.

#### CMK Permissions
Permissions which needs to be applied to the CMK
##### EBS CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| None | None | |

##### SNS CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| `sns.amazonaws.com` | GenerateDataKey, Decrypt | Service permission |
| Config parameter: `stack_manager.lambda_service_role_arn` | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo |  |
| Config parameter: `stack_manager.ssm_service_role_arn` | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo |  |

##### DynamoDB CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| Config parameter: `stack_manager.lambda_service_role_arn` | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo |  |

##### Lambda CMK
| Permission | Required Permissions | Notes |
|------|-------------|------|
| Config parameter: `stack_manager.lambda_service_role_arn` | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo |  |

##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| Config parameter: `stack_manager.lambda_service_role_arn` | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo |  |
| Config parameter: `stack_manager.ssm_service_role_arn` | Encrypt, Decrypt, DescribeKey, GenerateDataKey, ReEncryptFrom, ReEncryptTo |  |

### CloudFront permissions
Permissions required for CloudFront
#### CMK Permissions
Permissions which needs to be applied to the CMK
##### S3 CMK
| Role/Service | Required Permissions | Notes |
|------|-------------|------|
| delivery.logs.amazonaws.com | kms:GenerateDataKey | Service permission |

### AEM Stack manager Cloudwatch S3 Stream permissions
The AEM Stack manager Cloudwatch S3 Stream currently only supports encryption, if the configuration parameter `stack_name.cloudwatch_stream.s3_bucket` refers to the same bucket as the configuration parameter `s3.data_bucket_name`.

## CMK Shared across different AWS accounts
When you use a shared CMK across different AWS Accounts it's best to use manage policies for all AWS Resource encryption.
### EBS Volume Encryption
**Full-Set ONLY** To use a AEM OpenCloud Full-set permission type b & c with a CMK shared across different account and the CMK is not in the same AWS account as AEM OpenCloud you need to grant permissions for the AWS default AutoScalingGroup service-linked role ```arn:aws:iam::AWS_ACCOUNT_ID:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling```.

Here's small summary of what needs to be done in order to access the CMK across different AWS accounts for EBS Volume encryption:

- Allow use of the key for the different AWS Account in your CMK
```
{
   "Sid": "Allow use of the key in account 1234567890",
   "Effect": "Allow",
   "Principal": {
       "AWS": [
           "arn:aws:iam::1234567890:root"
       ]
   },
   "Action": [
       "kms:Encrypt",
       "kms:Decrypt",
       "kms:ReEncrypt*",
       "kms:GenerateDataKey*",
       "kms:DescribeKey"
   ],
   "Resource": "*"
}
```
- Allow attachment of persistent resources for the different AWS Account in your CMK
```
{
   "Sid": "Allow attachment of persistent resources in account 1234567890",
   "Effect": "Allow",
   "Principal": {
       "AWS": [
           "arn:aws:iam::1234567890:root"
       ]
   },
   "Action": [
       "kms:CreateGrant"
   ],
   "Resource": "*"
}
```
- Grant access for the `AWS AutoScalingGroup service-linked role` to the CMK in the different aws Account
```
aws kms create-grant \
  --region ap-southeast-2 \
  --key-id arn:aws:kms:ap-southeast-2:0987654321:key/0z9y8x-7w6v-5u-4t3s-1234567 \
  --grantee-principal arn:aws:iam::1234567890:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling \
  --operations "Encrypt" "Decrypt" "ReEncryptFrom" "ReEncryptTo" "GenerateDataKey" "GenerateDataKeyWithoutPlaintext" "DescribeKey" "CreateGrant"
```

- Define managed policies as described in [managed-policy permissions for permission-type B Full-Set](#managed-policy-permissions) This can also be used to create the managed policy for permission-type C Full-Set. If permission type B is in use don't forget to update the configuration parameter `aws.encryption.ebs_volume.managed_policy_arn` with the manage policy for EBS Volume encryption

More information about this can be found herin the AWS documentation [(link)](https://docs.aws.amazon.com/autoscaling/ec2/userguide/key-policy-requirements-EBS-encryption.html).


text:
package org.wso2.carbon.identity.oauth2.cache;

import org.wso2.carbon.identity.application.common.cache.BaseCache;
import org.wso2.carbon.utils.CarbonUtils;

/**
 * JWKS cache enables caching responses from JWK URIs
 */
public class JWKSCache extends BaseCache<JWKSCacheKey, JWKSCacheEntry> {

    private static final String JWKS_CACHE_NAME = "JWKSCache";

    private static volatile JWKSCache instance;

    private JWKSCache() {
        super(JWKS_CACHE_NAME);
    }

    /**
     * Returns JWKSCache instance
     *
     * @return instance of JWKSCache
     */
    public static JWKSCache getInstance() {
        CarbonUtils.checkSecurity();
        if (instance == null) {
            synchronized (JWKSCache.class) {
                if (instance == null) {
                    instance = new JWKSCache();
                }
            }
        }
        return instance;
    }
}


text:
class ActiveRecordWithoutCallbacks
  TRUE_BLOCK = proc{ true }

  def self.wo_callbacks(args)
    klass = args[:class]
    @debug = args[:debug]

    #Callback-types that we will clear or recompile.
    callbacks = [:create, :find, :initialize, :destroy, :commit, :rollback, :save, :touch, :update, :validate, :validation]
    callback_types = [:before, :after]
    previous_values = []

    #List of various possible callbacks.
    takes = [:_create_callbacks, :_find_callbacks, :_initialize_callbacks, :_destroy_callbacks, :_commit_callbacks, :_rollback_callbacks, :_save_callbacks, :_touch_callbacks, :_update_callbacks, :_validate_callbacks, :_validation_callbacks]

    #Run inside exclusive, so we are sure no other thread suffers from the horrible hack, that we are about to do.
    Thread.exclusive do
      callbacks.each do |callback|
        puts "Disabling callbacks for '#{callback}'." if @debug

        #Method-name for callbacks to reset.
        callbacks_method_name = "_#{callback}_callbacks"

        #Store previous value for restoring later.
        previous_values << {
          :callbacks_method_name => callbacks_method_name,
          :value => klass.__send__(callbacks_method_name).clone
        }

        #Clear all callbacks.
        puts "Clearing callbacks in '#{callbacks_method_name}'." if @debug
        klass.__send__(callbacks_method_name).clear

        #Test that callbacks really was cleared.
        puts "Checking if everything is okay for '#{callback}'." if @debug
        raise "Expected '#{callbacks_method_name}' to be empty but it wasnt: #{klass.__send__(callbacks_method_name)}" unless klass.__send__(callbacks_method_name).empty?

        #Trick ActiveRecord to recompile callbacks.
        callback_types.each do |callback_type|
          method_name = "#{callback_type}_#{callback}"

          if klass.respond_to?(method_name)
            klass.__send__(method_name, &TRUE_BLOCK)
          end
        end
      end

      begin
        #Run the given block, now that all callbacks are disabled.
        puts "Yielding block." if @debug

        klass.observers.disable :all do
          return yield
        end
      ensure
        puts "Restoring callbacks." if @debug

        #Restore previous callbacks.
        previous_values.each do |previous_value|
          method_name = "#{previous_value[:callbacks_method_name]}="
          klass.__send__(method_name, previous_value[:value])
        end

        #Trick ActiveRecord to recompile old callbacks.
        callbacks.each do |callback|
          callback_types.each do |callback_type|
            method_name = "#{callback_type}_#{callback}"

            if klass.respond_to?(method_name)
              klass.__send__(method_name, &TRUE_BLOCK)
            end
          end
        end
      end
    end
  end
end


text:
"use strict";

// https://github.com/conventional-changelog/conventional-changelog/blob/b516084ef6a725197f148236c0ddbfae7ffe3e6f/packages/conventional-changelog-angular/conventional-recommended-bump.js
const parserOpts = require("./parser-opts");
const writerOpts = require("./writer-opts");
const whatBump = require("./what-bump");

module.exports = {
  parserOpts,
  writerOpts,
  whatBump,
};


text:
void Save2OCDB(Char_t * det, Int_t runNumber=0)
{
  // Save QA data generated by DataMaker into OCDB
  const char * kYear = "09" ;
  // where ?
  //AliQA::SetQARefStorage(Form("%s%s/", AliQA::GetQARefDefaultStorage(), kYear)) ;
  AliQAv1::SetQARefStorage(Form("local://$ALICE_ROOT/QAref/", det)) ;
  AliQAv1::SetQARefDataDirName(AliRecoParam::kLowMult) ; //Event Specie
  AliQAManager *qam = AliQAManager::QAManager("rec") ;
  qam->Save2OCDB(runNumber, AliRecoParam::kLowMult, kYear, det) ;
}


text:
package io.quarkus.undertow.test;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AnnotatedListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        sce.getServletContext().setAttribute("annotated listener", true);
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memmove_63a.c
Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE193.label.xml
Template File: sources-sink-63a.tmpl.c
*/
/*
 * @description
 * CWE: 121 Stack Based Buffer Overflow
 * BadSource:  Point data to a buffer that does not have space for a NULL terminator
 * GoodSource: Point data to a buffer that includes space for a NULL terminator
 * Sinks: memmove
 *    BadSink : Copy string to data using memmove()
 * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING "AAAAAAAAAA"

#ifndef OMITBAD

/* bad function declaration */
void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memmove_63b_badSink(char * * dataPtr);

void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memmove_63_bad()
{
    char * data;
    char * dataBadBuffer = (char *)ALLOCA((10)*sizeof(char));
    char * dataGoodBuffer = (char *)ALLOCA((10+1)*sizeof(char));
    /* FLAW: Set a pointer to a buffer that does not leave room for a NULL terminator when performing
     * string copies in the sinks  */
    data = dataBadBuffer;
    data[0] = '\0'; /* null terminate */
    CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memmove_63b_badSink(&data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memmove_63b_goodG2BSink(char * * data);

static void goodG2B()
{
    char * data;
    char * dataBadBuffer = (char *)ALLOCA((10)*sizeof(char));
    char * dataGoodBuffer = (char *)ALLOCA((10+1)*sizeof(char));
    /* FIX: Set a pointer to a buffer that leaves room for a NULL terminator when performing
     * string copies in the sinks  */
    data = dataGoodBuffer;
    data[0] = '\0'; /* null terminate */
    CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memmove_63b_goodG2BSink(&data);
}

void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memmove_63_good()
{
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memmove_63_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memmove_63_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mockmock</groupId>
    <artifactId>MockMock</artifactId>
    <version>1.3</version>
    <packaging>jar</packaging>

    <name>MockMock</name>
    <description>Mock SMTP Server</description>
    <inceptionYear>2012</inceptionYear>
    <url>https://github.com/tweakers-dev/MockMock</url>

    <prerequisites>
        <maven>3.0</maven>
    </prerequisites>

    <properties>
        <project.build.sourceEncoding>ISO-8859-15</project.build.sourceEncoding>
        <project.resources.sourceEncoding>ISO-8859-15</project.resources.sourceEncoding>
        <spring.version>4.1.2.RELEASE</spring.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.1</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.mockmock.AppStarter</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.dstovall</groupId>
                <artifactId>onejar-maven-plugin</artifactId>
                <version>1.4.4</version>
                <executions>
                    <execution>
                        <configuration>
                            <onejarVersion>0.97</onejarVersion>
                            <attachToBuild>true</attachToBuild>
                            <classifier>onejar</classifier>
                        </configuration>
                        <phase>package</phase>
                        <goals>
                            <goal>one-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.4.3</version>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/static</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/resources</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <pluginRepositories>
        <pluginRepository>
            <id>onejar-maven-plugin.googlecode.com</id>
            <url>http://onejar-maven-plugin.googlecode.com/svn/mavenrepo</url>
        </pluginRepository>
    </pluginRepositories>

    <repositories>
        <repository>
            <id>repository.springframework.maven.release</id>
            <name>Spring Framework Maven Release Repository</name>
            <url>http://maven.springframework.org/release</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.2</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.2</version>
        </dependency>

        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>8.1.8.v20121106</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-webapp</artifactId>
            <version>8.1.8.v20121106</version>
        </dependency>

        <dependency>
            <groupId>org.subethamail</groupId>
            <artifactId>subethasmtp</artifactId>
            <version>3.1.7</version>
        </dependency>

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.1</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>13.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Test libraries ahead -->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.10.8</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
Whatsapp Spammer is a quick and dirty Java application to send multiple messages through the Whatsapp Web client.

## How to use
To use Whatsapp Spammer you need to run [Whatsapp Web](https://web.whatsapp.com) on your computer, then open Whatsapp Spammer, choose the source of the messages (single message or list of messages), fill in the fields and click run.
You will be prompted with further instructions: **do not close the popup until you have followed the instructions**.
You will need to open Whatsapp Web and maximize it (so it occupies the whole screen), then you have to open the contact or group you want to send the messages to and click on the message box; finally you can click on "Ok" on the popup and the program will send the messages.
**Do not click anything, move any window or open any program while the program is still sending messages.** You will be notified as the program will have sent all the messages.

## WSL (Whatsapp Spammer List)
One of the options offered by this application is to send a list of messages contained in a text file. The text file can have any extension, but it's advised to use one of these extensions: ```.txt .lst .wsl```

### Format
The file must contain one message per line: if you want a message to be composed of multiple lines insert ```#NL``` where you want to break the line (e.g. ```First line#NL#Second line```).

### Wait directives
Lines starting with ```#wait``` are interpreted by the application as commands instead of text messages. These lines are called _wait directives_ as they tell the application how much time to wait after sending a message before sending the next one.
Here is a simple example of a .WBL file with wait directives:
```
First message
Second message
#wait 1000
Third message
Fourth message
#wait 2000
Fifth message
```

When these messages will be sent this will happen:
-   no initial wait directive: the program will use the default wait time (100ms);
-   send the first message
-   wait 100ms
-   send the second message
-   wait 100ms
-   wait directive: change wait time to 1000ms
-   send the third message
-   wait 1000ms
-   send the fourth message
-   wait 1000ms
-   wait directive: change wait time to 2000ms
-   send the fifth message
-   wait 2000ms

Note how each directive will change the wait time **for all the following messages**, not just for the next one.

## Disclaimer
This application could cause unwanted behaviours (including, but not limited to freezes, performance issues, forced restarts and crashes) on the device running the application and Whatsapp Web, on the device mobile running Whatsapp and the device(s) receiving the messages.
The author of this software is not to be held responsible for any damage or problems caused by the use of this software.

## License
This application is licensed under the [MIT License](https://github.com/GioBonvi/WhatsappSpammer/blob/master/LICENSE).


text:
<?php

namespace N98\Util\Console\Helper;

use Exception;
use InvalidArgumentException;
use N98\Util\Validator\FakeMetadataFactory;
use RuntimeException;
use Symfony\Component\Console\Helper\DialogHelper;
use Symfony\Component\Console\Helper\Helper as AbstractHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validator;

/**
 * Helper to init some parameters
 */
class ParameterHelper extends AbstractHelper
{
    /**
     * @var Validator
     */
    private $validator;

    /**
     * Returns the canonical name of this helper.
     *
     * @return string The canonical name
     *
     * @api
     */
    public function getName()
    {
        return 'parameter';
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @param string $argumentName
     * @param bool $withDefaultStore [optional]
     *
     * @return mixed
     *
     * @throws InvalidArgumentException
     */
    public function askStore(
        InputInterface $input,
        OutputInterface $output,
        $argumentName = 'store',
        $withDefaultStore = false
    ) {
        /* @var $storeManager \Mage_Core_Model_App */
        $storeManager = \Mage::app();

        try {
            if ($input->getArgument($argumentName) === null) {
                throw new RuntimeException('No store given');
            }
            /** @var $store \Mage_Core_Model_Store */
            $store = $storeManager->getStore($input->getArgument($argumentName));
        } catch (Exception $e) {
            $stores = array();
            $i = 0;

            foreach ($storeManager->getStores($withDefaultStore) as $store) {
                $stores[$i] = $store->getId();
                $question[] = sprintf(
                    '<comment>[%d]</comment> %s - %s' . PHP_EOL,
                    ++$i,
                    $store->getCode(),
                    $store->getName()
                );
            }

            if (count($stores) > 1) {
                $question[] = '<question>Please select a store: </question>';
                $storeId = $this->askAndValidate(
                    $output,
                    $question,
                    function ($typeInput) use ($stores) {
                        if (!isset($stores[$typeInput - 1])) {
                            throw new InvalidArgumentException('Invalid store');
                        }

                        return $stores[$typeInput - 1];
                    }
                );
            } else {
                // only one store view available -> take it
                $storeId = $stores[0];
            }

            $store = $storeManager->getStore($storeId);
        }

        return $store;
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @param string $argumentName
     *
     * @return mixed
     * @throws InvalidArgumentException
     * @throws RuntimeException
     */
    public function askWebsite(InputInterface $input, OutputInterface $output, $argumentName = 'website')
    {
        /* @var $storeManager \Mage_Core_Model_App */
        $storeManager = \Mage::app();

        try {
            if ($input->getArgument($argumentName) === null) {
                throw new RuntimeException('No website given');
            }
            /** @var $website \Mage_Core_Model_Website */
            $website = $storeManager->getWebsite($input->getArgument($argumentName));
        } catch (Exception $e) {
            $i = 0;
            $websites = array();
            foreach ($storeManager->getWebsites() as $website) {
                $websites[$i] = $website->getId();
                $question[] = sprintf(
                    '<comment>[%d]</comment> ' . $website->getCode() . ' - ' . $website->getName() . PHP_EOL,
                    ++$i
                );
            }
            if (count($websites) == 1) {
                return $storeManager->getWebsite($websites[0]);
            }
            $question[] = '<question>Please select a website: </question>';

            $websiteId = $this->askAndValidate(
                $output,
                $question,
                function ($typeInput) use ($websites) {
                    if (!isset($websites[$typeInput - 1])) {
                        throw new InvalidArgumentException('Invalid store');
                    }

                    return $websites[$typeInput - 1];
                }
            );

            $website = $storeManager->getWebsite($websiteId);
        }

        return $website;
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @param string $argumentName
     *
     * @return string
     */
    public function askEmail(InputInterface $input, OutputInterface $output, $argumentName = 'email')
    {
        $constraints = new Constraints\Collection(
            array(
                'email' => array(
                    new Constraints\NotBlank(),
                    new Constraints\Email()
                )
            )
        );

        return $this->validateArgument($output, $argumentName, $input->getArgument($argumentName), $constraints);
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @param string $argumentName
     *
     * @param bool $needDigits [optional]
     * @return string
     */
    public function askPassword(
        InputInterface $input,
        OutputInterface $output,
        $argumentName = 'password',
        $needDigits = true
    ) {
        $validators = array();

        if ($needDigits) {
            $regex = array(
                'pattern' => '/^(?=.*\d)(?=.*[a-zA-Z])/',
                'message' => 'Password must contain letters and at least one digit'
            );
            $validators[] = new Constraints\Regex($regex);
        }

        $validators[] = new Constraints\Length(array('min' => 6));

        $constraints = new Constraints\Collection(
            array(
                'password' => $validators
            )
        );

        return $this->validateArgument($output, $argumentName, $input->getArgument($argumentName), $constraints);
    }

    /**
     * @param OutputInterface $output
     * @param                 $question
     * @param callable $callback
     *
     * @return string
     */
    private function askAndValidate(OutputInterface $output, $question, $callback)
    {
        /** @var DialogHelper $dialog */
        $dialog = $this->getHelperSet()->get('dialog');

        return $dialog->askAndValidate($output, $question, $callback);
    }

    /**
     * @param OutputInterface $output
     * @param string $name
     * @param string $value
     * @param Constraints\Collection $constraints The constraint(s) to validate against.
     *
     * @return string
     */
    private function validateArgument(OutputInterface $output, $name, $value, $constraints)
    {
        if (strlen($value)) {
            $errors = $this->validateValue($name, $value, $constraints);
            if ($errors->count() > 0) {
                $output->writeln('<error>' . $errors[0]->getMessage() . '</error>');
            } else {
                return $value;
            }
        }

        $question = '<question>' . ucfirst($name) . ': </question>';

        $value = $this->askAndValidate(
            $output,
            $question,
            function ($inputValue) use ($constraints, $name) {
                $errors = $this->validateValue($name, $inputValue, $constraints);
                if ($errors->count() > 0) {
                    throw new InvalidArgumentException($errors[0]->getMessage());
                }

                return $inputValue;
            }
        );

        return $value;
    }

    /**
     * @param string $name
     * @param string $value
     * @param Constraints\Collection $constraints The constraint(s) to validate against.
     *
     * @return \Symfony\Component\Validator\ConstraintViolationInterface[]|ConstraintViolationListInterface
     */
    private function validateValue($name, $value, $constraints)
    {
        $validator = $this->getValidator();
        /** @var ConstraintViolationListInterface|ConstraintViolationInterface[] $errors */
        $errors = $validator->validateValue(array($name => $value), $constraints);

        return $errors;
    }

    /**
     * @return Validator
     */
    private function getValidator()
    {
        return $this->validator ?: $this->validator = $this->createValidator();
    }

    /**
     * @return Validator
     */
    private function createValidator()
    {
        $factory = new ConstraintValidatorFactory();
        $validator = new Validator(new FakeMetadataFactory(), $factory, new Translator('en'));

        return $validator;
    }
}


text:
using System;
using System.Reactive;
using Nethereum.RPC.Eth.DTOs;
using Nethereum.RPC.Reactive.Polling.Streams;

namespace Nethereum.RPC.Reactive.Polling
{
    public static partial class Polling
    {
        public static IObservable<Transaction> GetPendingTransactions(this IEthApiService eth,
            IObservable<Unit> poller = null) => new PendingTransactionStreamProvider(
                poller ?? DefaultPoller,
                eth.Filters,
                eth.Transactions)
            .GetPendingTransactions();
    }
}


text:
<?php

namespace Cocorico\UserBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

class UserRequestListener
{
    protected $securityTokenStorage;
    protected $timezone;

    public function __construct(TokenStorage $securityTokenStorage, $timezone)
    {
        $this->securityTokenStorage = $securityTokenStorage;
        $this->timezone = $timezone;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) {
            return;
        }

        $request = $event->getRequest();
        $session = $request->getSession();
        $cookies = $request->cookies;

        $session->set('timezone', $this->timezone);
        $user = $this->securityTokenStorage->getToken() ? $this->securityTokenStorage->getToken()->getUser() : null;
        if ($user) {
            if ($user && method_exists($user, "getTimeZone")) {
                $session->set('timezone', $user->getTimeZone());
            }
        }

        if ($cookies->has('userType') && $cookies->get('userType') == "offerer") {
            $session->set('profile', 'offerer');
        } elseif ($cookies->has('userType') && $cookies->get('userType') == "asker") {
            $session->set('profile', 'asker');
        }
    }
}


text:
package com.quakearts.webapp.orm.stringconcat;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Transient;

import com.quakearts.webapp.orm.exception.DataStoreException;

/**Internal method for concatenating strings
 * @author kwakutwumasi-afriyie
 *
 */
class OrmStringConcat {
	private Map<String, ConcatenatorEntry> fieldMap;
	private Class<?> beanClass;

	OrmStringConcat(Class<?> beanClass) {
		fieldMap = new HashMap<>();

		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);

			for(PropertyDescriptor descriptor:beanInfo.getPropertyDescriptors()){
				if(descriptor.getPropertyType() == String.class
						&& descriptor.getWriteMethod()!=null
						&& descriptor.getReadMethod()!=null){

					Field field = getField(beanClass, descriptor);

					if(isTransient(field, descriptor))
						continue;

					fieldMap.put(descriptor.getName(),
							new ConcatenatorEntry(beanClass.getName(),
									descriptor.getName(),
									getMaxLength(descriptor, field, beanClass),
									getMethodHandle(descriptor.getWriteMethod()),
									getMethodHandle(descriptor.getReadMethod())));
				}
			}
		} catch (IntrospectionException | IllegalAccessException e) {
			throw new DataStoreException("Unable to introspect bean "+beanClass.getName(),e);
		}

		this.beanClass = beanClass;
	}

	private boolean isTransient(Field field, PropertyDescriptor descriptor) {
		if(field != null){
			return field.getAnnotation(Transient.class) != null;
		} else {
			return descriptor.getReadMethod().getAnnotation(Transient.class) != null
					|| descriptor.getWriteMethod().getAnnotation(Transient.class) != null;
		}
	}

	protected Field getField(Class<?> beanClass, PropertyDescriptor descriptor) {
		Field field = null;
		try {
			field = beanClass.getDeclaredField(descriptor.getName());
		} catch (NoSuchFieldException | SecurityException e) {
			try {
				field = getField(descriptor.getName(), beanClass.getSuperclass());
			} catch (NoSuchFieldException e1) {
				//Do nothing
			}
		}
		return field;
	}

	String concatenate(String value, int maxLength){
		return value.length()>maxLength? value.substring(0,maxLength):value;
	}

	int getMaxLength(PropertyDescriptor descriptor, Field field, Class<?> beanClass){
		Column column = null;
		if(field!=null)
			column = field.getAnnotation(Column.class);

		if(column != null){
			return column.length();
		} else {
			column = descriptor.getWriteMethod().getAnnotation(Column.class);
			if(column==null){
				column = descriptor.getReadMethod().getAnnotation(Column.class);
			}

			if(column!=null)
				return column.length();
			else
				return getMaxLengthSize(descriptor, field);
		}
	}

	int getMaxLengthSize(PropertyDescriptor descriptor, Field field) {
		try{
			@SuppressWarnings("unchecked")
			Class<? extends Annotation> sizeAnnotation = (Class<? extends Annotation>)
					Class.forName("javax.validation.constraints.Size");
			Object sizeObject = null;
			if(field!=null)
				sizeObject = field.getAnnotation(sizeAnnotation);

			if(sizeObject != null){
				return getSizeMax(sizeObject, sizeAnnotation);
			} else {
				sizeObject = descriptor.getWriteMethod().getAnnotation(sizeAnnotation);
				if(sizeObject==null){
					sizeObject = descriptor.getReadMethod().getAnnotation(sizeAnnotation);
				}

				if(sizeObject!=null)
					return getSizeMax(sizeObject, sizeAnnotation);
			}
		} catch (ClassNotFoundException e) {
			// Do nothing
		}

		return 255;
	}

	int getSizeMax(Object sizeObject, Class<?> sizeAnnotation){
		try {
			Method maxMethod = sizeAnnotation.getMethod("max");
			return (int) maxMethod.invoke(sizeObject);
		} catch (NoSuchMethodException | SecurityException |
				IllegalAccessException | IllegalArgumentException |
				InvocationTargetException e) {
			return 255;
		}
	}

	Field getField(String fieldName, Class<?> superClass) throws NoSuchFieldException {
		if(superClass == Object.class)
			throw new NoSuchFieldException("Field '"+fieldName+"' could not be found.");

		try {
			return superClass.getDeclaredField(fieldName);
		} catch (NoSuchFieldException e) {
			return getField(fieldName, superClass.getSuperclass());
		}
	}

	MethodHandle getMethodHandle(Method method) throws IllegalAccessException{
		MethodHandle handle = MethodHandles.lookup().unreflect(method);
		return new ConstantCallSite(handle).dynamicInvoker();
	}

	void trimStrings(Object object) {
		if(object.getClass().isAssignableFrom(beanClass)){
			if(fieldMap.size()<=0)
				return;

			for(ConcatenatorEntry entry: fieldMap.values()){
				Object valueObject = getValue(object, entry);
				trim(object, entry, valueObject);
			}
		} else {
			throw new IllegalArgumentException("Object is not a subtype of "+beanClass.getName());
		}
	}

	protected Object getValue(Object object, ConcatenatorEntry entry) {
		Object valueObject;
		try {
			valueObject = entry.getMethodHandle.invoke(object);
		} catch (Throwable e) {
			throw new DataStoreException("Unable to get string to concat", e);
		}
		return valueObject;
	}

	protected void trim(Object object, ConcatenatorEntry entry, Object valueObject) {
		if (valueObject == null)
			return;

		String value = valueObject.toString();

		String trimedValue = concatenate(value, entry.fieldLength);
		if (!value.equals(trimedValue)) {
			OrmStringConcatUtil.notify(beanClass, object, value, trimedValue);

			try {
				entry.writeMethodHandle.invoke(object, trimedValue);
			} catch (Throwable e) {
				throw new DataStoreException("Unable to concat string", e);
			}
		}
	}
}

class ConcatenatorEntry {
	int fieldLength;
	MethodHandle writeMethodHandle;
	MethodHandle getMethodHandle;
	String fieldName;
	String className;

	public ConcatenatorEntry(String className, String fieldName, int fieldLength, MethodHandle writeMethodHandle, MethodHandle getMethodHandle) {
		this.fieldLength = fieldLength;
		this.writeMethodHandle = writeMethodHandle;
		this.getMethodHandle = getMethodHandle;
		this.fieldName = fieldName;
		this.className = className;
	}
}


text:
namespace gl40core
{
// import booleans to namespace

using gl::GL_FALSE;
using gl::GL_TRUE;

}  // namespace gl40core


text:
"""
Pythonic LiDAR drivers
"""

from . import drivers
from . import core
from . import io
from . import settings

__all__ = ['core', 'io', 'settings', 'drivers']

# Build information
__version__ = settings.version
__release__ = settings.release
__author__ = settings.author
__package__ = settings.package
__source__ = settings.source
__license__ = settings.license


text:
package org.apache.directory.api.ldap.extras.extended.ads_impl.cancel;

import org.apache.directory.api.asn1.DecoderException;
import org.apache.directory.api.asn1.ber.grammar.AbstractGrammar;
import org.apache.directory.api.asn1.ber.grammar.Grammar;
import org.apache.directory.api.asn1.ber.grammar.GrammarAction;
import org.apache.directory.api.asn1.ber.grammar.GrammarTransition;
import org.apache.directory.api.asn1.ber.tlv.BerValue;
import org.apache.directory.api.asn1.ber.tlv.IntegerDecoder;
import org.apache.directory.api.asn1.ber.tlv.IntegerDecoderException;
import org.apache.directory.api.asn1.ber.tlv.UniversalTag;
import org.apache.directory.api.i18n.I18n;
import org.apache.directory.api.ldap.codec.api.LdapApiServiceFactory;
import org.apache.directory.api.ldap.extras.extended.cancel.CancelRequestImpl;
import org.apache.directory.api.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class implements the Cancel operation. All the actions are declared
 * in this class. As it is a singleton, these declaration are only done once.
 * The grammar is :
 *
 *

 *  cancelRequestValue ::= SEQUENCE {
 *      cancelId     MessageID
 *                   -- MessageID is as defined in [RFC2251]
 * }
 *

 *
 * @author Apache Directory Project
 */
public final class CancelGrammar extends AbstractGrammar<CancelContainer>
{
    /** The logger */
    static final Logger LOG = LoggerFactory.getLogger( CancelGrammar.class );

    /** Speedup for logs */
    static final boolean IS_DEBUG = LOG.isDebugEnabled();

    /** The instance of grammar. CancelGrammar is a singleton */
    private static Grammar<CancelContainer> instance = new CancelGrammar();

    /**
     * Creates a new GracefulDisconnectGrammar object.
     */
    @SuppressWarnings("unchecked")
    private CancelGrammar()
    {
        setName( CancelGrammar.class.getName() );

        // Create the transitions table
        super.transitions = new GrammarTransition[CancelStatesEnum.LAST_CANCEL_STATE.ordinal()][256];

        /**
         * Transition from init state to cancel sequence
         * cancelRequestValue ::= SEQUENCE {
         *     ...
         *
         * Creates the Cancel object
         */
        super.transitions[CancelStatesEnum.START_STATE.ordinal()][UniversalTag.SEQUENCE.getValue()] =
            new GrammarTransition<CancelContainer>( CancelStatesEnum.START_STATE,
                CancelStatesEnum.CANCEL_SEQUENCE_STATE,
                UniversalTag.SEQUENCE.getValue(),
                new GrammarAction<CancelContainer>( "Init Cancel" )
                {
                    public void action( CancelContainer cancelContainer )
                    {
                        CancelRequestDecorator cancel = new CancelRequestDecorator(
                            LdapApiServiceFactory.getSingleton(),
                            new CancelRequestImpl() );

                        cancelContainer.setCancel( cancel );
                    }
                } );

        /**
         * Transition from cancel SEQ to cancelId
         *
         * cancelRequestValue ::= SEQUENCE {
         *     cancelId   MessageID
         * }
         *
         * Set the cancelId value into the Cancel object.
         */
        super.transitions[CancelStatesEnum.CANCEL_SEQUENCE_STATE.ordinal()][UniversalTag.INTEGER.getValue()] =
            new GrammarTransition<CancelContainer>( CancelStatesEnum.CANCEL_SEQUENCE_STATE,
                CancelStatesEnum.CANCEL_ID_STATE,
                UniversalTag.INTEGER.getValue(),
                new GrammarAction<CancelContainer>( "Stores CancelId" )
                {
                    public void action( CancelContainer cancelContainer ) throws DecoderException
                    {
                        BerValue value = cancelContainer.getCurrentTLV().getValue();

                        try
                        {
                            int cancelId = IntegerDecoder.parse( value, 0, Integer.MAX_VALUE );

                            if ( IS_DEBUG )
                            {
                                LOG.debug( "CancelId = " + cancelId );
                            }

                            cancelContainer.getCancel().setCancelId( cancelId );
                            cancelContainer.setGrammarEndAllowed( true );
                        }
                        catch ( IntegerDecoderException e )
                        {
                            String msg = I18n.err( I18n.ERR_04031, Strings.dumpBytes( value.getData() ) );
                            LOG.error( msg );
                            throw new DecoderException( msg );
                        }
                    }
                } );
    }

    /**
     * This class is a singleton.
     *
     * @return An instance on this grammar
     */
    public static Grammar<CancelContainer> getInstance()
    {
        return instance;
    }
}


text:
import timezz from '../dist/timezz';

test('init and get error', () => {
  expect(() => timezz()).toThrow();
});

test('init only with selector and get error', () => {
  expect(() => timezz('.nothing')).toThrow();
});

test('init and destroy', () => {
  const timer = timezz([], { date: new Date() });

  expect(timer.elements).toEqual([]);

  timer.destroy();

  expect(timer.isDestroyed).toBe(true);
});


text:
//returns value of integral in string form or error
//assumes tuples[].x and tuples[].y are defined as an ordered pair
function integrate(tuples){
	var sum = 0;
	var boundB = tuples[tuples.length - 1].x
	var boundA = tuples[0].x
	for(var i=0;i<(tuples.length-1);i++){
		sum += ((tuples[i+1].x - tuples[i].x)*(tuples[i+1].y + tuples[i].y));
	}
	return (.5 * sum);
}

//for testing, returns tuples array with x and y corresponding to y=x^2, bounds hard coded
function xQuad(){
	var tempArr = [];
	for(var i=0;i<=10;i++){
		var tuple = {};
		tuple.x = i;
		tuple.y = Math.pow(i,2);
		tempArr.push(tuple);
	}
	return tempArr;
}
//for testing, returns tuples array with x and y corresponding to y=x, bounds hard coded
function xLin(){
	var tempArr = [];
	for(var i=0;i<=10;i++){
		var tuple = {};
		tuple.x = i;
		tuple.y = i;
		tempArr.push(tuple);
	}
	return tempArr;
}


text:
<TITLE>Configure the Network</TITLE>
<META NAME="description" CONTENT="Configure the Network">
<META NAME="keywords" CONTENT="debian-tutorial">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<META NAME="Generator" CONTENT="LaTeX2HTML v2K.1beta">
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">

<LINK REL="STYLESHEET" HREF="debian-tutorial.css">

<LINK REL="next" HREF="node30.html">
<LINK REL="previous" HREF="node28.html">
<LINK REL="up" HREF="node18.html">
<LINK REL="next" HREF="node30.html">

 Next: Install the Base System
 Up: Step-by-Step Installation
 Previous: Configure Device Driver Modules
 &nbsp   Contents
 &nbsp   Index

Configure the Network

You'll have to configure the network even if you don't have a network, but you'll
only have to answer the first two questions - ``Choose the Host name,'' and
``Is your system connected to a network?''

If you are connected to a network, you'll need the information you collected
from 2.2.1.  However, if your primary connection to the network
will be PPP, you should choose NOT to configure the network.

<TT>dbootstrap</TT> will ask you a number of questions about your network; fill
in the answers from 2.2.1. The system will also summarize your
network information and ask you for confirmation.  Next, you need to specify
the network device that your primary network connection uses.  Usually, this
will be <TT>eth0</TT> (the first Ethernet device).   On a laptop, it's more
likely that your primary network device is <TT>pcmcia</TT>.

Here are some technical details you may find handy: The program assumes the
network IP address is the bitwise <TT>AND</TT> of your system's IP address and
your netmask. It will guess the broadcast address is the bitwise <TT>OR</TT>
of your system's IP address with the bitwise negation of the netmask. It will
guess that your gateway system is also your DNS server.  If you can't find any
of these answers, use the system's guesses. You can change them once the system
has been installed, if necessary, by editing <TT>/etc/init.d/network</TT>. (On
a Debian system, daemons are started by scripts in the directory <TT>/etc/init.d/</TT>.)

 Next: Install the Base System
 Up: Step-by-Step Installation
 Previous: Configure Device Driver Modules
 &nbsp   Contents
 &nbsp   Index

<ADDRESS>
John Goerzen / Ossama Othman
</ADDRESS>


text:
package org.sosy_lab.cpachecker.cfa.ast.c;

import java.util.Objects;

import org.sosy_lab.cpachecker.cfa.ast.AExpression;
import org.sosy_lab.cpachecker.cfa.ast.FileLocation;
import org.sosy_lab.cpachecker.cfa.types.c.CType;

public final class CComplexCastExpression extends AExpression implements CLeftHandSide {

  private final CExpression operand;
  private final CType     type;
  /**
   * When isReal is false this is a cast to get the imaginary Part of the complex number
   */
  private final boolean isReal;

  public CComplexCastExpression(final FileLocation pFileLocation,
                            final CType pExpressionType,
                            final CExpression pOperand,
                            final CType pType,
                            final boolean pIsRealCast) {
    super(pFileLocation, pExpressionType);

    isReal = pIsRealCast;
    operand = pOperand;
    type = pType;
  }

  @Override
  public CType getExpressionType() {
    return (CType)super.getExpressionType();
  }

  public CExpression getOperand() {
    return operand;
  }

  public CType getType() {
    return type;
  }

  public boolean isImaginaryCast() {
    return !isReal;
  }

  public boolean isRealCast() {
    return isReal;
  }

  @Override
  public <R, X extends Exception> R accept(CExpressionVisitor<R, X> v) throws X {
    return v.visit(this);
  }

  @Override
  public <R, X extends Exception> R accept(CRightHandSideVisitor<R, X> v) throws X {
    return v.visit(this);
  }

  @Override
  public <R, X extends Exception> R accept(CLeftHandSideVisitor<R, X> v) throws X {
    return v.visit(this);
  }

  @Override
  public String toASTString() {
    if (isReal) {
      return "__real__ " + operand.toASTString();
    } else {
      return "__imag__ " + operand.toASTString();
    }
  }

  /* (non-Javadoc)
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 7;
    result = prime * result + Objects.hashCode(operand);
    result = prime * result + Objects.hashCode(type);
    result = prime * result + Objects.hashCode(isReal);
    result = prime * result + super.hashCode();
    return result;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }

    if (!(obj instanceof CComplexCastExpression)
        || !super.equals(obj)) {
      return false;
    }

    CComplexCastExpression other = (CComplexCastExpression) obj;

    return Objects.equals(other.operand, operand) && Objects.equals(other.type, type)
            && Objects.equals(other.isReal, isReal);
  }

}