text:
'''
Python renderer that includes a Pythonic Object based interface

:maintainer: Evan Borgstrom <evan@borgstrom.ca>

Let's take a look at how you use pyobjects in a state file. Here's a quick
example that ensures the ``/tmp`` directory is in the correct state.

.. code-block:: python
   :linenos:

    #!pyobjects

    File.managed("/tmp", user='root', group='root', mode='1777')

Nice and Pythonic!

By using the "shebang" syntax to switch to the pyobjects renderer we can now
write our state data using an object based interface that should feel at home
to python developers. You can import any module and do anything that you'd
like (with caution, importing sqlalchemy, django or other large frameworks has
not been tested yet). Using the pyobjects renderer is exactly the same as
using the built-in Python renderer with the exception that pyobjects provides
you with an object based interface for generating state data.

Creating state data
^^^^^^^^^^^^^^^^^^^
Pyobjects takes care of creating an object for each of the available states on
the minion. Each state is represented by an object that is the CamelCase
version of its name (i.e. ``File``, ``Service``, ``User``, etc), and these
objects expose all of their available state functions (i.e. ``File.managed``,
``Service.running``, etc).

The name of the state is split based upon underscores (``_``), then each part
is capitalized and finally the parts are joined back together.

Some examples:

* ``postgres_user`` becomes ``PostgresUser``
* ``ssh_known_hosts`` becomes ``SshKnownHosts``

Context Managers and requisites
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
How about something a little more complex. Here we're going to get into the
core of how to use pyobjects to write states.

.. code-block:: python
   :linenos:

    #!pyobjects

    with Pkg.installed("nginx"):
        Service.running("nginx", enable=True)

        with Service("nginx", "watch_in"):
            File.managed("/etc/nginx/conf.d/mysite.conf",
                         owner='root', group='root', mode='0444',
                         source='salt://nginx/mysite.conf')

The objects that are returned from each of the magic method calls are setup to
be used a Python context managers (``with``) and when you use them as such all
declarations made within the scope will **automatically** use the enclosing
state as a requisite!

The above could have also been written use direct requisite statements as.

.. code-block:: python
   :linenos:

    #!pyobjects

    Pkg.installed("nginx")
    Service.running("nginx", enable=True, require=Pkg("nginx"))
    File.managed("/etc/nginx/conf.d/mysite.conf",
                 owner='root', group='root', mode='0444',
                 source='salt://nginx/mysite.conf',
                 watch_in=Service("nginx"))

You can use the direct requisite statement for referencing states that are
generated outside of the current file.

.. code-block:: python
   :linenos:

    #!pyobjects

    # some-other-package is defined in some other state file
    Pkg.installed("nginx", require=Pkg("some-other-package"))

The last thing that direct requisites provide is the ability to select which
of the SaltStack requisites you want to use (require, require_in, watch,
watch_in, use & use_in) when using the requisite as a context manager.

.. code-block:: python
   :linenos:

    #!pyobjects

    with Service("my-service", "watch_in"):
        ...

The above example would cause all declarations inside the scope of the context
manager to automatically have their ``watch_in`` set to
``Service("my-service")``.

Including and Extending
^^^^^^^^^^^^^^^^^^^^^^^

To include other states use the ``include()`` function. It takes one name per
state to include.

To extend another state use the ``extend()`` function on the name when creating
a state.

.. code-block:: python
   :linenos:

    #!pyobjects

    include('http', 'ssh')

    Service.running(extend('apache'),
                    watch=[File('/etc/httpd/extra/httpd-vhosts.conf')])

Importing from other state files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Like any Python project that grows you will likely reach a point where you want
to create reusability in your state tree and share objects between state files,
Map Data (described below) is a perfect example of this.

To facilitate this Python's ``import`` statement has been augmented to allow
for a special case when working with a Salt state tree. If you specify a Salt
url (``salt://...``) as the target for importing from then the pyobjects
renderer will take care of fetching the file for you, parsing it with all of
the pyobjects features available and then place the requested objects in the
global scope of the template being rendered.

This works for all types of import statements; ``import X``,
``from X import Y``, and ``from X import Y as Z``.

.. code-block:: python
   :linenos:

    #!pyobjects

    import salt://myfile.sls
    from salt://something/data.sls import Object
    from salt://something/data.sls import Object as Other

See the Map Data section for a more practical use.

Caveats:

* Imported objects are ALWAYS put into the global scope of your template,
  regardless of where your import statement is.

Salt object
^^^^^^^^^^^
In the spirit of the object interface for creating state data pyobjects also
provides a simple object interface to the ``__salt__`` object.

A function named ``salt`` exists in scope for your sls files and will dispatch
its attributes to the ``__salt__`` dictionary.

The following lines are functionally equivalent:

.. code-block:: python
   :linenos:

    #!pyobjects

    ret = salt.cmd.run(bar)
    ret = __salt__['cmd.run'](bar)

Pillar, grain, mine & config data
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Pyobjects provides shortcut functions for calling ``pillar.get``,
``grains.get``, ``mine.get`` & ``config.get`` on the ``__salt__`` object. This
helps maintain the readability of your state files.

Each type of data can be access by a function of the same name: ``pillar()``,
``grains()``, ``mine()`` and ``config()``.

The following pairs of lines are functionally equivalent:

.. code-block:: python
   :linenos:

    #!pyobjects

    value = pillar('foo:bar:baz', 'qux')
    value = __salt__['pillar.get']('foo:bar:baz', 'qux')

    value = grains('pkg:apache')
    value = __salt__['grains.get']('pkg:apache')

    value = mine('os:Fedora', 'network.interfaces', 'grain')
    value = __salt__['mine.get']('os:Fedora', 'network.interfaces', 'grain')

    value = config('foo:bar:baz', 'qux')
    value = __salt__['config.get']('foo:bar:baz', 'qux')

Map Data
^^^^^^^^
When building complex states or formulas you often need a way of building up a
map of data based on grain data. The most common use of this is tracking the
package and service name differences between distributions.

To build map data using pyobjects we provide a class named Map that you use to
build your own classes with inner classes for each set of values for the
different grain matches.

.. code-block:: python
   :linenos:

    #!pyobjects

    class Samba(Map):
        merge = 'samba:lookup'

        class Debian:
            server = 'samba'
            client = 'samba-client'
            service = 'samba'

        class Ubuntu:
            __grain__ = 'os'
            service = 'smbd'

        class RedHat:
            server = 'samba'
            client = 'samba'
            service = 'smb'

To use this new data you can import it into your state file and then access
your attributes. To access the data in the map you simply access the attribute
name on the base class that is extending Map. Assuming the above Map was in the
file ``samba/map.sls``, you could do the following.

.. code-block:: python
   :linenos:

    #!pyobjects

    from salt://samba/map.sls import Samba

    with Pkg.installed("samba", names=[Samba.server, Samba.client]):
        Service.running("samba", name=Samba.service)

TODO
^^^^
* Interface for working with reactor files
'''

# Import Python Libs
from __future__ import absolute_import
import logging
import os
import re

# Import Salt Libs
from salt.ext.six import exec_
import salt.utils
import salt.loader
from salt.fileclient import get_file_client
from salt.utils.pyobjects import Registry, StateFactory, SaltObject, Map
import salt.ext.six as six

# our import regexes
FROM_RE = re.compile(r'^\s*from\s+(salt:\/\/.*)\s+import (.*)$')
IMPORT_RE = re.compile(r'^\s*import\s+(salt:\/\/.*)$')
FROM_AS_RE = re.compile(r'^(.*) as (.*)$')

log = logging.getLogger(__name__)

try:
    __context__['pyobjects_loaded'] = True
except NameError:
    __context__ = {}

class PyobjectsModule(object):
    '''This provides a wrapper for bare imports.'''

    def __init__(self, name, attrs):
        self.name = name
        self.__dict__ = attrs

    def __repr__(self):
        return "<module '{0!s}' (pyobjects)>".format(self.name)

def load_states():
    '''
    This loads our states into the salt __context__
    '''
    states = {}

    # the loader expects to find pillar & grain data
    __opts__['grains'] = salt.loader.grains(__opts__)
    __opts__['pillar'] = __pillar__
    lazy_funcs = salt.loader.minion_mods(__opts__)
    lazy_utils = salt.loader.utils(__opts__)
    lazy_states = salt.loader.states(__opts__, lazy_funcs, lazy_utils)

    # TODO: some way to lazily do this? This requires loading *all* state modules
    for key, func in six.iteritems(lazy_states):
        if '.' not in key:
            continue
        mod_name, func_name = key.split('.', 1)
        if mod_name not in states:
            states[mod_name] = {}
        states[mod_name][func_name] = func

    __context__['pyobjects_states'] = states

def render(template, saltenv='base', sls='', salt_data=True, **kwargs):
    if 'pyobjects_states' not in __context__:
        load_states()

    # these hold the scope that our sls file will be executed with
    _globals = {}

    # create our StateFactory objects
    mod_globals = {'StateFactory': StateFactory}
    for mod in __context__['pyobjects_states']:
        mod_locals = {}
        mod_camel = ''.join([
            part.capitalize()
            for part in mod.split('_')
        ])
        valid_funcs = "','".join(
            __context__['pyobjects_states'][mod]
        )
        mod_cmd = "{0} = StateFactory('{1!s}', valid_funcs=['{2}'])".format(
            mod_camel,
            mod,
            valid_funcs
        )
        exec_(mod_cmd, mod_globals, mod_locals)

        _globals[mod_camel] = mod_locals[mod_camel]

    # add our include and extend functions
    _globals['include'] = Registry.include
    _globals['extend'] = Registry.make_extend

    # add our map class
    Map.__salt__ = __salt__
    _globals['Map'] = Map

    # add some convenience methods to the global scope as well as the "dunder"
    # format of all of the salt objects
    try:
        _globals.update({
            # salt, pillar & grains all provide shortcuts or object interfaces
            'salt': SaltObject(__salt__),
            'pillar': __salt__['pillar.get'],
            'grains': __salt__['grains.get'],
            'mine': __salt__['mine.get'],
            'config': __salt__['config.get'],

            # the "dunder" formats are still available for direct use
            '__salt__': __salt__,
            '__pillar__': __pillar__,
            '__grains__': __grains__
        })
    except NameError:
        pass

    # if salt_data is not True then we just return the global scope we've
    # built instead of returning salt data from the registry
    if not salt_data:
        return _globals

    # this will be used to fetch any import files
    client = get_file_client(__opts__)

    # process our sls imports
    #
    # we allow pyobjects users to use a special form of the import statement
    # so that they may bring in objects from other files. while we do this we
    # disable the registry since all we're looking for here is python objects,
    # not salt state data
    Registry.enabled = False

    def process_template(template, template_globals):
        template_data = []
        state_globals = {}
        for line in template.readlines():
            line = line.rstrip('\r\n')
            matched = False
            for RE in (IMPORT_RE, FROM_RE):
                matches = RE.match(line)
                if not matches:
                    continue

                import_file = matches.group(1).strip()
                try:
                    imports = matches.group(2).split(',')
                except IndexError:
                    # if we don't have a third group in the matches object it means
                    # that we're importing everything
                    imports = None

                state_file = client.cache_file(import_file, saltenv)
                if not state_file:
                    raise ImportError("Could not find the file {0!r}".format(import_file))

                state_locals = {}
                with salt.utils.fopen(state_file) as state_fh:
                    state_contents, state_locals = process_template(state_fh, template_globals)
                exec_(state_contents, template_globals, state_locals)

                # if no imports have been specified then we are being imported as: import salt://foo.sls
                # so we want to stick all of the locals from our state file into the template globals
                # under the name of the module -> i.e. foo.MapClass
                if imports is None:
                    import_name = os.path.splitext(os.path.basename(state_file))[0]
                    state_globals[import_name] = PyobjectsModule(import_name, state_locals)
                else:
                    for name in imports:
                        name = alias = name.strip()

                        matches = FROM_AS_RE.match(name)
                        if matches is not None:
                            name = matches.group(1).strip()
                            alias = matches.group(2).strip()

                        if name not in state_locals:
                            raise ImportError("{0!r} was not found in {1!r}".format(
                                name,
                                import_file
                            ))
                        state_globals[alias] = state_locals[name]

                matched = True
                break

            if not matched:
                template_data.append(line)

        return "\n".join(template_data), state_globals

    # process the template that triggered the render
    final_template, final_locals = process_template(template, _globals)
    _globals.update(final_locals)

    # re-enable the registry
    Registry.enabled = True

    # now exec our template using our created scopes
    exec_(final_template, _globals)

    return Registry.salt_data()


text:
using NUnit.Framework;

using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using HostMe.Sdk.Api;
using HostMe.Sdk.Model;
using HostMe.Sdk.Client;
using System.Reflection;

namespace HostMe.Sdk.Test
{
    /// <summary>
    ///  Class for testing Message
    /// </summary>
    /// <remarks>
    /// This file is automatically generated by Swagger Codegen.
    /// Please update the test case below to test the model.
    /// </remarks>
    [TestFixture]
    public class MessageTests
    {
        private Message instance;

        /// <summary>
        /// Setup before each test
        /// </summary>
        [SetUp]
        public void Init()
        {
            instance = new Message();
        }

        /// <summary>
        /// Clean up after each test
        /// </summary>
        [TearDown]
        public void Cleanup()
        {

        }

        /// <summary>
        /// Test an instance of Message
        /// </summary>
        [Test]
        public void MessageInstanceTest()
        {
            Assert.IsInstanceOf<Message> (instance, "instance is a Message");
        }

        /// <summary>
        /// Test the property 'Id'
        /// </summary>
        [Test]
        public void IdTest()
        {
            // TODO: unit test for the property 'Id'
        }
        /// <summary>
        /// Test the property 'Body'
        /// </summary>
        [Test]
        public void BodyTest()
        {
            // TODO: unit test for the property 'Body'
        }
        /// <summary>
        /// Test the property 'Time'
        /// </summary>
        [Test]
        public void TimeTest()
        {
            // TODO: unit test for the property 'Time'
        }
        /// <summary>
        /// Test the property 'Origin'
        /// </summary>
        [Test]
        public void OriginTest()
        {
            // TODO: unit test for the property 'Origin'
        }
        /// <summary>
        /// Test the property 'IsAutoMessage'
        /// </summary>
        [Test]
        public void IsAutoMessageTest()
        {
            // TODO: unit test for the property 'IsAutoMessage'
        }
        /// <summary>
        /// Test the property 'DeliveryStatus'
        /// </summary>
        [Test]
        public void DeliveryStatusTest()
        {
            // TODO: unit test for the property 'DeliveryStatus'
        }
        /// <summary>
        /// Test the property 'DeliveryTime'
        /// </summary>
        [Test]
        public void DeliveryTimeTest()
        {
            // TODO: unit test for the property 'DeliveryTime'
        }
        /// <summary>
        /// Test the property 'DeliveryFailureReason'
        /// </summary>
        [Test]
        public void DeliveryFailureReasonTest()
        {
            // TODO: unit test for the property 'DeliveryFailureReason'
        }
        /// <summary>
        /// Test the property 'IsRead'
        /// </summary>
        [Test]
        public void IsReadTest()
        {
            // TODO: unit test for the property 'IsRead'
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hyracks.storage.am.lsm.btree;

import java.util.Random;

import org.junit.After;
import org.junit.Before;

import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.exceptions.HyracksException;
import org.apache.hyracks.storage.am.btree.OrderedIndexBulkLoadTest;
import org.apache.hyracks.storage.am.btree.OrderedIndexTestContext;
import org.apache.hyracks.storage.am.btree.frames.BTreeLeafFrameType;
import org.apache.hyracks.storage.am.config.AccessMethodTestsConfig;
import org.apache.hyracks.storage.am.lsm.btree.util.LSMBTreeTestContext;
import org.apache.hyracks.storage.am.lsm.btree.util.LSMBTreeTestHarness;

@SuppressWarnings("rawtypes")
public class LSMBTreeMultiBulkLoadTest extends OrderedIndexBulkLoadTest {
    public LSMBTreeMultiBulkLoadTest() {
        // Using 5 bulk load rounds.
        super(LSMBTreeTestHarness.LEAF_FRAMES_TO_TEST, AccessMethodTestsConfig.LSM_BTREE_BULKLOAD_ROUNDS);
    }

    private final LSMBTreeTestHarness harness = new LSMBTreeTestHarness();

    @Before
    public void setUp() throws HyracksException {
        harness.setUp();
    }

    @After
    public void tearDown() throws HyracksDataException {
        harness.tearDown();
    }

    @Override
    protected OrderedIndexTestContext createTestContext(ISerializerDeserializer[] fieldSerdes, int numKeys,
            BTreeLeafFrameType leafType) throws Exception {
        return LSMBTreeTestContext.create(harness.getVirtualBufferCaches(), harness.getFileReference(),
                harness.getDiskBufferCache(), harness.getDiskFileMapProvider(), fieldSerdes, numKeys,
                harness.getBoomFilterFalsePositiveRate(), harness.getMergePolicy(), harness.getOperationTracker(),
                harness.getIOScheduler(), harness.getIOOperationCallback());
    }

    @Override
    protected Random getRandom() {
        return harness.getRandom();
    }
}


text:
package framework

import (
	"fmt"
	"io"
	"reflect"
	"sync"
	"time"

	"github.com/hashicorp/go-multierror"

	"istio.io/istio/pkg/test/framework/resource"
	"istio.io/istio/pkg/test/scopes"
)

// scope hold resources in a particular scope.
type scope struct {
	// friendly name for the scope for debugging purposes.
	id string

	parent *scope

	resources []resource.Resource

	closers []io.Closer

	children []*scope

	closeChan chan struct{}

	skipDump bool

	// Mutex to lock changes to resources, children, and closers that can be done concurrently
	mu sync.Mutex
}

func newScope(id string, p *scope) *scope {
	s := &scope{
		id:        id,
		parent:    p,
		closeChan: make(chan struct{}, 1),
	}

	if p != nil {
		p.children = append(p.children, s)
	}

	return s
}

func (s *scope) add(r resource.Resource, id *resourceID) {
	scopes.Framework.Debugf("Adding resource for tracking: %v", id)
	s.mu.Lock()
	defer s.mu.Unlock()
	s.resources = append(s.resources, r)

	if c, ok := r.(io.Closer); ok {
		s.closers = append(s.closers, c)
	}
}

func (s *scope) get(ref any) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	refVal := reflect.ValueOf(ref)
	if refVal.Kind() != reflect.Ptr {
		return fmt.Errorf("ref must be a pointer instead got: %T", ref)
	}
	// work with the underlying value rather than the pointer
	refVal = refVal.Elem()

	targetT := refVal.Type()
	if refVal.Kind() == reflect.Slice {
		// for slices look at the element type
		targetT = targetT.Elem()
	}

	for _, res := range s.resources {
		if res == nil {
			continue
		}
		resVal := reflect.ValueOf(res)
		if resVal.Type().AssignableTo(targetT) {
			if refVal.Kind() == reflect.Slice {
				refVal.Set(reflect.Append(refVal, resVal))
			} else {
				refVal.Set(resVal)
				return nil
			}
		}
	}

	if s.parent != nil {
		// either didn't find the value or need to continue filling the slice
		return s.parent.get(ref)
	}

	if refVal.Kind() != reflect.Slice {
		// didn't find the non-slice value
		return fmt.Errorf("no %v in context", targetT)
	}

	return nil
}

func (s *scope) addCloser(c io.Closer) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.closers = append(s.closers, c)
}

func (s *scope) done(nocleanup bool) error {
	scopes.Framework.Debugf("Begin cleaning up scope: %v", s.id)

	// First, wait for all of the children to be done.
	for _, c := range s.children {
		c.waitForDone()
	}

	// Upon returning, notify the parent that we're done.
	defer func() {
		close(s.closeChan)
	}()

	var err error
	// Do reverse walk for cleanup.
	for i := len(s.closers) - 1; i >= 0; i-- {
		c := s.closers[i]

		if nocleanup {
			if cc, ok := c.(*closer); ok && cc.noskip {
				continue
			} else if !ok {
				continue
			}
		}

		name := "lambda"
		if r, ok := c.(resource.Resource); ok {
			name = fmt.Sprintf("resource %v", r.ID())
		}

		scopes.Framework.Debugf("Begin cleaning up %s", name)
		if e := c.Close(); e != nil {
			scopes.Framework.Debugf("Error cleaning up %s: %v", name, e)
			err = multierror.Append(err, e).ErrorOrNil()
		}
		scopes.Framework.Debugf("Cleanup complete for %s", name)
	}

	s.mu.Lock()
	s.resources = nil
	s.closers = nil
	s.mu.Unlock()

	scopes.Framework.Debugf("Done cleaning up scope: %v", s.id)
	return err
}

func (s *scope) waitForDone() {
	<-s.closeChan
}

func (s *scope) skipDumping() {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.skipDump = true
}

func (s *scope) dump(ctx resource.Context, recursive bool) {
	s.mu.Lock()
	skip := s.skipDump
	s.mu.Unlock()
	if skip {
		return
	}
	st := time.Now()
	defer func() {
		l := scopes.Framework.Debugf
		if time.Since(st) > time.Second*10 {
			// Log slow dumps at higher level
			l = scopes.Framework.Infof
		}
		l("Done dumping: %s for %s (%v)", s.id, ctx.ID(), time.Since(st))
	}()
	s.mu.Lock()
	defer s.mu.Unlock()
	if recursive {
		for _, c := range s.children {
			c.dump(ctx, recursive)
		}
	}
	wg := sync.WaitGroup{}
	for _, c := range s.resources {
		if d, ok := c.(resource.Dumper); ok {
			d := d
			wg.Add(1)
			go func() {
				d.Dump(ctx)
				wg.Done()
			}()
		}
	}
	wg.Wait()
}


text:
import * as types from './telemetryActionTypes';

/*
    Packet structure:
    TIME,TEMPERATURE,PRESSURE,HUMIDITY,LATITUDE,LATITUDE_ORIENTATION,LONGITUDE,LONGITUDE_ORIENTATION,ALTITUDE,RSSI,BATTERY_LEVEL,PROPELLER_ROTATION,X_ACCELERATION,Y_ACCELERATION,Z_ACCELERATION,X_ROTATION,Y_ROTATION,Z_ROTATION,X_MAGNETIC_FIELD,Y_MAGNETIC_FIELD,Z_MAGNETIC_FIELD
*/

export const addTimeAction = time => ({
    type: types.ADD_TIME,
    payload: time
});

export const addPrimAction = (temperature, pressure, humidity) => ({
    type: types.ADD_PRIM,
    payload: {
        temperature,
        pressure,
        humidity
    }
});

export const addGpsAction = (latitudeVal, latitudeOr, longitudeVal, longitudeOr, altitudeVal) => ({
    type: types.ADD_GPS,
    payload: {
        latitude: {
            value: latitudeVal,
            orientation: latitudeOr
        },
        longitude: {
            value: longitudeVal,
            orientation: longitudeOr
        },
        altitude: altitudeVal
    }
});

export const addStatsAction = (rssi, batteryLevel) => ({
    type: types.ADD_STATS,
    payload: {
        rssi,
        batteryLevel
    }
});

export const addAccAction = (x, y, z) => ({
    type: types.ADD_ACC,
    payload: {
        x,
        y,
        z
    }
});

export const addRotAction = (x, y, z) => ({
    type: types.ADD_ROT,
    payload: {
        x,
        y,
        z
    }
});

export const addMagAction = (x, y, z) => ({
    type: types.ADD_MAG,
    payload: {
        x,
        y,
        z
    }
});

export const addVelAction = (accelerationVelocity, altitudeVelocity, pressureVelocity) => ({
    type: types.ADD_VEL,
    payload: {
        accelerationVelocity,
        altitudeVelocity,
        pressureVelocity
    }
});

export const addPacketAction = packet => ({
    type: types.ADD_PACKET,
    payload: packet
});


text:
function openFile(filename,func){
	var xhttp = new XMLHttpRequest();
	xhttp.onreadystatechange = function() {
		if (this.readyState == 4 && this.status == 200) {
			//load(this.responseText);
			//console.log(this.responsetext)
			func(this.responseText);
		}
	};
	xhttp.open("GET", "ncc1701b.data", true);
	xhttp.send();
}

var a = {
	fun : function(zzz){
		console.log(this.v);
	},
	v:10
}

function Instantiate(name,mat=mat4()){

}


text:
package test

import (
	"github.com/pkg/errors"
)

// Assert -
func Assert(value bool, message string) (string, error) {
	if !value {
		if message != "" {
			return "", errors.Errorf("assertion failed: %s", message)
		}
		return "", errors.New("assertion failed")
	}
	return "", nil
}

// Fail -
func Fail(message string) error {
	if message != "" {
		return errors.Errorf("template generation failed: %s", message)
	}
	return errors.New("template generation failed")
}

// Required -
func Required(message string, value interface{}) (interface{}, error) {
	if message == "" {
		message = "can not render template: a required value was not set"
	}

	if s, ok := value.(string); value == nil || (ok && s == "") {
		return nil, errors.New(message)
	}

	return value, nil
}


text:
import { Directive, OnDestroy, OnInit, TemplateRef, ViewContainerRef } from '@angular/core';

import { Subscription } from 'rxjs';

import { OperatorService } from 'app/core/core-services/operator.service';

/**
 * Directive to check if the operator is a superadmin
 *
 * @example <div *osIsSuperadmin ..> ... < /div>
 */
@Directive({
    selector: '[osIsSuperAdmin]'
})
export class IsSuperAdminDirective implements OnInit, OnDestroy {
    /**
     * Holds the value of the last is superadmin check. Therefore one can check, if the
     * permission has changes, to save unnecessary view updates, if not.
     */
    private lastIsSuperAdminCheckResult = false;

    private operatorSubscription: Subscription | null;

    /**
     * Constructs the directive once. Observes the operator for it's groups so the
     * directive can perform changes dynamically
     *
     * @param template inner part of the HTML container
     * @param viewContainer outer part of the HTML container (for example a `<div>`)
     * @param operator OperatorService
     */
    public constructor(
        private template: TemplateRef<any>,
        private viewContainer: ViewContainerRef,
        private operator: OperatorService
    ) {}

    public ngOnInit(): void {
        // observe groups of operator, so the directive can actively react to changes
        this.operatorSubscription = this.operator.getUserObservable().subscribe(() => {
            this.updateView();
        });
    }

    public ngOnDestroy(): void {
        if (this.operatorSubscription) {
            this.operatorSubscription.unsubscribe();
        }
    }

    /**
     * Shows or hides certain content in the view.
     */
    private updateView(): void {
        const isSuperadmin = this.operator.isSuperAdmin;
        const superADminChanged = isSuperadmin !== this.lastIsSuperAdminCheckResult;

        if (isSuperadmin && superADminChanged) {
            // clean up and add the template
            this.viewContainer.clear();
            this.viewContainer.createEmbeddedView(this.template);
        } else if (!isSuperadmin) {
            // will remove the content of the container
            this.viewContainer.clear();
        }
        this.lastIsSuperAdminCheckResult = isSuperadmin;
    }
}


text:
#include "mongoc-prelude.h"

#ifndef MONGOC_OPTS_H
#define MONGOC_OPTS_H

#include <bson/bson.h>

#include "mongoc-client-session.h"
#include "mongoc-bulk-operation-private.h"
#include "mongoc-opts-helpers-private.h"

/**************************************************
 *
 * Generated by build/generate-opts.py.
 *
 * DO NOT EDIT THIS FILE.
 *
 *************************************************/
/* clang-format off */

typedef struct _mongoc_crud_opts_t {
   mongoc_write_concern_t *writeConcern;
   bool write_concern_owned;
   mongoc_client_session_t *client_session;
   bson_validate_flags_t validate;
} mongoc_crud_opts_t;

typedef struct _mongoc_update_opts_t {
   mongoc_crud_opts_t crud;
   bool bypass;
   bson_t collation;
   bson_value_t hint;
   bool upsert;
   bson_t let;
} mongoc_update_opts_t;

typedef struct _mongoc_insert_one_opts_t {
   mongoc_crud_opts_t crud;
   bool bypass;
   bson_t extra;
} mongoc_insert_one_opts_t;

typedef struct _mongoc_insert_many_opts_t {
   mongoc_crud_opts_t crud;
   bool ordered;
   bool bypass;
   bson_t extra;
} mongoc_insert_many_opts_t;

typedef struct _mongoc_delete_opts_t {
   mongoc_crud_opts_t crud;
   bson_t collation;
   bson_value_t hint;
   bson_t let;
} mongoc_delete_opts_t;

typedef struct _mongoc_delete_one_opts_t {
   mongoc_delete_opts_t delete;
   bson_t extra;
} mongoc_delete_one_opts_t;

typedef struct _mongoc_delete_many_opts_t {
   mongoc_delete_opts_t delete;
   bson_t extra;
} mongoc_delete_many_opts_t;

typedef struct _mongoc_update_one_opts_t {
   mongoc_update_opts_t update;
   bson_t arrayFilters;
   bson_t extra;
} mongoc_update_one_opts_t;

typedef struct _mongoc_update_many_opts_t {
   mongoc_update_opts_t update;
   bson_t arrayFilters;
   bson_t extra;
} mongoc_update_many_opts_t;

typedef struct _mongoc_replace_one_opts_t {
   mongoc_update_opts_t update;
   bson_t extra;
} mongoc_replace_one_opts_t;

typedef struct _mongoc_bulk_opts_t {
   mongoc_write_concern_t *writeConcern;
   bool write_concern_owned;
   bool ordered;
   mongoc_client_session_t *client_session;
   bson_t let;
   bson_t extra;
} mongoc_bulk_opts_t;

typedef struct _mongoc_bulk_insert_opts_t {
   bson_validate_flags_t validate;
   bson_t extra;
} mongoc_bulk_insert_opts_t;

typedef struct _mongoc_bulk_update_opts_t {
   bson_validate_flags_t validate;
   bson_t collation;
   bson_value_t hint;
   bool upsert;
   bool multi;
} mongoc_bulk_update_opts_t;

typedef struct _mongoc_bulk_update_one_opts_t {
   mongoc_bulk_update_opts_t update;
   bson_t arrayFilters;
   bson_t extra;
} mongoc_bulk_update_one_opts_t;

typedef struct _mongoc_bulk_update_many_opts_t {
   mongoc_bulk_update_opts_t update;
   bson_t arrayFilters;
   bson_t extra;
} mongoc_bulk_update_many_opts_t;

typedef struct _mongoc_bulk_replace_one_opts_t {
   mongoc_bulk_update_opts_t update;
   bson_t extra;
} mongoc_bulk_replace_one_opts_t;

typedef struct _mongoc_bulk_remove_opts_t {
   bson_t collation;
   bson_value_t hint;
   int32_t limit;
} mongoc_bulk_remove_opts_t;

typedef struct _mongoc_bulk_remove_one_opts_t {
   mongoc_bulk_remove_opts_t remove;
   bson_t extra;
} mongoc_bulk_remove_one_opts_t;

typedef struct _mongoc_bulk_remove_many_opts_t {
   mongoc_bulk_remove_opts_t remove;
   bson_t extra;
} mongoc_bulk_remove_many_opts_t;

typedef struct _mongoc_change_stream_opts_t {
   int32_t batchSize;
   bson_t resumeAfter;
   bson_t startAfter;
   mongoc_timestamp_t startAtOperationTime;
   int64_t maxAwaitTimeMS;
   const char *fullDocument;
   bson_t extra;
} mongoc_change_stream_opts_t;

typedef struct _mongoc_create_index_opts_t {
   mongoc_write_concern_t *writeConcern;
   bool write_concern_owned;
   mongoc_client_session_t *client_session;
   bson_t extra;
} mongoc_create_index_opts_t;

typedef struct _mongoc_read_write_opts_t {
   bson_t readConcern;
   mongoc_write_concern_t *writeConcern;
   bool write_concern_owned;
   mongoc_client_session_t *client_session;
   bson_t collation;
   uint32_t serverId;
   bson_t extra;
} mongoc_read_write_opts_t;

typedef struct _mongoc_gridfs_bucket_opts_t {
   const char *bucketName;
   int32_t chunkSizeBytes;
   mongoc_write_concern_t *writeConcern;
   bool write_concern_owned;
   mongoc_read_concern_t *readConcern;
   bson_t extra;
} mongoc_gridfs_bucket_opts_t;

typedef struct _mongoc_gridfs_bucket_upload_opts_t {
   int32_t chunkSizeBytes;
   bson_t metadata;
   bson_t extra;
} mongoc_gridfs_bucket_upload_opts_t;

typedef struct _mongoc_aggregate_opts_t {
   mongoc_read_concern_t *readConcern;
   mongoc_write_concern_t *writeConcern;
   bool write_concern_owned;
   mongoc_client_session_t *client_session;
   bool bypass;
   bson_t collation;
   uint32_t serverId;
   int32_t batchSize;
   bool batchSize_is_set;
   bson_t let;
   bson_t extra;
} mongoc_aggregate_opts_t;

typedef struct _mongoc_find_and_modify_appended_opts_t {
   mongoc_write_concern_t *writeConcern;
   bool write_concern_owned;
   mongoc_client_session_t *client_session;
   bson_value_t hint;
   bson_t let;
   bson_t extra;
} mongoc_find_and_modify_appended_opts_t;

bool
_mongoc_insert_one_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_insert_one_opts_t *mongoc_insert_one_opts,
   bson_error_t *error);

void
_mongoc_insert_one_opts_cleanup (mongoc_insert_one_opts_t *mongoc_insert_one_opts);

bool
_mongoc_insert_many_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_insert_many_opts_t *mongoc_insert_many_opts,
   bson_error_t *error);

void
_mongoc_insert_many_opts_cleanup (mongoc_insert_many_opts_t *mongoc_insert_many_opts);

bool
_mongoc_delete_one_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_delete_one_opts_t *mongoc_delete_one_opts,
   bson_error_t *error);

void
_mongoc_delete_one_opts_cleanup (mongoc_delete_one_opts_t *mongoc_delete_one_opts);

bool
_mongoc_delete_many_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_delete_many_opts_t *mongoc_delete_many_opts,
   bson_error_t *error);

void
_mongoc_delete_many_opts_cleanup (mongoc_delete_many_opts_t *mongoc_delete_many_opts);

bool
_mongoc_update_one_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_update_one_opts_t *mongoc_update_one_opts,
   bson_error_t *error);

void
_mongoc_update_one_opts_cleanup (mongoc_update_one_opts_t *mongoc_update_one_opts);

bool
_mongoc_update_many_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_update_many_opts_t *mongoc_update_many_opts,
   bson_error_t *error);

void
_mongoc_update_many_opts_cleanup (mongoc_update_many_opts_t *mongoc_update_many_opts);

bool
_mongoc_replace_one_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_replace_one_opts_t *mongoc_replace_one_opts,
   bson_error_t *error);

void
_mongoc_replace_one_opts_cleanup (mongoc_replace_one_opts_t *mongoc_replace_one_opts);

bool
_mongoc_bulk_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_bulk_opts_t *mongoc_bulk_opts,
   bson_error_t *error);

void
_mongoc_bulk_opts_cleanup (mongoc_bulk_opts_t *mongoc_bulk_opts);

bool
_mongoc_bulk_insert_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_bulk_insert_opts_t *mongoc_bulk_insert_opts,
   bson_error_t *error);

void
_mongoc_bulk_insert_opts_cleanup (mongoc_bulk_insert_opts_t *mongoc_bulk_insert_opts);

bool
_mongoc_bulk_update_one_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_bulk_update_one_opts_t *mongoc_bulk_update_one_opts,
   bson_error_t *error);

void
_mongoc_bulk_update_one_opts_cleanup (mongoc_bulk_update_one_opts_t *mongoc_bulk_update_one_opts);

bool
_mongoc_bulk_update_many_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_bulk_update_many_opts_t *mongoc_bulk_update_many_opts,
   bson_error_t *error);

void
_mongoc_bulk_update_many_opts_cleanup (mongoc_bulk_update_many_opts_t *mongoc_bulk_update_many_opts);

bool
_mongoc_bulk_replace_one_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_bulk_replace_one_opts_t *mongoc_bulk_replace_one_opts,
   bson_error_t *error);

void
_mongoc_bulk_replace_one_opts_cleanup (mongoc_bulk_replace_one_opts_t *mongoc_bulk_replace_one_opts);

bool
_mongoc_bulk_remove_one_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_bulk_remove_one_opts_t *mongoc_bulk_remove_one_opts,
   bson_error_t *error);

void
_mongoc_bulk_remove_one_opts_cleanup (mongoc_bulk_remove_one_opts_t *mongoc_bulk_remove_one_opts);

bool
_mongoc_bulk_remove_many_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_bulk_remove_many_opts_t *mongoc_bulk_remove_many_opts,
   bson_error_t *error);

void
_mongoc_bulk_remove_many_opts_cleanup (mongoc_bulk_remove_many_opts_t *mongoc_bulk_remove_many_opts);

bool
_mongoc_change_stream_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_change_stream_opts_t *mongoc_change_stream_opts,
   bson_error_t *error);

void
_mongoc_change_stream_opts_cleanup (mongoc_change_stream_opts_t *mongoc_change_stream_opts);

bool
_mongoc_create_index_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_create_index_opts_t *mongoc_create_index_opts,
   bson_error_t *error);

void
_mongoc_create_index_opts_cleanup (mongoc_create_index_opts_t *mongoc_create_index_opts);

bool
_mongoc_read_write_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_read_write_opts_t *mongoc_read_write_opts,
   bson_error_t *error);

void
_mongoc_read_write_opts_cleanup (mongoc_read_write_opts_t *mongoc_read_write_opts);

bool
_mongoc_gridfs_bucket_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_gridfs_bucket_opts_t *mongoc_gridfs_bucket_opts,
   bson_error_t *error);

void
_mongoc_gridfs_bucket_opts_cleanup (mongoc_gridfs_bucket_opts_t *mongoc_gridfs_bucket_opts);

bool
_mongoc_gridfs_bucket_upload_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_gridfs_bucket_upload_opts_t *mongoc_gridfs_bucket_upload_opts,
   bson_error_t *error);

void
_mongoc_gridfs_bucket_upload_opts_cleanup (mongoc_gridfs_bucket_upload_opts_t *mongoc_gridfs_bucket_upload_opts);

bool
_mongoc_aggregate_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_aggregate_opts_t *mongoc_aggregate_opts,
   bson_error_t *error);

void
_mongoc_aggregate_opts_cleanup (mongoc_aggregate_opts_t *mongoc_aggregate_opts);

bool
_mongoc_find_and_modify_appended_opts_parse (
   mongoc_client_t *client,
   const bson_t *opts,
   mongoc_find_and_modify_appended_opts_t *mongoc_find_and_modify_appended_opts,
   bson_error_t *error);

void
_mongoc_find_and_modify_appended_opts_cleanup (mongoc_find_and_modify_appended_opts_t *mongoc_find_and_modify_appended_opts);

#endif /* MONGOC_OPTS_H */


text:
<?php

/**
 * @file
 * Contains \Drupal\ctools_wizard_test\ExampleConfigEntityListBuilder.
 */

namespace Drupal\ctools_wizard_test;

use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;

/**
 * Provides a listing of Example config entity entities.
 */
class ExampleConfigEntityListBuilder extends ConfigEntityListBuilder {
  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['label'] = $this->t('Example config entity');
    $header['id'] = $this->t('Machine name');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {
    $row['label'] = $this->getLabel($entity);
    $row['id'] = $entity->id();
    // You probably want a few more properties here...
    return $row + parent::buildRow($entity);
  }

  /**
   * @inheritDoc
   */
  public function getOperations(EntityInterface $entity) {
    $operations = parent::getOperations($entity);

    if (!empty($operations['edit'])) {
      /** @var \Drupal\Core\Url $edit */
      $edit = $operations['edit']['url'];
      $edit->setRouteParameters([
        'machine_name' => $entity->id(),
        'step' => 'general',
      ]);
    }

    return $operations;
  }

}


text:
Write the bare minimum test. Yes, this bit of code is obviously doing a lot. But, for it to work most of the time, what needs to have been accomplished by the end?

## Step 2

Write out in prose (or say outloud) what is happening in the function/block of code that you want to refactor.

We are opening up a window, and setting its resolution, and then opening up a second window, and setting its resolution. Then we are setting other properties for the windows, lenses and cameras<!-- .element: class="fragment" data-fragment-index="1" -->

_Wait a minute, why are we doing it that way?_<!-- .element: class="fragment" data-fragment-index="2" -->

## Step 3

Make an outline. Yes, an old-fashioned outline like your English teacher made you write before you could start your essay.

Sample outline as code is currently written:<!-- .element: class="fragment" data-fragment-index="1" -->

1. Open both Windows<!-- .element: class="fragment" data-fragment-index="1" -->
   * a. set resolution<!-- .element: class="fragment" data-fragment-index="1" -->
2. Set Properties<!-- .element: class="fragment" data-fragment-index="1" -->
   * a. window<!-- .element: class="fragment" data-fragment-index="1" -->
   * b. lens<!-- .element: class="fragment" data-fragment-index="1" -->
   * c. camera<!-- .element: class="fragment" data-fragment-index="1" -->

## Step 4

_Notice that the outline may not make sense._<!-- .element: class="fragment" data-fragment-index="1" -->

_Play around with outline until it actually makes sense._<!-- .element: class="fragment" data-fragment-index="2" -->

_Subpoints may not be necessary to outline._<!-- .element: class="fragment" data-fragment-index="3" -->

Revised Sample Outline<!-- .element: class="fragment" data-fragment-index="4" -->

1. Open both Windows<!-- .element: class="fragment" data-fragment-index="4" -->
2. Set Window properties<!-- .element: class="fragment" data-fragment-index="4" -->
3. Set Lens Properties<!-- .element: class="fragment" data-fragment-index="4" -->
4. Set Camera Properties<!-- .element: class="fragment" data-fragment-index="4" -->

## Step 5

Your main bullet points are your new function calls.

Everything else goes in one of these calls.

## Step 6

Write a test for each of your new functions!

## Thank you for listening!

https://codedragon.github.io/refactor_lightning/

maria@mariakathryn.net

Twitter: @twiteness

Github: codedragon

Website: mariakathryn.net


text:
(function() {
  var Rufinol, ViewBase;
  var __extends = function(child, parent) {
    var ctor = function(){};
    ctor.prototype = parent.prototype;
    child.prototype = new ctor();
    child.prototype.constructor = child;
    if (typeof parent.extended === "function") parent.extended(child);
    child.__super__ = parent.prototype;
  };
  Rufinol = this.Rufinol || (this.Rufinol = {});
  Rufinol.views || (Rufinol.views = {});
  ViewBase = function() {
    return Backbone.View.apply(this, arguments);
  };
  __extends(ViewBase, Backbone.View);
  ViewBase.prototype.initialize = function(options) {
    if (options) {
      this.templateSelector || (this.templateSelector = options.templateSelector);
    }
    return this.template || (this.template = Handlebars.compile(this.templateContent()));
  };
  ViewBase.prototype.templateContent = function() {
    return $(this.templateSelector).html();
  };
  ViewBase.prototype.renderTemplate = function(data) {
    if (this.template) {
      return this.template(data);
    }
  };
  ViewBase.prototype.data = function() {
    return this.model.toJSON();
  };
  ViewBase.prototype.render = function() {
    var rendered;
    rendered = this.renderTemplate(this.data());
    $(this.el).html(rendered);
    return this;
  };
  Rufinol.views.Base = ViewBase;
}).call(this);


text:
package org.dylanfoundry.deft.filetypes.dylan.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface DylanConstantFragment extends DylanCompositeElement {

  @Nullable
  DylanConstant getConstant();

  @Nullable
  DylanConstants getConstants();

  @Nullable
  DylanString getString();

  @Nullable
  DylanSymbol getSymbol();

}


text:
package org.apache.jackrabbit.oak.spi.security.authentication.external.impl;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.jcr.Credentials;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;

import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.oak.api.AuthInfo;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.commons.DebugTimer;
import org.apache.jackrabbit.oak.namepath.NamePathMapper;
import org.apache.jackrabbit.oak.plugins.value.ValueFactoryImpl;
import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters;
import org.apache.jackrabbit.oak.spi.security.authentication.AbstractLoginModule;
import org.apache.jackrabbit.oak.spi.security.authentication.AuthInfoImpl;
import org.apache.jackrabbit.oak.spi.security.authentication.ImpersonationCredentials;
import org.apache.jackrabbit.oak.spi.security.authentication.PreAuthenticatedLogin;
import org.apache.jackrabbit.oak.spi.security.authentication.credentials.SimpleCredentialsSupport;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityException;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityProvider;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityProviderManager;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityRef;
import org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalUser;
import org.apache.jackrabbit.oak.spi.security.authentication.credentials.CredentialsSupport;
import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncContext;
import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncException;
import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncHandler;
import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncManager;
import org.apache.jackrabbit.oak.spi.security.authentication.external.SyncedIdentity;
import org.apache.jackrabbit.oak.spi.whiteboard.Whiteboard;
import org.apache.jackrabbit.oak.spi.whiteboard.WhiteboardUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * {@code ExternalLoginModule} implements a {@code LoginModule} that uses an
 * {@link ExternalIdentityProvider} for authentication.
 */
public class ExternalLoginModule extends AbstractLoginModule {

    private static final Logger log = LoggerFactory.getLogger(ExternalLoginModule.class);

    private static final int MAX_SYNC_ATTEMPTS = 50;

    /**
     * Name of the parameter that configures the name of the external identity provider.
     */
    public static final String PARAM_IDP_NAME = SyncHandlerMapping.PARAM_IDP_NAME;

    /**
     * Name of the parameter that configures the name of the synchronization handler.
     */
    public static final String PARAM_SYNC_HANDLER_NAME = SyncHandlerMapping.PARAM_SYNC_HANDLER_NAME;

    private ExternalIdentityProviderManager idpManager;

    private SyncManager syncManager;

    private CredentialsSupport credentialsSupport = SimpleCredentialsSupport.getInstance();

    /**
     * internal configuration when invoked from a factory rather than jaas
     */
    private ConfigurationParameters osgiConfig;

    /**
     * The external identity provider as specified by the {@link #PARAM_IDP_NAME}
     */
    private ExternalIdentityProvider idp;

    /**
     * The configured sync handler as specified by the {@link #PARAM_SYNC_HANDLER_NAME}
     */
    private SyncHandler syncHandler;

    /**
     * The external user as resolved in the login call.
     */
    private ExternalUser externalUser;

    /**
     * Login credentials
     */
    private Credentials credentials;

    /**
     * Default constructor for the OSGIi LoginModuleFactory case and the default non-OSGi JAAS case.
     */
    @SuppressWarnings("UnusedDeclaration")
    public ExternalLoginModule() {
    }

    /**
     * Creates a new ExternalLoginModule with the given OSGi config.
     * @param osgiConfig the config
     */
    public ExternalLoginModule(ConfigurationParameters osgiConfig) {
        this.osgiConfig = osgiConfig;
    }

    //--------------------------------------------------------< LoginModule >---
    @Override
    public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> opts) {
        super.initialize(subject, callbackHandler, sharedState, opts);

        // merge options with osgi options if needed
        if (osgiConfig != null) {
            options = ConfigurationParameters.of(osgiConfig, options);
        }

        Whiteboard whiteboard = getWhiteboard();
        if (whiteboard == null) {
            log.error("External login module needs whiteboard. Will not be used for login.");
            return;
        }

        String idpName = options.getConfigValue(PARAM_IDP_NAME, "");
        if (idpName.isEmpty()) {
            log.error("External login module needs IPD name. Will not be used for login.");
        } else {
            if (idpManager == null) {
                idpManager = WhiteboardUtils.getService(whiteboard, ExternalIdentityProviderManager.class);
            }
            if (idpManager == null) {
                log.error("External login module needs IDPManager. Will not be used for login.");
            } else {
                idp = idpManager.getProvider(idpName);
                if (idp == null) {
                    log.error("No IDP found with name {}. Will not be used for login.", idpName);
                }
            }
        }

        String syncHandlerName = options.getConfigValue(PARAM_SYNC_HANDLER_NAME, "");
        if (syncHandlerName.isEmpty()) {
            log.error("External login module needs SyncHandler name. Will not be used for login.");
        } else {
            if (syncManager == null) {
                syncManager = WhiteboardUtils.getService(whiteboard, SyncManager.class);
            }
            if (syncManager == null) {
                log.error("External login module needs SyncManager. Will not be used for login.");
            } else {
                syncHandler = syncManager.getSyncHandler(syncHandlerName);
                if (syncHandler == null) {
                    log.error("No SyncHandler found with name {}. Will not be used for login.", syncHandlerName);
                }
            }
        }

        if (idp instanceof CredentialsSupport) {
            credentialsSupport = (CredentialsSupport) idp;
        } else {
            log.debug("No 'SupportedCredentials' configured. Using default implementation supporting 'SimpleCredentials'.");
        }
    }

    @Override
    public boolean login() throws LoginException {
        if (idp == null || syncHandler == null) {
            return false;
        }
        credentials = getCredentials();

        // check if we have a pre authenticated login from a previous login module
        final PreAuthenticatedLogin preAuthLogin = getSharedPreAuthLogin();
        final String userId = getUserId(preAuthLogin, credentials);

        if (userId == null && credentials == null) {
            log.debug("No credentials|userId found for external login module. ignoring.");
            return false;
        }

        // remember identification for log-output
        Object logId = (userId != null) ? userId : credentials;
        try {
            SyncedIdentity sId = null;
            UserManager userMgr = getUserManager();
            if (userId != null && userMgr != null) {
                sId = syncHandler.findIdentity(userMgr, userId);
                // if there exists an authorizable with the given userid but is
                // not an external one or if it belongs to another IDP, we just ignore it.
                if (sId != null) {
                    ExternalIdentityRef externalIdRef = sId.getExternalIdRef();
                    if (externalIdRef == null) {
                        log.debug("ignoring local user: {}", sId.getId());
                        return false;
                    } else if (!idp.getName().equals(externalIdRef.getProviderName())) {
                        if (log.isDebugEnabled()) {
                            log.debug("ignoring foreign identity: {} (idp={})", externalIdRef.getString(), idp.getName());
                        }
                        return false;
                    }
                }
            }

            if (preAuthLogin != null) {
                if (sId != null && !syncHandler.requiresSync(sId)) {
                    log.debug("pre-authenticated external user {} does not require syncing.", sId);
                    return false;
                }
                externalUser = idp.getUser(preAuthLogin.getUserId());
            } else {
                externalUser = idp.authenticate(credentials);
            }

            if (externalUser != null) {
                log.debug("IDP {} returned valid user {}", idp.getName(), externalUser);

                if (credentials != null) {
                    //noinspection unchecked
                    sharedState.put(SHARED_KEY_CREDENTIALS, credentials);
                }

                //noinspection unchecked
                sharedState.put(SHARED_KEY_LOGIN_NAME, externalUser.getId());

                syncUser(externalUser);

                return true;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("IDP {} returned null for {}", idp.getName(), logId);
                }

                if (sId != null) {
                    // invalidate the user if it exists as synced variant
                    log.debug("local user exists for '{}'. re-validating.", sId.getId());
                    validateUser(sId.getId());
                }
                return false;
            }
        } catch (ExternalIdentityException e) {
            log.error("Error while authenticating '{}' with {}", logId, idp.getName(), e);
            return false;
        } catch (LoginException e) {
            log.debug("IDP {} throws login exception for '{}': {}", idp.getName(), logId, e.getMessage());
            throw e;
        } catch (Exception e) {
            log.debug("SyncHandler {} throws sync exception for '{}'", syncHandler.getName(), logId, e);
            LoginException le = new LoginException("Error while syncing user.");
            le.initCause(e);
            throw le;
        }
    }

    @Override
    public boolean commit() throws LoginException {
        if (externalUser == null) {
            // login attempt in this login module was not successful
            clearState();
            return false;
        }
        Set<? extends Principal> principals = getPrincipals(externalUser.getId());
        if (!principals.isEmpty()) {
            if (!subject.isReadOnly()) {
                subject.getPrincipals().addAll(principals);
                if (credentials != null) {
                    subject.getPublicCredentials().add(credentials);
                }
                setAuthInfo(createAuthInfo(externalUser.getId(), principals), subject);
            } else {
                log.debug("Could not add information to read only subject {}", subject);
            }
            return true;
        }
        clearState();
        return false;
    }

    @Override
    public boolean abort() throws LoginException {
        clearState();
        // do we need to remove the user again, in case we created it during login() ?
        return true;
    }

    //------------------------------------------------------------< private >---

    @CheckForNull
    private String getUserId(@CheckForNull PreAuthenticatedLogin preAuthLogin, @CheckForNull Credentials credentials) {
        if (preAuthLogin != null) {
            return preAuthLogin.getUserId();
        } else if (credentials != null){
            return credentialsSupport.getUserId(credentials);
        } else {
            return null;
        }
    }

    /**
     * Initiates synchronization of the external user.
     * @param user the external user
     * @throws SyncException if an error occurs
     */
    private void syncUser(@Nonnull ExternalUser user) throws SyncException {
        Root root = getRoot();
        if (root == null) {
            throw new SyncException("Cannot synchronize user. root == null");
        }
        UserManager userManager = getUserManager();
        if (userManager == null) {
            throw new SyncException("Cannot synchronize user. userManager == null");
        }

        int numAttempt = 0;
        while (numAttempt++ < MAX_SYNC_ATTEMPTS) {
            SyncContext context = null;
            try {
                DebugTimer timer = new DebugTimer();
                context = syncHandler.createContext(idp, userManager, new ValueFactoryImpl(root, NamePathMapper.DEFAULT));
                context.sync(user);
                timer.mark("sync");
                root.commit();
                timer.mark("commit");
                if (log.isDebugEnabled()) {
                    log.debug("syncUser({}) {}", user.getId(), timer.getString());
                }
                return;
            } catch (CommitFailedException e) {
                log.warn("User synchronization failed during commit: {}. (attempt {}/{})", e.toString(), numAttempt, MAX_SYNC_ATTEMPTS);
                root.refresh();
            } finally {
                if (context != null) {
                    context.close();
                }
            }
        }
        throw new SyncException("User synchronization failed during commit after " + MAX_SYNC_ATTEMPTS + " attempts");
    }

    /**
     * Initiates synchronization of a possible remove user
     * @param id the user id
     */
    private void validateUser(@Nonnull String id) throws SyncException {
        SyncContext context = null;
        try {
            Root root = getRoot();
            if (root == null) {
                throw new SyncException("Cannot synchronize user. root == null");
            }
            UserManager userManager = getUserManager();
            if (userManager == null) {
                throw new SyncException("Cannot synchronize user. userManager == null");
            }
            DebugTimer timer = new DebugTimer();
            context = syncHandler.createContext(idp, userManager, new ValueFactoryImpl(root, NamePathMapper.DEFAULT));
            context.sync(id);
            timer.mark("sync");
            root.commit();
            timer.mark("commit");
            if (log.isDebugEnabled()) {
                log.debug("validateUser({}) {}", id, timer.getString());
            }
        } catch (CommitFailedException e) {
            throw new SyncException("User synchronization failed during commit.", e);
        } finally {
            if (context != null) {
                context.close();
            }
        }

    }

    @Nonnull
    private AuthInfo createAuthInfo(@Nonnull String userId, @Nonnull Set<? extends Principal> principals) {
        Credentials creds;
        if (credentials instanceof ImpersonationCredentials) {
            creds = ((ImpersonationCredentials) credentials).getBaseCredentials();
        } else {
            creds = credentials;
        }
        Map<String, Object> attributes = new HashMap<String, Object>();
        Object shared = sharedState.get(SHARED_KEY_ATTRIBUTES);
        if (shared instanceof Map) {
            for (Map.Entry entry : ((Map<?,?>) shared).entrySet()) {
                attributes.put(entry.getKey().toString(), entry.getValue());
            }
        } else if (creds != null) {
            attributes.putAll(credentialsSupport.getAttributes(creds));
        }
        return new AuthInfoImpl(userId, attributes, principals);
    }

    //------------------------------------------------< AbstractLoginModule >---

    @Override
    protected void clearState() {
        super.clearState();
        externalUser = null;
        credentials = null;
    }

    /**
     * @return the set of credentials classes as exposed by the configured
     * {@link CredentialsSupport} implementation.
     */
    @Nonnull
    @Override
    protected Set<Class> getSupportedCredentials() {
        return credentialsSupport.getCredentialClasses();
    }

    //----------------------------------------------< public setters (JAAS) >---

    public void setSyncManager(@Nonnull SyncManager syncManager) {
        this.syncManager = syncManager;
    }

    public void setIdpManager(@Nonnull ExternalIdentityProviderManager idpManager) {
        this.idpManager = idpManager;
    }
}


text:
:man_page: mongoc_apm_command_started_get_server_id

mongoc_apm_command_started_get_server_id()
==========================================

Synopsis
--------

.. code-block:: c

  uint32_t
  mongoc_apm_command_started_get_server_id (
     const mongoc_apm_command_started_t *event);

Returns this event's server id.

Parameters
----------

* ``event``: A :symbol:`mongoc_apm_command_started_t`.

Returns
-------

The event's server id.

See Also
--------

:doc:`Introduction to Application Performance Monitoring <application-performance-monitoring>`


text:
package com.ogaclejapan.arclayout.demo;

import com.ogaclejapan.arclayout.ArcLayout;
import com.ogaclejapan.arclayout.demo.widget.ClipRevealFrame;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class DemoLikeTumblrActivity extends ActionBarActivity implements View.OnClickListener {

    private static final String KEY_DEMO = "demo";

    public static void startActivity(Context context, Demo demo) {
        Intent intent = new Intent(context, DemoLikeTumblrActivity.class);
        intent.putExtra(KEY_DEMO, demo.name());
        context.startActivity(intent);
    }

    private static Demo getDemo(Intent intent) {
        return Demo.valueOf(intent.getStringExtra(KEY_DEMO));
    }

    Toast mToast = null;

    View mRootLayout;

    ClipRevealFrame mMenuLayout;

    ArcLayout mArcLayout;

    View mCenterItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.like_a_tumblr);

        Demo demo = getDemo(getIntent());

        ActionBar bar = getSupportActionBar();
        bar.setTitle(demo.titleResId);
        bar.setDisplayHomeAsUpEnabled(true);

        mRootLayout = findViewById(R.id.root_layout);
        mMenuLayout = (ClipRevealFrame)findViewById(R.id.menu_layout);
        mArcLayout = (ArcLayout) findViewById(R.id.arc_layout);
        mCenterItem = findViewById(R.id.center_item);

        mCenterItem.setOnClickListener(this);
        for (int i = 0, size = mArcLayout.getChildCount(); i < size; i++) {
            mArcLayout.getChildAt(i).setOnClickListener(this);
        }

        findViewById(R.id.fab).setOnClickListener(this);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.fab) {
            onFabClick(v);
            return;
        }

        if (v instanceof Button) {
            showToast((Button) v);
        }

    }

    private void showToast(Button btn) {
        if (mToast != null) {
            mToast.cancel();
        }

        String text = "Clicked: " + btn.getText();
        mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        mToast.show();

    }

    private void onFabClick(View v) {
        int x = (v.getLeft() + v.getRight()) / 2;
        int y = (v.getTop() + v.getBottom()) / 2;
        float radiusOfFab = 1f * v.getWidth() / 2f;
        float radiusFromFabToRoot = (float) Math.hypot(
                Math.max(x, mRootLayout.getWidth() - x),
                Math.max(y, mRootLayout.getHeight() - y));

        if (v.isSelected()) {
            hideMenu(x, y, radiusFromFabToRoot, radiusOfFab);
        } else {
            showMenu(x, y, radiusOfFab, radiusFromFabToRoot);
        }
        v.setSelected(!v.isSelected());
    }

    private void showMenu(int cx, int cy, float startRadius, float endRadius) {
        mMenuLayout.setVisibility(View.VISIBLE);

        List<Animator> animList = new ArrayList<>();

        Animator revealAnim = createCircularReveal(mMenuLayout, cx, cy, startRadius, endRadius);
        revealAnim.setInterpolator(new AccelerateDecelerateInterpolator());
        revealAnim.setDuration(200);

        animList.add(revealAnim);
        animList.add(createShowItemAnimator(mCenterItem));

        for (int i = 0, len = mArcLayout.getChildCount(); i < len; i++) {
            animList.add(createShowItemAnimator(mArcLayout.getChildAt(i)));
        }

        AnimatorSet animSet = new AnimatorSet();
        animSet.playSequentially(animList);
        animSet.start();
    }

    private void hideMenu(int cx, int cy, float startRadius, float endRadius) {
        List<Animator> animList = new ArrayList<>();

        for (int i = mArcLayout.getChildCount() - 1; i >= 0; i--) {
            animList.add(createHideItemAnimator(mArcLayout.getChildAt(i)));
        }

        animList.add(createHideItemAnimator(mCenterItem));

        Animator revealAnim = createCircularReveal(mMenuLayout, cx, cy, startRadius, endRadius);
        revealAnim.setInterpolator(new AccelerateDecelerateInterpolator());
        revealAnim.setDuration(200);
        revealAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mMenuLayout.setVisibility(View.INVISIBLE);
            }
        });

        animList.add(revealAnim);

        AnimatorSet animSet = new AnimatorSet();
        animSet.playSequentially(animList);
        animSet.start();

    }

    private Animator createShowItemAnimator(View item) {
        float dx = mCenterItem.getX() - item.getX();
        float dy = mCenterItem.getY() - item.getY();

        item.setScaleX(0f);
        item.setScaleY(0f);
        item.setTranslationX(dx);
        item.setTranslationY(dy);

        Animator anim = ObjectAnimator.ofPropertyValuesHolder(
                item,
                AnimatorUtils.scaleX(0f, 1f),
                AnimatorUtils.scaleY(0f, 1f),
                AnimatorUtils.translationX(dx, 0f),
                AnimatorUtils.translationY(dy, 0f)
        );

        anim.setInterpolator(new DecelerateInterpolator());
        anim.setDuration(50);
        return anim;
    }

    private Animator createHideItemAnimator(final View item) {
        final float dx = mCenterItem.getX() - item.getX();
        final float dy = mCenterItem.getY() - item.getY();

        Animator anim = ObjectAnimator.ofPropertyValuesHolder(
                item,
                AnimatorUtils.scaleX(1f, 0f),
                AnimatorUtils.scaleY(1f, 0f),
                AnimatorUtils.translationX(0f, dx),
                AnimatorUtils.translationY(0f, dy)
        );

        anim.setInterpolator(new DecelerateInterpolator());
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                item.setTranslationX(0f);
                item.setTranslationY(0f);
            }
        });
        anim.setDuration(50);
        return anim;
    }

    private Animator createCircularReveal(final ClipRevealFrame view, int x, int y, float startRadius, float endRadius) {
        final Animator reveal;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            reveal = ViewAnimationUtils.createCircularReveal(view, x, y, startRadius, endRadius);
        } else {
            view.setClipOutLines(true);
            view.setClipCenter(x, y);
            reveal = ObjectAnimator.ofFloat(view, "ClipRadius", startRadius, endRadius);
            reveal.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    view.setClipOutLines(false);
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }
        return reveal;
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Simulating DOM Events</title>
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,700,400italic,700italic">
    <link rel="stylesheet" href="../../build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/css/main.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

        Jump to Table of Contents

Simulating DOM Events

        When creating automated tests for your application or modules, you need
        to be able to mock user events.  The DOM supports creating native events
        that behave essentially the same as user generated events, though
        without the associated browser default behaviors (e.g. following a link
        on click).

        The event-simulate module adds the Y.Event.simulate method for
        working with raw DOM nodes, but for most cases, the
        node-event-simulate module is the right choice, since it allows you
        to call the simulate method directly from the Node.

Simulating Mouse Events

    There are seven mouse events that can be simulated:

click

dblclick

mousedown

mouseup

mouseover

mouseout

mousemove

    Each event is fired by calling simulate() and passing in two
    arguments: the type of event to fire and an optional object specifying
    additional information for the event. To simulate a click on the document's
    body element, for example, the following code can be used:

YUI().use('node-event-simulate', function(Y) {

    Y.one("body").simulate("click");
});

    This code simulates a click with all of the default properties on the
    event object. To specify additional information, such as the
    Shift key being down, the second argument must be used and the exact DOM
    name for the event property specified (there is browser-normalizing logic
    that translates these into browser-specific properties when necessary):

Y.one("body").simulate("click", { shiftKey: true });

    In this updated example, a click event is fired on the document's body
    while simulating that the Shift key is down.

    The extra properties to specify vary depending on the event being simulated
    and are limited to this list:

detail

            Indicates the number of times a button was clicked (DOM-compliant
            browsers only).

screenX, screenY

            Coordinates of the mouse event in relation to the entire screen
            (DOM-compliant browsers only).

clientX, clientY

            Coordinates of the mouse event in relation to the browser client
            area.

ctrlKey, altKey, shiftKey, metaKey

            The state of the Ctrl, Alt, Shift, and Meta keys, respectively
            (true for down, false for up).

button

            The button being used for the event, 0 for left (default), 1 for
            right, 2 for center.

relatedTarget

            the element the mouse moved from (during a mouseover event) or to
            (during a mouseout event).

YUI().use('node-event-simulate', function(Y) {

    var node = Y.one("#myDiv");

    //simulate a click Alt key down
    node.simulate("click", { altKey: true});

    //simulate a double click with Ctrl key down
    node.simulate("dblclick", { ctrlKey: true });

    //simulate a mouse over
    node.simulate("mouseover", { relatedTarget: document.body });

    //simulate a mouse out
    node.simulate("mouseout", { relatedTarget: document.body });

    //simulate a mouse down at point (100,100) in the client area
    node.simulate("mousedown", { clientX: 100, clientY: 100 });

    //simulate a mouse up at point (100,100) in the client area
    node.simulate("mouseup", { clientX: 100, clientY: 100 });

    //simulate a mouse move at point (200, 200) in the client area
    node.simulate("mousemove", { clientX: 200, clientY: 200 });
});

Simulating Key Events

There are three key event simulations available:

keyup

keydown

keypress

    As with the mouse events, key events are simulated using
    simulate(). For keyup and keydown,
    the keyCode property must be specified; for
    keypress, the charCode property must be included.
    In many cases, keyCode and charCode may be the
    same value to represent the same key (97, for instance, represents the
    "A" key as well as being the ASCII code for the letter
    "a"). For example:

YUI().use('node-event-simulate', function(Y) {

    var node = Y.one("#myDiv");

    //simulate a keydown on the A key
    node.simulate("keydown", { keyCode: 97 });

    //simulate a keyup on the A key
    node.simulate("keyup", { keyCode: 97 });

    //simulate typing "a"
    node.simulate("keypress", { charCode: 97 });
});

    Key events also support the ctrlKey, altKey,
    shiftKey, and metaKey event properties.

    Note: Due to differences in browser implementations, key
    events may not be simulated in the same manner across all browsers. For
    instance, when simulating a keypress event on a textbox, only Firefox will
    update the textbox with the new character of the key that was simulated to
    be pressed. For other browsers, the events are still registered and all
    event handlers are called, however, the textbox display and
    value property are not updated. These differences should go
    away as browser support for simulated events improves in the future.

Simulating UI Events

There are several UI event simulations available:

blur

change

focus

resize

scroll

select

    As with the other events, UI events are simulated using
    simulate(). There are no properties that are required to
    simulate UI events as these events don't carry extra information. Some
    examples:

YUI().use('node-event-simulate', function(Y) {

    var node = Y.one("#myInput");

    //simulate a change event
    node.simulate("change");

    //simulate a select event
    node.simulate("select");
});

Simulating Touch Gestures

There are several high level gesture simulations primarily targeted for
smartphones, tablets, and other touch-enabled devices. Single touch gestures
such as tap and flick are simulated using Mouse Events on desktop or mobile
devices where creating Touch Events are not supported. All gesture simulations
are done by calling the simulateGesture() method against a Node instance. The
method is asynchronous by default so an optional callback function can be
passed.

tap

            Single finger gesture to simulate a tap. Default is to simulate
            one tap but it can be configured to simulate any number of taps.

doubletap

            Single finger gesture to simulate double taps.

press

            Single finger gesture to simulate a long press.

move

            Single finger gesture to simulate a move. It simulates moving
            one finger straight in any direction.

flick

            Single finger gesture to simulate the flick gesture. It simulates
            moving one finger with a certain velocity along either an X or Y
            axis.

pinch

            Two finger gesture to simulate pinch and spread gestures.

rotate

            Two finger gesture to simulate a rotate.

Gesture can be simulated by calling simulateGesture() and
passing the following arguments: the name of the gesture to simulate, an
optional object to define gesture properties, and an optional callback function.
The available properties vary per gesture.

If the location of the finger is not given, the center of the node element is
used by default. This default behavior can be overridden by passing coordinates
into the optional object. The coordinate values are relative to the top/left
corner of the node element.

Single Touch Gestures: Tap, Double Tab and Press

The following code simulates tap, double tap and press gestures:

YUI().use('node-event-simulate', function(Y) {

    var node = Y.one("#myElement");

    //simulate tap gesture
    node.simulateGesture("tap");

    //simulate double-tap gesture
    node.simulateGesture("doubletap");

    //simulate press gesture
    node.simulateGesture("press", {
        hold: 3000    // press and hold for 3000ms
    });

    // simulate tap with options and callback
    node.simulateGesture("tap", {
        point: [30, 30], // tap (30, 30) relative to the top/left of the node
        hold: 3000,      // hold for 3sec in a tap
        times: 2,        // tap 2 times
        delay: 500       // delay time before next tap starts
    }, function() {
        Y.log("I was called.");
    });
});

Valid Options

Optional properties for the tap gesture:

point

            Indicates the [x,y] coordinates where the tap should be
            simulated. Default is the center of the node element.

hold

            The hold time in milliseconds. This is the time between
            touchstart and touchend event generation.

times

            Indicates the number of taps. Default is 1.

delay

            The number of milliseconds before the next tap simulation
            happens. This is valid only when times is more than 1.

Optional properties for the doubletap gesture:

point

            Indicates the [x, y] coordinates where the doubletap should be
            simulated. Default is the center of the node element.

The press gesture is essentially a single tap with the hold property
defined. Optional properties for the press gesture:

point

            Indicates the [x, y] coordinates where the tap should be
            simulated. Default is the center of the node element.

hold

            The hold time in milliseconds. This is the time between
            touchstart and touchend event generation.

Single Touch Gestures: Move and Flick

The following code can be used To simulate various gestures of moving one
finger:

YUI().use('node-event-simulate', function(Y) {

    var node = Y.one("#myElement");

    //simulate moving a finger 200 pixels along the x-axis
    //to the right for one second (default)
    node.simulateGesture("move");

    //simulate moving a finger from the center of the node
    //to a point 70 pixels to the right and 50 pixels down over 2000ms
    node.simulateGesture("move", {
        path: {
            xdist: 70,
            ydist: -50
        } ,
        duration: 2000
    });

    //simulate a flick to the right (default)
    node.simulateGesture("flick");

    //simulate a flick down 100 pixels over 50ms
    node.simulateGesture("flick", {
        axis: "y",
        distance: -100,
        duration: 50
    });

});

Valid Options

Optional properties for the move gesture:

path

            Indicates the path of the finger movement. It's an object with three
            optional properties: point, xdist and  ydist. The point is
            the start point and defaults to the center of the node element.
            xdist and  ydist indicate the distance moved in pixels along the
            x- and y-axis. A negative distance value indicates moving to left
            for xdist and down for ydist.

duration

            The duration of the gesture in milliseconds.

Optional properties for the flick gesture:

point

            Indicates the [x, y] coordinates where the flick should be
            simulated. Default is the center of the node element.

axis

            Valid values are either "x" or "y". Indicates moving axis. The flick
            moves in only 4 directions (left, right, up and down).

distance

            Distance to move (in pixels).

duration

            The duration of the gesture in milliseconds. This value may be
            adjusted if it is below the minimum velocity to be a flick gesture.

Two Finger Gestures: Pinch and Rotate

The pinch gesture is used to simulate the pinching and spreading of two
fingers. During a pinch simulation, rotation is also possible. Essentially
pinch and rotate simulations share the same base implementation to allow
both pinching and rotation at the same time. The only difference is pinch
requires start and end option properties while rotate requires rotation
option property.

The pinch and rotate gestures can be described as placing 2 fingers along a
circle. Pinching and spreading can be described by start and end circles while
rotation occurs on a single circle. If the radius of the start circle is greater
than the end circle, the gesture becomes a pinch, otherwise it is a spread spread.

The following code can be used to simulate two finger gestures:

YUI().use('node-event-simulate', function(Y) {

    var node = Y.one("#myElement");

    //simulate a pinch: "r1" and "r2" are required
    node.simulateGesture("pinch", {
        r1: 100, // start circle radius at the center of the node
        r2: 50   // end circle radius at the center of the node
    });

    //simulate a spread: same as "pinch" gesture but r2>r1
    node.simulateGesture("pinch", {
        r1: 50,
        r2: 100
    });

    //simulate rotating a node 75 degrees counter-clockwise
    node.simulateGesture("rotate", {
        rotation: -75
    });

    //simulate a pinch and a rotation at the same time.
    //fingers start on a circle of radius 100 px, placed at top/bottom
    //fingers end on a circle of radius 50px, placed at right/left
    node.simulateGesture("pinch", {
        r1: 100,
        r2: 50,
        start: 0
        rotation: 90
    });
});

Valid Options

The optional properties available for pinch and rotate gestures are the
same:

center

            The center of the circle where the two fingers are placed. Default
            is the center of the node element.

r1

            Required for pinch gestures but optional for rotate. Pixel radius
            of the start circle. If omitted in rotate gestures, default is
            a fourth of the node element width or height, whichever is smaller.

r2

            Required for pinch gestures but optional for rotate gestures.
            Pixel radius of the end circle. If omitted in rotate gestures,
            default is a fourth of the node element width or height, whichever
            is smaller.

duration

            The duration of the gesture in milliseconds.

start

            Start degree of the first finger for the rotation gesture. Default
            is 0 (i.e., 12:00 on a clock).

rotation

            Degrees to rotate from the start degree. Negative value means
            rotation of counter-clockwise direction.

Gesture Simulation on iOS

If the gesture simulation is called in iOS, it generates not only touch events
but also
iOS specific gesture events: gesturestart, gesturechange
and gestureend.

Customizing Default Gesture Properties

You can define custom default behaviors for gesture simulations by modifying the
following Y.GestureSimulation.defaults object properties:

HOLD_TAP

DELAY_TAP

HOLD_PRESS

MIN_HOLD_PRESS

MAX_HOLD_PRESS

DISTANCE_MOVE

DURATION_MOVE

MAX_DURATION_MOVE

MIN_VELOCITY_FLICK

DISTANCE_FLICK

DURATION_FLICK

MAX_DURATION_FLICK

DURATION_PINCH

And an example:

YUI().use('node-event-simulate', function(Y) {

    var node = Y.one("#myElement");

    Y.GestureSimulation.defaults = Y.merge(Y.GestureSimulation.defaults, {
        HOLD_TAP: 3000
    });

    //now touchend event will be generated after 3 sec from the touchstart
    //event generation.
    node.simulateGesture("tap");
});

Caveats and Coming Soons

Don't use simulation in user facing code

    Event simulation is for automated testing.  Your application should respond
    to real user events.  For reasons
    mentioned below, it can be easy to get
    your application into a confused runtime state when some callbacks have
    been executed but not others.

    Typically, event simulation is sought to trigger certain callbacks.  If a
    function needs to respond to user action or be called programmatically, it
    should be written accordingly and called directly in the latter case.
    Often a better solution is to extract the core logic from the event handler
    into a separate function and call that method from the event handler and
    from the other part of the application that was going to use simulation.

    In some cases, simulation is wanted because there may be any number of
    subscriptions on a node, and all applicable callbacks should be triggered.
    If this is the case, investigate using custom events, instead.

    The bottom line is, reliance on event simulation in production code is a
    warning sign that the architecture is not scaling.  The affected code
    should be refactored before it becomes a larger problem.

Only what you ask for

    In many cases, events happen in groups (mousedown, mouseup, click, or
    keydown, keyup, keypress).  If you simulate an event that is
    typically part of a group or is often followed by other events, the
    other events will NOT be generated for free.

    For example, if you simulate a click event on a submit button, you only
    simulate the click event.  The preceding mousedown and mouseup, as
    well as the subsequently expected 'submit' are neither simulated or fired
    natively.

No synthetic event simulation yet

    The Synthetic event system doesn't yet support
    defining simulation. In most cases, though, synthetic events are triggered
    by other DOM events that can be simulated, so it's often possible to
    trigger them by simulating the underlying events.  But that ignores the
    point that synthetic events are supposed to mask that abstraction for your
    benefit.

    Support for synthetic event simulation is on the roadmap.

Table of Contents

Simulating Mouse Events

Simulating Key Events

Simulating UI Events

Simulating Touch Gestures

Single Touch Gestures: Tap, Double Tab and Press

Valid Options

Single Touch Gestures: Move and Flick

Valid Options

Two Finger Gestures: Pinch and Rotate

Valid Options

Gesture Simulation on iOS

Customizing Default Gesture Properties

Caveats and Coming Soons

Don't use simulation in user facing code

Only what you ask for

No synthetic event simulation yet

Examples

                                            Simple DOM Events

                                            Creating an Arrow Event for DOM Subscription

                                            Supporting A Swipe Left Gesture

Examples That Use This Component

                                            Photo Browser

                                            Portal Style Example

                                            Extending the Base Widget Class

                                            Accessible Menu Button

                                            HTTP GET to request data


text:
using System;
using System.Drawing;
using System.Linq;

namespace SudokuSolver
{
    public class BoardRenderer
    {
        private const float Gbw = 1;

        private readonly Board board;

        private Size viewportSize;
        private SizeF cellSize;
        private SizeF boardSize;

        public Image RenderingImage { get; set; }

        public event Action RenderingComplete;
        public void OnRenderingComplete()
        {
            Action handler = RenderingComplete;
            handler?.Invoke();
        }

        public BoardRenderer(Board s, Size viewportSize)
        {
            board = s;
            this.viewportSize = viewportSize;

            CreateImage();
        }

        public void UpdateViewportSize(Size viewportSize)
        {
            this.viewportSize = viewportSize;
            CreateImage();
            RenderBoard();
        }

        private void CreateImage()
        {
            if (RenderingImage != null)
            {
                RenderingImage.Dispose();
                RenderingImage = null;
            }

            RenderingImage = new Bitmap(this.viewportSize.Width, this.viewportSize.Height);

            boardSize = new SizeF(this.viewportSize.Width,
                                  this.viewportSize.Height);
            cellSize = new SizeF((boardSize.Width - Gbw) / Board.BoardSize,
                                 (boardSize.Height - Gbw) / Board.BoardSize);
        }

        public void RenderBoard()
        {
            using (Graphics g = Graphics.FromImage(RenderingImage))
            {
                DrawGrid(g, board, cellSize, new PointF(0, 0), new Size(Board.BoardSize, Board.BoardSize));
                DrawCellValues(g, board, cellSize, new PointF(0, 0));
            }

            OnRenderingComplete();
        }

        private void DrawCellValues(Graphics graphics, Board board, SizeF drawCellSize, PointF boardTopLeft)
        {
            Font valueFont = new Font(FontFamily.GenericMonospace, 25, FontStyle.Bold);
            Font fiftyFiftyFint = new Font(FontFamily.GenericMonospace, 10, FontStyle.Bold);

            for (int y = 0; y < Board.BoardSize; y++)
            {
                for (int x = 0; x < Board.BoardSize; x++)
                {
                    var cell = board.GetCell(x, y);

                    if (cell.Excluded)
                    {
                        RectangleF cellInterior = new RectangleF(
                            drawCellSize.Width * x + Gbw*3 + boardTopLeft.X,
                            drawCellSize.Height * y + Gbw*3 + boardTopLeft.Y,
                            drawCellSize.Width - Gbw*6,
                            drawCellSize.Height - Gbw*6);

                        graphics.FillRectangle(new SolidBrush(Color.LightCoral), cellInterior);
                    }

                    if (cell.Highlight)
                    {
                        RectangleF cellInterior = new RectangleF(
                            drawCellSize.Width * x + Gbw * 8 + boardTopLeft.X,
                            drawCellSize.Height * y + Gbw * 8 + boardTopLeft.Y,
                            drawCellSize.Width - Gbw * 16,
                            drawCellSize.Height - Gbw * 16);

                        graphics.FillRectangle(new SolidBrush(Color.LightBlue), cellInterior);
                    }

                    if (cell.FiftyFiftyExclusion)
                    {
                        RectangleF cellInterior = new RectangleF(
                            drawCellSize.Width * x + Gbw * 12 + boardTopLeft.X,
                            drawCellSize.Height * y + Gbw * 12 + boardTopLeft.Y,
                            drawCellSize.Width - Gbw * 24,
                            drawCellSize.Height - Gbw * 24);

                        graphics.FillRectangle(new SolidBrush(Color.DarkOrange), cellInterior);
                    }

                    if (cell.Guessed)
                    {
                        RectangleF cellInterior = new RectangleF(
                            drawCellSize.Width * x + Gbw * 16 + boardTopLeft.X,
                            drawCellSize.Height * y + Gbw * 16 + boardTopLeft.Y,
                            drawCellSize.Width - Gbw * 32,
                            drawCellSize.Height - Gbw * 32);

                        graphics.FillRectangle(new SolidBrush(Color.MediumPurple), cellInterior);
                    }

                    if (cell.Value != SudokuCell.EmptyValue)
                    {
                        var s = cell.Value.ToString();
                        var stringSize = graphics.MeasureString(s, valueFont);

                        PointF textPoint = new PointF(
                            boardTopLeft.X + drawCellSize.Width * x + drawCellSize.Width / 2 - stringSize.Width / 2,
                            boardTopLeft.Y + drawCellSize.Height * y + drawCellSize.Height / 2 - stringSize.Height / 2 +
                            Gbw * 3
                        );

                        graphics.DrawString(s, valueFont, Brushes.Black, textPoint);
                    }

                    if (cell.FiftyFifties.Any())
                    {
                        string fiftyFifties= string.Join(",", cell.FiftyFifties);

                        PointF textPoint = new PointF(
                            boardTopLeft.X + drawCellSize.Width * x,
                            boardTopLeft.Y + drawCellSize.Height * y
                        );

                        graphics.DrawString(fiftyFifties, fiftyFiftyFint, Brushes.Blue, textPoint);
                    }
                }
            }
        }

        private void DrawGrid(Graphics g, Board b, SizeF drawCellSize, PointF boardTopLeft, Size boardCellCount)
        {
            g.Clear(Color.Wheat);

            // draw grid
            Pen gridPen = new Pen(Color.Gray, Gbw);
            Pen thickGridPen = new Pen(Color.Gray, Gbw*4);
            float gbw2 = Gbw / 2;
            for (int y = 0; y < boardCellCount.Width + 1; y++)
            {
                g.DrawLine(y % 3 == 0 ? thickGridPen : gridPen,
                    boardTopLeft.X + drawCellSize.Width * y + gbw2,
                    boardTopLeft.Y,
                    boardTopLeft.X + drawCellSize.Width * y + gbw2,
                    boardTopLeft.Y + drawCellSize.Height * boardCellCount.Height + Gbw);
            }
            for (int x = 0; x < boardCellCount.Height + 1; x++)
            {
                g.DrawLine(x % 3 == 0 ? thickGridPen : gridPen,
                    boardTopLeft.X,
                    boardTopLeft.Y + drawCellSize.Height * x + gbw2,
                    boardTopLeft.X + drawCellSize.Width * boardCellCount.Width + Gbw,
                    boardTopLeft.Y + drawCellSize.Height * x + gbw2);
            }

            //// draw board cells
            //for (int x = 0; x < boardCellCount.Width; x++)
            //{
            //    for (int y = 0; y < boardCellCount.Height; y++)
            //    {
            //        RectangleF cellInterior = new RectangleF(
            //        drawCellSize.Width * x + Gbw + boardTopLeft.X,
            //        drawCellSize.Height * y + Gbw + boardTopLeft.Y,
            //        drawCellSize.Width - Gbw,
            //        drawCellSize.Height - Gbw);

            //        g.FillRectangle(new SolidBrush(Color.Wheat), cellInterior);
            //    }
            //}
        }
    }
}


text:
package com.buildria.mocking.serializer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JAXBXmlSerializer implements ObjectSerializer {

    private final ObjectSerializerContext ctx;

    public JAXBXmlSerializer(ObjectSerializerContext ctx) {
        this.ctx = Objects.requireNonNull(ctx);
    }

    @Override
    public byte[] serialize(@Nonnull Object obj) throws IOException {
        Objects.requireNonNull(obj);
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(
                    Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
            marshaller.setProperty(
                    Marshaller.JAXB_ENCODING, ctx.getCharset().toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            marshaller.marshal(obj, baos);
            return baos.toByteArray();
        } catch (JAXBException ex) {
            throw new IOException(ex);
        }

    }

    @Override
    public <T> T deserialize(@Nonnull InputStream src, @Nonnull Class<T> type)
            throws IOException {
        Objects.requireNonNull(src);
        Objects.requireNonNull(type);
        try {
            JAXBContext context = JAXBContext.newInstance(type);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            try (InputStreamReader is
                    = new InputStreamReader(src, ctx.getCharset())) {
                Object obj = unmarshaller.unmarshal(is);
                return type.cast(obj);
            }
        } catch (JAXBException ex) {
            throw new IOException(ex);
        }
    }

}