text:
<sect1>
	<title>Writing your first service</title>
	<para>
		In this section we will write a service and discover how to
		publish methods with &peloton;. It is assumed that you have installed
		&peloton; as per the instructions in the Installation Guide and followed
		the Quickstart chapter therein to establish a functioning system.
	</para>
	<para>
		Create a folder to contain your services; we will call this
		<filename>$SERVICE_HOME</filename> and this is passed to
		<filename>psc.py</filename> as <filename>-s $SERVICE_HOME</filename>
		so that services therein can be found (alternatively, add this to the
		PYTHONPATH environment label [INVALID PRIOR TO NEW CONFIGURATION
		SETUP]).
	</para>
	<sect2>
		<title>Writing the service</title>
		<para>
			Creating a new service is very straight forward as there is a script
			called <filename>newservice.py</filename> to do the work for you:
		</para>
		<informalexample>
			<programlisting> > cd $SERVICE_HOME
 > python $PELOTON_HOME/src/tools/newservice.py -s Tutorial
			</programlisting>
		</informalexample>
		<para>
			This will create a folder named <filename>tutorial</filename> under which
			there are templates for service code, configuration and support files. To
			start with, look at tutorial/tutorial which is as follows:
		</para>
		<informalexample>
			<programlisting># $Id$
from peloton.service import PelotonService
from peloton.svcdeco import *

class Tutorial(PelotonService):
	def public_sum(self, x, y):
		"Example service method."
		x = int(x)
		y = int(y)
		return x+y</programlisting>
		</informalexample>
		<para>
			First we import the base class from which all services derive,
			PelotonService and then we import all the decorators
			from svcdeco the use of which will shortly be discussed.
		</para>
		<para>
			One service method is defined here and it is called public_sum
			and will be published to the outside world as sum. It
			performs the very simple task of returning the sum of two values
			that are expected to be integers.
		</para>
		<para>
			All service methods should check their input. In this case we cast
			both input values to integers, because this is what we have defined
			the logic of the service to require. Given that you cannot know
			what protocol is being used to call this method, you must cast the
			value - if it is an HTTP request then <emphasis>all</emphasis> arguments
			will be String.
		</para>
		<para>
			Now we'll work with this simple method but please experiment and add some
			methods of your own if you're itching to get going!
		</para>
	</sect2>
	<sect2>
		<title>Calling your service</title>
		<para>
			First start a server:
		</para>
		<informalexample>
			<programlisting> > cd $PELOTON_HOME/src/peloton
 > python psc.py -c $PELOTON_HOME/example/config/psc.pcfg -s $SERVICE_HOME \
 	             --nodetach --loglevel=debug
			</programlisting>
		</informalexample>
		<note>
			<para>
				The PELOTON_HOME and SERVICE_HOME
				variables must either be defined in your shell or substituted
				as you type in this line! SERVICE_HOME is the path
				to the folder containing your tutorial  service
				folder.
			</para>
		</note>
		<para>
			Now from another shell connect to your new node and start the
			tutorial service (it is assumed that all this is happening
			on the same machine; substitute hostnames/addresses as appropriate
			if this is not the case):
		</para>
		<informalexample>
			<programlisting> > ssh -l admin -p 9110 localon
 admin@localhost's password: [password is "admin"]
 >>> start('Tutorial')
 >>>			</programlisting>
		</informalexample>
		<para>
			In the console running the node you should see much output (we've set
			the debugging level to DEBUG which ensures that a great
			deal is sent to the logs).
		</para>
		<para>
			Now we can make requests of our new service which, out of the box, means
			we can try all sorts of things. For example, in a web browser open
			the url:
		</para>
		<informalexample>
			<programlisting> http://localhost:8080/Tutorial/sum/1/2</programlisting>
		</informalexample>
		<para>
  		    Immediately a page is returned with the result surrounded by some default
			&peloton; formatting as in figure <xref linkend='firstservice_1'/>
		</para>
		<example  id='firstservice_1'>
			<title>HTTP request to a service</title>
			<mediaobject>
				<imageobject>
					<imagedata fileref='images/firstservice_1.png' format='PNG'/>
				</imageobject>
			</mediaobject>
		</example>
		<para>
			The same result is also obtained by:
		</para>
		<informalexample>
			<programlisting> http://localhost:8080/Tutorial/sum.html/1/2</programlisting>
		</informalexample>
		<para>
			The .html suffix is assumed if no suffix is supplied. The suffix
			indicates to &peloton; that the result should be transformed into an HTML page.
			If no template is provided by the developer, &peloton; uses a default one
			which renders the structure in an intelligible manner.
			We will add templates to this method in a later chapter.
		</para>
		<para>
			Other suffixes may be used however; for example try making the same call but
			to <filename>sum.xml</filename> instead of <filename>sum.html</filename>.
			The result is a very simple default &peloton; serialization of the
			result into XML.
		</para>
		<para>
			How about if you want a JSON formatted string? Well, just call
			<filename>sum.json</filename>; the raw, Python stringified result?
			Call <filename>sum.raw</filename>.
		</para>
		<para>
			If you make a JSON call and want a JSONP response, i.e. the data wrapped in a function call, specify the function wrapper in the callback argument, e.g.:
		</para>
		<informalexample>
			<programlisting> http://localhost:8080/Tutorial/sum.json/1/2?callback=foo</programlisting>
		</informalexample>
		<para>
			Now an integer is a fairly dull data type to serialise. Let's change
			the code to add a new method. Edit <filename>tutorial.py</filename>
			and add something that returns a dictionary, for example:
		</para>
		<informalexample>
			<programlisting>def public_returnDict(self):
    return {'name':'Matthew', 'food':'Apples',
				'pets':['dog', 'cat', 'python']}</programlisting>
		</informalexample>
		<para>
			Hopefuly you have not stopped your service node because now you can see
			how to deploy your new method. Simply connect to the SSH console and type:
		</para>
        <informalexample>
			<programlisting> >>> start('Tutorial')
Purging tutorial
Purging tutorial.tutorial
 >>>
			</programlisting>
		</informalexample>
		<para>
			The Tutorial service has now been restarted on-the-fly.
			Now you can call the new returnDict method and explore
			the result for all the different target types (XML, HTML etc). For
			example, calling http://localhost:8080/Tutorial/returnDict.xml
			returns the result in <xref linkend='firstservice_2'/>.
		</para>
		<example  id='firstservice_2'>
			<title>Request to a service for XML result</title>
			<mediaobject>
				<imageobject>
					<imagedata fileref='images/firstservice_2.png' format='PNG'/>
				</imageobject>
			</mediaobject>
		</example>
		<para>
			This is all very well, but what of real programming languages? How would
			I call it from a Python script, or a shell script? Well, the systems
			guys may well enjoy:
  	    </para>
        <informalexample>
			<programlisting> > curl http://localhost:8080/Tutorial/returnDict.xml
<?xml version="1.0"?>
<result>
<dict>
<item id="food">"Apples"</item>
<item id="name">"Matthew"</item>
<item id="pets"><list>
<item>"dog"</item>
<item>"cat"</item>
<item>"python"</item>
</list></item>
</dict>
</result>
			</programlisting>
		</informalexample>
		<para>
			Whilst a Python programmer might wish to make an XMLRPC call; try
			the following script:
		</para>
        <informalexample>
			<programlisting>#!/usr/bin/env python
import xmlrpclib
import os

server = xmlrpclib.Server('http://localhost:8080/RPC2')
# the field for which we provied '0' is a cookie field -
# to be used for authenticated requests.
result = server.request(0, "Tutorial","sum", 25, 35)
print result
			</programlisting>
		</informalexample>
	<para>
		Python programmers may also make a direct connection with Twisted:
	</para>
        <informalexample>
			<programlisting>#!/usr/bin/env python
from twisted.internet import reactor
from twisted.spread import pb
import sys

HOST='localhost'

def clientConnect(svr, x, y):
    d = svr.callRemote('login', 'blah')
    d.addCallback(gotIface, x, y)
    d.addErrback(error)

def gotIface(iface, x, y):
    d = iface.callRemote('call', 'Tutorial', 'sum', x, y)
    d.addCallback(done, x, y)
    d.addErrback(error)

def done(result, x, y):
    print("Sum of %d + %d = %d" % (x,y,result))
    reactor.stop()

def error(err):
    print("Ooooh - error:%s " % err.value)
    reactor.stop()

def main(x, y):
    factory = pb.PBClientFactory()
    reactor.connectTCP(HOST, 9100, factory)
    d = factory.getRootObject()
    d.addCallback(clientConnect, int(x), int(y))
    d.addErrback(error)
    reactor.run()
    return 0

if __name__ == '__main__':
    sys.exit(main(*sys.argv[1:3]))			</programlisting>
		</informalexample>
	<para>
		From the shell, this script can be called with two integer arguments:
	</para>
	<informalexample>
		<programlisting> > ./psum.py 34 35
 Sum of 34 + 35 = 69
</programlisting>
	</informalexample>
	</sect2>
	<sect2>
		<title>Special case one: Inspecting a request</title>
		<para>
			Sometimes when debugging you may wish to see the innards of an HTTP
			request. To do so, make a call to your method in the browser, inserting
			inspect before the service name. For example:
		</para>
		<informalexample>
			<programlisting> http://localhost:8080/inspect/Tutorial/getDictionary.xml</programlisting>
		</informalexample>
		<para>
			This returns a page with details of the request, which host the
			request came from etc.
		</para>
	</sect2>
	<sect2>
		<title>Special case two: index page</title>
		<para>
			If an http request is made to a service with no
			method specified, &peloton; forwards this to the index
			method (public_index(self)) which has a default defined
			in the PelotonService class that you should override if you
			wish this URL format to return a meaningful result.
		</para>
	</sect2>
		<sect2>
		<title>Summary</title>
	<para>
		So any method simply takes Python arguments and returns a Python structure.
		&peloton; takes care of translating the data input into an appropriate
		call and serializes the result into a form suitable for the client. The service
		writer is at no point bothered by the niceties of this process. Within seconds
		one can have written and published a method that is consumable by pretty much
		any shell script or program written in any language.
	</para>
		<para>
			We've also seen how services may be edited and re-started on-the-fly
			very easily.
 	    </para>
	</sect2>
</sect1>
<sect1>
	<title>Resilience</title>
	<para>
		The example services in the <filename>example/service</filename> folder and
		the scripts in the <filename>scripts</filename> sub-folder provide a starting
		point for some simple testing. You will be able to use <filename>testpclient.py</filename>
		to perform a long running operation with many, many calls. During this time you
		will be able to kill worker nodes and see them bounce back; kill PSC nodes (excluding
		the one to which the client connects) and see no change in the result returned
		to the client.
	</para>
</sect1>


text:
package mobi.cloudymail.mailclient;

import mobi.cloudymail.mailclient.net.ServerAgent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;

public class NetworkChangeReceiver extends BroadcastReceiver {
	public static final String CONNECTIVITY_ACTION=ConnectivityManager.CONNECTIVITY_ACTION;
	static private java.util.Date networkLostTime;
    @Override
    public void onReceive(Context context, Intent intent) {
        // ÔÚÕâÀï¸ÉÄãÏë¸ÉµÄÊ£¨Æô¶¯Ò»¸öService£¬ActivityµÈ£©£¬±¾ÀýÊÇÆô¶¯Ò»¸ö¶¨Ê±µ÷¶È³ÌÐò£¬Ã¿30·ÖÖÓÆô¶¯Ò»¸öServiceÈ¥¸üÐÂÊý¾Ý
        final String action = intent.getAction();
        Log.d("Connection", "Receive broadcast:"+action);
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action))
        {
    		ServerAgent.onConnectionChanged();
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
hot100.py
=========

Generate an [un-icky view][hosted] of the [Billboard Hot 100][hot100] chart. That's it!

    $ python3 hot100.py > hot100.html ; open hot100.html

Yours to do with what you will under the [MIT license][].

[hot100]: http://www.billboard.com/charts/hot-100
[MIT license]: http://opensource.org/licenses/MIT
[hosted]: http://radbox.org/hot100.html


text:
package org.apache.camel.builder.component.dsl;

import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.google.bigquery.GoogleBigQueryComponent;

/**
 * Google BigQuery data warehouse for analytics.
 *
 * Generated by camel-package-maven-plugin - do not edit this file!
 */
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface GoogleBigqueryComponentBuilderFactory {

    /**
     * Google BigQuery (camel-google-bigquery)
     * Google BigQuery data warehouse for analytics.
     *
     * Category: cloud,bigdata
     * Since: 2.20
     * Maven coordinates: org.apache.camel:camel-google-bigquery
     */
    static GoogleBigqueryComponentBuilder googleBigquery() {
        return new GoogleBigqueryComponentBuilderImpl();
    }

    /**
     * Builder for the Google BigQuery component.
     */
    interface GoogleBigqueryComponentBuilder
            extends
                ComponentBuilder<GoogleBigQueryComponent> {
        /**
         * ConnectionFactory to obtain connection to Bigquery Service. If not
         * provided the default one will be used.
         *
         * The option is a:
         * org.apache.camel.component.google.bigquery.GoogleBigQueryConnectionFactory type.
         *
         * Group: producer
         */
        default GoogleBigqueryComponentBuilder connectionFactory(
                org.apache.camel.component.google.bigquery.GoogleBigQueryConnectionFactory connectionFactory) {
            doSetProperty("connectionFactory", connectionFactory);
            return this;
        }
        /**
         * BigQuery Dataset Id.
         *
         * The option is a: java.lang.String type.
         *
         * Group: producer
         */
        default GoogleBigqueryComponentBuilder datasetId(
                java.lang.String datasetId) {
            doSetProperty("datasetId", datasetId);
            return this;
        }
        /**
         * Whether the producer should be started lazy (on the first message).
         * By starting lazy you can use this to allow CamelContext and routes to
         * startup in situations where a producer may otherwise fail during
         * starting and cause the route to fail being started. By deferring this
         * startup to be lazy then the startup failure can be handled during
         * routing messages via Camel's routing error handlers. Beware that when
         * the first message is processed then creating and starting the
         * producer may take a little time and prolong the total processing time
         * of the processing.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: producer
         */
        default GoogleBigqueryComponentBuilder lazyStartProducer(
                boolean lazyStartProducer) {
            doSetProperty("lazyStartProducer", lazyStartProducer);
            return this;
        }
        /**
         * Google Cloud Project Id.
         *
         * The option is a: java.lang.String type.
         *
         * Group: producer
         */
        default GoogleBigqueryComponentBuilder projectId(
                java.lang.String projectId) {
            doSetProperty("projectId", projectId);
            return this;
        }
        /**
         * Whether autowiring is enabled. This is used for automatic autowiring
         * options (the option must be marked as autowired) by looking up in the
         * registry to find if there is a single instance of matching type,
         * which then gets configured on the component. This can be used for
         * automatic configuring JDBC data sources, JMS connection factories,
         * AWS Clients, etc.
         *
         * The option is a: boolean type.
         *
         * Default: true
         * Group: advanced
         */
        default GoogleBigqueryComponentBuilder autowiredEnabled(
                boolean autowiredEnabled) {
            doSetProperty("autowiredEnabled", autowiredEnabled);
            return this;
        }
    }

    class GoogleBigqueryComponentBuilderImpl
            extends
                AbstractComponentBuilder<GoogleBigQueryComponent>
            implements
                GoogleBigqueryComponentBuilder {
        @Override
        protected GoogleBigQueryComponent buildConcreteComponent() {
            return new GoogleBigQueryComponent();
        }
        @Override
        protected boolean setPropertyOnComponent(
                Component component,
                String name,
                Object value) {
            switch (name) {
            case "connectionFactory": ((GoogleBigQueryComponent) component).setConnectionFactory((org.apache.camel.component.google.bigquery.GoogleBigQueryConnectionFactory) value); return true;
            case "datasetId": ((GoogleBigQueryComponent) component).setDatasetId((java.lang.String) value); return true;
            case "lazyStartProducer": ((GoogleBigQueryComponent) component).setLazyStartProducer((boolean) value); return true;
            case "projectId": ((GoogleBigQueryComponent) component).setProjectId((java.lang.String) value); return true;
            case "autowiredEnabled": ((GoogleBigQueryComponent) component).setAutowiredEnabled((boolean) value); return true;
            default: return false;
            }
        }
    }
}


text:
import math
import random

import pyglet
from pyglet import gl

WIDTH = 800
HEIGHT = 600
ROTATION_SPEED = 200
ACCELERATION = 300
SPACESHIP_RADIUS = 40
ASTEROID_SPEED = 100
ASTEROID_ROTATION_SPEED = 3
ASTEROID_RADIUSES = {
    1: 8,
    2: 15,
    3: 20,
    4: 42,
}

def load_image(filename):
    image = pyglet.image.load(filename)
    image.anchor_x = image.width // 2
    image.anchor_y = image.height // 2
    return image

# Images from www.kenney.nl, thank you!
# Public Domain (Creative Commons CC-0)
spaceship_img = load_image('assets/PNG/playerShip2_red.png')
asteroid_images = {
    1: [load_image('assets/PNG/Meteors/meteorGrey_tiny1.png'),
        load_image('assets/PNG/Meteors/meteorGrey_tiny2.png'),
       ],
    2: [load_image('assets/PNG/Meteors/meteorGrey_small1.png'),
        load_image('assets/PNG/Meteors/meteorGrey_small2.png'),
       ],
    3: [load_image('assets/PNG/Meteors/meteorGrey_med1.png'),
        load_image('assets/PNG/Meteors/meteorGrey_med2.png'),
       ],
    4: [load_image('assets/PNG/Meteors/meteorGrey_big1.png'),
        load_image('assets/PNG/Meteors/meteorGrey_big3.png'),
        load_image('assets/PNG/Meteors/meteorGrey_big4.png'),
       ],
}

def circle(x, y, radius):
    iterations = 20
    s = math.sin(2*math.pi / iterations)
    c = math.cos(2*math.pi / iterations)

    dx, dy = radius, 0

    gl.glBegin(gl.GL_LINE_STRIP)
    for i in range(iterations+1):
        gl.glVertex2f(x+dx, y+dy)
        dx, dy = (dx*c - dy*s), (dy*c + dx*s)
    gl.glEnd()

pressed_keys = set()
objects = []
batch = pyglet.graphics.Batch()

class SpaceObject:
    def __init__(self, window, image, x, y, radius, rotation=0, x_speed=0, y_speed=0):
        self.x = x
        self.y = y
        self.x_speed = x_speed
        self.y_speed = y_speed
        self.rotation = rotation
        self.radius = radius
        self.sprite = pyglet.sprite.Sprite(image, batch=batch)
        self.window = window

    def tick(self, dt):
        self.x += dt * self.x_speed
        self.y += dt * self.y_speed

        if self.x < 0:
            self.x += self.window.width
        if self.y < 0:
            self.y += self.window.height
        if self.x > self.window.width:
            self.x -= self.window.width
        if self.y > self.window.height:
            self.y -= self.window.height

        self.sprite.rotation = 90 - self.rotation
        self.sprite.x = self.x
        self.sprite.y = self.y

    def hit_by_spaceship(self, spaceship):
        return

    def delete(self):
        if self in objects:
            objects.remove(self)
            self.sprite.delete()

class Spaceship(SpaceObject):
    def __init__(self, window, rotation=0):
        super().__init__(window=window,
                         image=spaceship_img,
                         x=window.width / 2,
                         y=window.height / 2,
                         rotation=rotation,
                         radius=SPACESHIP_RADIUS,
                        )

    def tick(self, dt):
        if pyglet.window.key.LEFT in pressed_keys:
            self.rotation += dt * ROTATION_SPEED
        if pyglet.window.key.RIGHT in pressed_keys:
            self.rotation -= dt * ROTATION_SPEED
        if pyglet.window.key.UP in pressed_keys:
            rotation_radians = math.radians(self.rotation)
            self.x_speed += dt * ACCELERATION * math.cos(rotation_radians)
            self.y_speed += dt * ACCELERATION * math.sin(rotation_radians)

        super().tick(dt)

        for obj in list(objects):
            if overlaps(self, obj):
                obj.hit_by_spaceship(self)

class Asteroid(SpaceObject):
    def __init__(self, window, size):
        # Asteroids start at edges of the screen, so they don't
        # initially collide with the ship
        edge = random.choice(['horizontal', 'vertical'])
        if edge == 'vertical':
            x = 0
            y = random.randrange(window.height)
        else:
            x = random.randrange(window.width)
            y = 0
        super().__init__(window=window,
                         image=random.choice(asteroid_images[size]),
                         x=x, y=y,
                         x_speed=random.uniform(-ASTEROID_SPEED, ASTEROID_SPEED),
                         y_speed=random.uniform(-ASTEROID_SPEED, ASTEROID_SPEED),
                         rotation=random.uniform(0, 360),
                         radius=ASTEROID_RADIUSES[size],
                        )
        self.size = size
        self.rotation_speed = random.uniform(-ASTEROID_ROTATION_SPEED,
                                             ASTEROID_ROTATION_SPEED)

    def tick(self, dt):
        self.rotation += self.rotation_speed
        super().tick(dt)

    def hit_by_spaceship(self, spaceship):
        spaceship.delete()

def distance(a, b, wrap_size):
    result = abs(a - b)
    if result > wrap_size / 2:
        result = wrap_size - result
    return result

def overlaps(a, b):
    distance_squared = (distance(a.x, b.x, window.width) ** 2 +
                        distance(a.y, b.y, window.height) ** 2)
    max_distance_squared = (a.radius + b.radius) ** 2
    return distance_squared < max_distance_squared

def tick(dt):
    for obj in objects:
        obj.tick(dt)

def draw():
    window.clear()

    for x_offset in (-window.width, 0, window.width):
        for y_offset in (-window.height, 0, window.height):
            gl.glPushMatrix()
            gl.glTranslatef(x_offset, y_offset, 0)
            batch.draw()

            for obj in objects:
                circle(obj.x, obj.y, obj.radius)

            gl.glPopMatrix()

def key_pressed(key, mod):
    pressed_keys.add(key)

def key_released(key, mod):
    pressed_keys.discard(key)

window = pyglet.window.Window(width=WIDTH, height=HEIGHT)

window.push_handlers(
    on_draw=draw,
    on_key_press=key_pressed,
    on_key_release=key_released,
)

pyglet.clock.schedule(tick)

objects.append(Spaceship(window))
for i in range(1):
    objects.append(Asteroid(window, 4))
for i in range(1, 4):
    objects.append(Asteroid(window, i))

pyglet.app.run()


text:
package org.onosproject.evpnrouteservice.store;

import com.google.common.collect.ImmutableSet;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.Service;
import org.onlab.packet.IpAddress;
import org.onlab.util.KryoNamespace;
import org.onosproject.evpnrouteservice.EvpnInternalRouteEvent;
import org.onosproject.evpnrouteservice.EvpnRoute;
import org.onosproject.evpnrouteservice.EvpnRouteSet;
import org.onosproject.evpnrouteservice.EvpnRouteStore;
import org.onosproject.evpnrouteservice.EvpnRouteStoreDelegate;
import org.onosproject.evpnrouteservice.EvpnRouteTableId;
import org.onosproject.evpnrouteservice.EvpnTable;
import org.onosproject.store.AbstractStore;
import org.onosproject.store.service.DistributedSet;
import org.onosproject.store.service.Serializer;
import org.onosproject.store.service.SetEvent;
import org.onosproject.store.service.SetEventListener;
import org.onosproject.store.service.StorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.onlab.util.Tools.groupedThreads;

/**
 * Route store based on distributed storage.
 */
@Service
@Component
public class DistributedEvpnRouteStore extends
        AbstractStore<EvpnInternalRouteEvent,
                EvpnRouteStoreDelegate>
        implements EvpnRouteStore {

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

    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
    public StorageService storageService;

    private static final EvpnRouteTableId EVPN_IPV4 = new EvpnRouteTableId("evpn_ipv4");
    private static final EvpnRouteTableId EVPN_IPV6 = new EvpnRouteTableId("evpn_ipv6");

    private final SetEventListener<EvpnRouteTableId> masterRouteTableListener =
            new MasterRouteTableListener();
    private final EvpnRouteStoreDelegate ourDelegate = new
            InternalEvpnRouteStoreDelegate();

    // Stores the route tables that have been created
    public DistributedSet<EvpnRouteTableId> masterRouteTable;
    // Local memory map to store route table object
    public Map<EvpnRouteTableId, EvpnTable> routeTables;

    private ExecutorService executor;

    /**
     * Sets up distributed route store.
     */
    @Activate
    public void activate() {
        routeTables = new ConcurrentHashMap<>();
        executor = Executors.newSingleThreadExecutor(groupedThreads("onos/route", "store", log));

        KryoNamespace masterRouteTableSerializer = KryoNamespace.newBuilder()
                .register(EvpnRouteTableId.class)
                .build();

        masterRouteTable = storageService.<EvpnRouteTableId>setBuilder()
                .withName("onos-master-route-table")
                .withSerializer(Serializer.using(masterRouteTableSerializer))
                .build()
                .asDistributedSet();

        masterRouteTable.forEach(this::createRouteTable);

        masterRouteTable.addListener(masterRouteTableListener);

        // Add default tables (add is idempotent)
        masterRouteTable.add(EVPN_IPV4);
        masterRouteTable.add(EVPN_IPV6);

        log.info("Started");
    }

    /**
     * Cleans up distributed route store.
     */
    @Deactivate
    public void deactivate() {
        masterRouteTable.removeListener(masterRouteTableListener);

        routeTables.values().forEach(EvpnTable::shutdown);

        log.info("Stopped");
    }

    @Override
    public void updateRoute(EvpnRoute route) {
        getDefaultRouteTable(route).update(route);
    }

    @Override
    public void removeRoute(EvpnRoute route) {
        getDefaultRouteTable(route).remove(route);
    }

    @Override
    public Set<EvpnRouteTableId> getRouteTables() {
        return ImmutableSet.copyOf(masterRouteTable);
    }

    @Override
    public Collection<EvpnRouteSet> getRoutes(EvpnRouteTableId table) {
        EvpnTable routeTable = routeTables.get(table);
        if (routeTable == null) {
            return Collections.emptySet();
        } else {
            return ImmutableSet.copyOf(routeTable.getRoutes());
        }
    }

    @Override
    public Collection<EvpnRoute> getRoutesForNextHop(IpAddress ip) {
        return getDefaultRouteTable(ip).getRoutesForNextHop(ip);
    }

    private void createRouteTable(EvpnRouteTableId tableId) {
        routeTables.computeIfAbsent(tableId, id -> new EvpnRouteTable(id,
                                                                      ourDelegate, storageService, executor));
    }

    private void destroyRouteTable(EvpnRouteTableId tableId) {
        EvpnTable table = routeTables.remove(tableId);
        if (table != null) {
            table.destroy();
        }
    }

    private EvpnTable getDefaultRouteTable(EvpnRoute route) {
        return getDefaultRouteTable(route.prefixIp().address());
    }

    private EvpnTable getDefaultRouteTable(IpAddress ip) {
        EvpnRouteTableId routeTableId = (ip.isIp4()) ? EVPN_IPV4 : EVPN_IPV6;
        return routeTables.getOrDefault(routeTableId, EmptyEvpnRouteTable
                .instance());
    }

    private class InternalEvpnRouteStoreDelegate implements
            EvpnRouteStoreDelegate {
        @Override
        public void notify(EvpnInternalRouteEvent event) {
            executor.execute(() -> DistributedEvpnRouteStore
                    .this.notifyDelegate(event));
        }
    }

    private class MasterRouteTableListener implements SetEventListener<EvpnRouteTableId> {
        @Override
        public void event(SetEvent<EvpnRouteTableId> event) {
            switch (event.type()) {
                case ADD:
                    executor.execute(() -> createRouteTable(event.entry()));
                    break;
                case REMOVE:
                    executor.execute(() -> destroyRouteTable(event.entry()));
                    break;
                default:
                    break;
            }
        }
    }
}


text:
package io.github.greyp9.arwo.app.ssh.sftp.handler;

import io.github.greyp9.arwo.app.core.state.AppUserState;
import io.github.greyp9.arwo.app.ssh.connection.SSHConnectionFactory;
import io.github.greyp9.arwo.app.ssh.connection.SSHConnectionResource;
import io.github.greyp9.arwo.app.ssh.sftp.core.SFTPRequest;
import io.github.greyp9.arwo.app.ssh.sftp.data.SFTPDataSource;
import io.github.greyp9.arwo.core.alert.Alert;
import io.github.greyp9.arwo.core.alert.Alerts;
import io.github.greyp9.arwo.core.app.App;
import io.github.greyp9.arwo.core.bundle.Bundle;
import io.github.greyp9.arwo.core.codec.hex.HexCodec;
import io.github.greyp9.arwo.core.file.FileX;
import io.github.greyp9.arwo.core.hash.secure.HashU;
import io.github.greyp9.arwo.core.http.form.MimeHeader;
import io.github.greyp9.arwo.core.http.form.MimePart;
import io.github.greyp9.arwo.core.http.form.MultipartForm;
import io.github.greyp9.arwo.core.http.servlet.ServletHttpRequest;
import io.github.greyp9.arwo.core.value.Value;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;

public class SFTPHandlerPostMultipart {
    private final SFTPRequest request;
    private final ServletHttpRequest httpRequest;
    private final AppUserState userState;
    private final Bundle bundle;
    private final Alerts alerts;

    public SFTPHandlerPostMultipart(final SFTPRequest request, final AppUserState userState) {
        this.request = request;
        this.httpRequest = request.getHttpRequest();
        this.userState = userState;
        this.bundle = request.getBundle();
        this.alerts = request.getAlerts();
    }

    @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
    public final String doPostMultipartFormData(final String location) throws IOException {
        final ByteArrayInputStream is = httpRequest.getHttpRequest().getEntity();
        final MultipartForm form = new MultipartForm(is);
        for (final Iterator<MimePart> mimePartIt = form.iterator(); mimePartIt.hasNext(); mimePartIt.getClass()) {
            final MimePart mimePart = mimePartIt.next();
            final Properties propertiesPart = new Properties();
            for (final Iterator<MimeHeader> headerIt = mimePart.iterator(); headerIt.hasNext(); headerIt.getClass()) {
                final MimeHeader mimeHeader = headerIt.next();
                mimeHeader.addTo(propertiesPart);
            }
            final String name = propertiesPart.getProperty(App.Post.CD_NAME);
            if (App.Post.UPLOAD_FILE.equals(name)) {
                doPostUploadFile(mimePart, propertiesPart);
            }
        }
        return location;
    }

    private void doPostUploadFile(final MimePart mimePart, final Properties properties) throws IOException {
        final String server = request.getServer();
        final String filename = properties.getProperty(App.Post.CD_FILENAME);
        final SSHConnectionFactory factory = new SSHConnectionFactory(httpRequest, userState, bundle, alerts);
        final SSHConnectionResource resource = (SSHConnectionResource)
                userState.getSSH().getCache().getResource(server, factory);
        if (resource == null) {
            alerts.add(new Alert(Alert.Severity.WARN, bundle.format("SFTPHandlerPostMultipart.no.connect", server)));
        } else if (filename.length() == 0) {
            alerts.add(new Alert(Alert.Severity.WARN, bundle.format("SFTPHandlerPostMultipart.no.file", server)));
        } else {
            doPostUploadFile(mimePart, filename, resource);
            resource.getConnection().update(httpRequest.getDate());
        }
    }

    private void doPostUploadFile(
            final MimePart mimePart, final String filename, final SSHConnectionResource resource) throws IOException {
        final byte[] bytes = mimePart.getBody().toByteArray();
        alerts.add(new Alert(Alert.Severity.INFO, bundle.format(
                "SFTPHandlerPostMultipart.file.source", filename)));
        // put data to remote
        final FileX fileX = new FileX(Value.join("", request.getPath(), filename));
        final SFTPDataSource source = new SFTPDataSource(request, resource.getConnection());
        source.write(bytes, fileX.getFolder(), fileX.getFilename(), null);
        // info alert
        final String hash = HexCodec.encode(HashU.md5(bytes));
        alerts.add(new Alert(Alert.Severity.INFO, bundle.format(
                "SFTPHandlerPostMultipart.file.target", fileX.getFolderSlash(), bytes.length, hash)));
    }
}


text:
using System;
using Drumble.DomainDrivenArchitecture.Domain.EntityFramework;
using Drumble.DomainDrivenArchitecture.Domain.Interfaces;

namespace Drumble.DomainDrivenArchitecture.Infrastructure.EntityFramework
{
    public sealed class EntityFrameworkUnitOfWork<TContext> : IUnitOfWork
        where TContext : EntityFrameworkContext
    {
        public IContext Context
        {
            get
            {
                var context = Activator.CreateInstance<TContext>();
                context.Configuration.AutoDetectChangesEnabled = false;
                context.Configuration.LazyLoadingEnabled = false;

                return context;
            }
        }

        public EntityFrameworkUnitOfWork()
        {
        }
    }
}


text:
using content::BrowserThread;

namespace {

// Caller takes ownership of the returned dictionary.
DictionaryValue* ExtractPrefs(const FilePath& path,
                              base::ValueSerializer* serializer) {
  std::string error_msg;
  Value* extensions = serializer->Deserialize(NULL, &error_msg);
  if (!extensions) {
    LOG(WARNING) << "Unable to deserialize json data: " << error_msg
                 << " In file " << path.value() << " .";
  } else {
    if (!extensions->IsType(Value::TYPE_DICTIONARY)) {
      LOG(WARNING) << "Expected a JSON dictionary in file "
                   << path.value() << " .";
    } else {
      return static_cast<DictionaryValue*>(extensions);
    }
  }
  return new DictionaryValue;
}

}  // namespace

ExternalPrefExtensionLoader::ExternalPrefExtensionLoader(int base_path_key,
                                                         Options options)
    : base_path_key_(base_path_key),
      options_(options){
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

const FilePath ExternalPrefExtensionLoader::GetBaseCrxFilePath() {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // |base_path_| was set in LoadOnFileThread().
  return base_path_;
}

void ExternalPrefExtensionLoader::StartLoading() {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  BrowserThread::PostTask(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(&ExternalPrefExtensionLoader::LoadOnFileThread, this));
}

DictionaryValue* ExternalPrefExtensionLoader::ReadJsonPrefsFile() {
  // TODO(skerner): Some values of base_path_key_ will cause
  // PathService::Get() to return false, because the path does
  // not exist.  Find and fix the build/install scripts so that
  // this can become a CHECK().  Known examples include chrome
  // OS developer builds and linux install packages.
  // Tracked as crbug.com/70402 .
  if (!PathService::Get(base_path_key_, &base_path_)) {
    return NULL;
  }

  FilePath json_file = base_path_.Append(
      FILE_PATH_LITERAL("external_extensions.json"));

  if (!file_util::PathExists(json_file)) {
    // This is not an error.  The file does not exist by default.
    return NULL;
  }

  if (IsOptionSet(ENSURE_PATH_CONTROLLED_BY_ADMIN)) {
#if defined(OS_MACOSX)
    if (!file_util::VerifyPathControlledByAdmin(json_file)) {
      LOG(ERROR) << "Can not read external extensions source.  The file "
                 << json_file.value() << " and every directory in its path, "
                 << "must be owned by root, have group \"admin\", and not be "
                 << "writable by all users. These restrictions prevent "
                 << "unprivleged users from making chrome install extensions "
                 << "on other users' accounts.";
      return NULL;
    }
#else
    // The only platform that uses this check is Mac OS.  If you add one,
    // you need to implement file_util::VerifyPathControlledByAdmin() for
    // that platform.
    NOTREACHED();
#endif  // defined(OS_MACOSX)
  }

  JSONFileValueSerializer serializer(json_file);
  DictionaryValue* parsed_json_prefs = ExtractPrefs(json_file, &serializer);

#if defined(OS_MACOSX)
  if (base_path_key_ == chrome::DIR_DEPRECATED_EXTERNAL_EXTENSIONS &&
      parsed_json_prefs->size() > 0) {
    LOG(WARNING) << "Deprecated external extension source " << json_file.value()
                 << " is used to install some CRX files.  This source will be "
                 << "removed in version 19.  See http://code.google.com/chrome"
                 << "/extensions/external_extensions.html#preferences for "
                 << "documentation of other supported paths.";

    for (DictionaryValue::key_iterator crx_id = parsed_json_prefs->begin_keys();
         crx_id != parsed_json_prefs->end_keys(); ++crx_id) {
      LOG(WARNING) << "External CRX install for ID " << *crx_id
                   << " is from a deprecated source.";
    }
  }
#endif  // defined(OS_MACOSX)

  return parsed_json_prefs;
}

void ExternalPrefExtensionLoader::LoadOnFileThread() {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));

  prefs_.reset(ReadJsonPrefsFile());
  if (!prefs_.get())
    prefs_.reset(new DictionaryValue());

  // We want to deprecate the external extensions file inside the app
  // bundle on mac os.  Use a histogram to see how many extensions
  // are installed using the deprecated path, and how many are installed
  // from the supported path.  We can use this data to measure the
  // effectiveness of asking developers to use the new path, or any
  // automatic migration methods we implement.
#if defined(OS_MACOSX)
  // The deprecated path only exists on mac for now.
  if (base_path_key_ == chrome::DIR_DEPRECATED_EXTERNAL_EXTENSIONS) {
    UMA_HISTOGRAM_COUNTS_100("Extensions.DepricatedExternalJsonCount",
                             prefs_->size());
  }
#endif  // defined(OS_MACOSX)
  if (base_path_key_ == chrome::DIR_EXTERNAL_EXTENSIONS) {
    UMA_HISTOGRAM_COUNTS_100("Extensions.ExternalJsonCount",
                             prefs_->size());
  }

  // If we have any records to process, then we must have
  // read the .json file.  If we read the .json file, then
  // we were should have set |base_path_|.
  if (!prefs_->empty())
    CHECK(!base_path_.empty());

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(&ExternalPrefExtensionLoader::LoadFinished, this));
}

ExternalTestingExtensionLoader::ExternalTestingExtensionLoader(
    const std::string& json_data,
    const FilePath& fake_base_path)
    : fake_base_path_(fake_base_path) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  JSONStringValueSerializer serializer(json_data);
  FilePath fake_json_path = fake_base_path.AppendASCII("fake.json");
  testing_prefs_.reset(ExtractPrefs(fake_json_path, &serializer));
}

void ExternalTestingExtensionLoader::StartLoading() {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  prefs_.reset(testing_prefs_->DeepCopy());
  LoadFinished();
}

ExternalTestingExtensionLoader::~ExternalTestingExtensionLoader() {}

const FilePath ExternalTestingExtensionLoader::GetBaseCrxFilePath() {
  return fake_base_path_;
}


text:
import React from 'react';
import ReactDOM from 'react-dom';

import JqxLoader from '../../../jqwidgets-react/react_jqxloader.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';

class App extends React.Component {
    componentDidMount() {
        this.refs.openLoader.on('click', () => {
            this.refs.myLoader.open();
        });
    }
    render() {
        return (
            <div>
                <JqxLoader ref='myLoader' style={{ marginTop: 230 }}
                    width={100} height={60}
                    imagePosition={'top'} isModal={true}
                />
                <JqxButton ref='openLoader'
                    value='Open Loader' width={150} height={25}
                />
            </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('app'));


text:
template<class T>
class TClass : public IClass
{
public:
	virtual const char* name() const override { return Class<T>::name(); }
	virtual const type_info& type() const override { return Class<T>::type(); }
	virtual int memberCount() const override { return Class<T>::member_count; }
	virtual const IMember* members() const override { return Class<T>::members(); }
};


text:
or

## How to improve developers workflow

By [Bart Tomzynski](http://tomzynski.com)

Built using amazing [reveal.js](http://lab.hakim.se/reveal-js/#/).


text:
<ion-header-bar class="bar-balanced">

{{'content_lable' | translate}} : {{productInfo.product}}

              EN
              ES

      </ion-header-bar>

{{'tapOnInfo_lable' | translate}}

<ion-content class="padding has-subheader">
    <ion-list>
        <ion-item class="item item-icon-right" href="#/productInfoInfo/{{productName}}">
            {{'productInfo_lable' | translate}}

        </ion-item>
        <ion-item class="item item-icon-right" href="#/productInfoProducer/{{productName}}">
            {{'producerInfo_lable' | translate}}

        </ion-item>
        <ion-item class="item item-icon-right" href="#/productInfoFirstAid/{{productName}}">
            {{'firstAid_lable' | translate}}

        </ion-item>
        <ion-item class="item item-icon-right" href="#/productInfoHealth/{{productName}}">
            {{'healthInfo_lable' | translate}}

        </ion-item>
        <ion-item class="item item-icon-right" href="#/productInfoProtectiveClothing/{{productName}}">
            {{'protectiveClothing_lable' | translate}}

        </ion-item>
        <ion-item class="item item-icon-right" href="#/productInfoEngControl/{{productName}}">
            {{'engineeringControls_lable' | translate}}

        </ion-item>
        <ion-item class="item item-icon-right" href="#/productInfoChemicalHazards/{{productName}}">
            {{'chemicalHazards_lable' | translate}}

        </ion-item>
        <ion-item class="item item-icon-right" href="#/productInfoStorage/{{productName}}">
            {{'storage_lable' | translate}}

        </ion-item>
        <ion-item class="item item-icon-right" href="#/productInfoSafelyInfo/{{productName}}">
            {{'safelyInfo_lable' | translate}}

        </ion-item>
        <ion-item class="item item-icon-right" href="#/productInfoCredits/{{productName}}">
            {{'creditsAndLinks_lable' | translate}}

        </ion-item>
    </ion-list>
</ion-content>
<ion-footer-bar class="bar-balanced">

            {{'newSearch_lable'|translate}}

</ion-footer-bar>

{{'footerInfo' | translate}}


text:
 angular.module('MicroGerApp')
     .controller('PedidoController', function($scope, $http) {

     });


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Gtk;
using Pinta.Core;

namespace Pinta.Gui.Widgets
{
	public class LayersListWidget : ScrolledWindow
	{
		private TreeView tree;
		private TreeStore store;
		private Document? active_document;
		private bool updating_model;

		// For the active layer, we also draw the selection layer on top of it,
		// so we can't directly use that layer's surface.
		private Cairo.ImageSurface? active_layer_surface;
		private readonly CanvasRenderer canvas_renderer = new CanvasRenderer (false, false);

		private const int store_index_thumbnail = 0;
		private const int store_index_name = 1;
		private const int store_index_visibility = 2;
		private const int store_index_layer = 3;

		private const int thumbnail_width = 60;
		private const int thumbnail_height = 40;
		private const int thumbnail_column_width = 70;

		private const int name_column_min_width = 100;
		private const int name_column_max_width = 300;

		private const int visibility_column_width = 30;

		public LayersListWidget ()
		{
			Build ();

			PintaCore.Workspace.ActiveDocumentChanged += Workspace_ActiveDocumentChanged;

			tree.CursorChanged += HandleLayerSelected;
		}

		private UserLayer? GetSelectedLayerInTreeView () => tree.GetSelectedValueAt<UserLayer> (store_index_layer);

		private void SelectLayerInTreeView (int layerIndex) => tree.SetSelectedRows (layerIndex);

		[MemberNotNull (nameof (tree), nameof (store))]
		private void Build ()
		{
			CanFocus = false;
			SetSizeRequest (200, 200);

			SetPolicy (PolicyType.Automatic, PolicyType.Automatic);

			// Create tree
			tree = new TreeView {
				HeadersVisible = false,
				FixedHeightMode = true,
				Reorderable = false,
				EnableGridLines = TreeViewGridLines.None,
				EnableTreeLines = false,
				ShowExpanders = false,
				CanFocus = false
			};

			// Create Thumbnail column
			var crs = new CellRendererSurface (thumbnail_width, thumbnail_height);

			var col = new TreeViewColumn ("Thumbnail", crs, "surface", store_index_thumbnail) {
				Sizing = TreeViewColumnSizing.Fixed,
				FixedWidth = thumbnail_column_width
			};

			tree.AppendColumn (col);

			// Create text column
			var textCell = new CellRendererText {
				Ellipsize = Pango.EllipsizeMode.End
			};

			col = new TreeViewColumn ("Name", textCell, "text", store_index_name) {
				Sizing = TreeViewColumnSizing.Fixed,
				Expand = true,
				MinWidth = name_column_min_width,
				MaxWidth = name_column_max_width
			};

			tree.AppendColumn (col);

			// Create visible checkbox toggle
			var crt = new CellRendererToggle {
				Activatable = true
			};

			crt.Toggled += LayerVisibilityToggled;

			col = new TreeViewColumn ("Visible", crt, "active", store_index_visibility) {
				Sizing = TreeViewColumnSizing.Fixed,
				FixedWidth = visibility_column_width
			};

			tree.AppendColumn (col);

			store = new TreeStore (typeof (Cairo.ImageSurface), typeof (string), typeof (bool), typeof (Layer));

			tree.Model = store;
			tree.RowActivated += HandleRowActivated;

			Add (tree);

			ShowAll ();
		}

		private void HandleLayerSelected (object? o, EventArgs e)
		{
			if (updating_model)
				return;

			// This handler is triggered via Reset() when the tree is cleared.
			// So, if the selection was reset we should exit early, since there might not be
			// an active document or the document might not have any layers yet.
			// Otherwise, if the selection is non-empty there should be an open document with layers.
			var layer = GetSelectedLayerInTreeView ();
			if (layer is null)
				return;

			updating_model = true;

			var doc = PintaCore.Workspace.ActiveDocument;
			if (doc.Layers.CurrentUserLayer != layer)
				doc.Layers.SetCurrentUserLayer (layer);

			updating_model = false;
		}

		private void LayerVisibilityToggled (object? o, ToggledArgs args)
		{
			if (updating_model)
				return;

			updating_model = true;

			var visible = tree.GetValueAt<object> (args.Path, store_index_visibility);
			var layer = tree.GetValueAt<UserLayer> (args.Path, store_index_layer);

			if (visible is bool b && layer is not null)
				SetLayerVisibility (layer, !b);

			updating_model = false;
		}

		private void HandleHistoryItemAdded (object? sender, EventArgs e)
		{
			// TODO: Handle this more efficiently.
			Reset ();
		}

		private void HandleSelectedLayerChanged (object? sender, EventArgs e)
		{
			// TODO: Handle this more efficiently.
			Reset ();
		}

		void HandlePintaCoreLayersLayerPropertyChanged (object? sender, PropertyChangedEventArgs e)
		{
			// TODO: Handle this more efficiently.
			Reset ();
		}

		private void HandleLayerAddedOrRemoved (object? sender, EventArgs e)
		{
			// TODO: Handle this more efficiently.
			Reset ();

			// TODO: this should be handled elsewhere
			PintaCore.Workspace.Invalidate ();
		}

		private void HandleRowActivated (object? o, RowActivatedArgs args)
		{
			// The double click to activate will have already selected the layer.
			PintaCore.Actions.Layers.Properties.Activate ();
		}

		private void Workspace_ActiveDocumentChanged (object? sender, EventArgs e)
		{
			var doc = PintaCore.Workspace.HasOpenDocuments ? PintaCore.Workspace.ActiveDocument : null;

			if (active_document == doc)
				return;

			if (active_document != null) {
				active_document.History.HistoryItemAdded -= HandleHistoryItemAdded;
				active_document.History.ActionUndone -= HandleHistoryItemAdded;
				active_document.History.ActionRedone -= HandleHistoryItemAdded;
				active_document.Layers.LayerAdded -= HandleLayerAddedOrRemoved;
				active_document.Layers.LayerRemoved -= HandleLayerAddedOrRemoved;
				active_document.Layers.SelectedLayerChanged -= HandleSelectedLayerChanged;
				active_document.Layers.LayerPropertyChanged -= HandlePintaCoreLayersLayerPropertyChanged;
			}

			if (doc is not null) {
				doc.History.HistoryItemAdded += HandleHistoryItemAdded;
				doc.History.ActionUndone += HandleHistoryItemAdded;
				doc.History.ActionRedone += HandleHistoryItemAdded;
				doc.Layers.LayerAdded += HandleLayerAddedOrRemoved;
				doc.Layers.LayerRemoved += HandleLayerAddedOrRemoved;
				doc.Layers.SelectedLayerChanged += HandleSelectedLayerChanged;
				doc.Layers.LayerPropertyChanged += HandlePintaCoreLayersLayerPropertyChanged;
			}

			active_document = doc;

			Reset ();
		}

		private void Reset ()
		{
			updating_model = true;
			store.Clear ();
			updating_model = false;

			if (active_layer_surface != null) {
				(active_layer_surface as IDisposable).Dispose ();
				active_layer_surface = null;
			}

			if (!PintaCore.Workspace.HasOpenDocuments)
				return;

			var doc = PintaCore.Workspace.ActiveDocument;

			foreach (var layer in doc.Layers.UserLayers.Reverse ()) {
				var surf = layer.Surface;

				// If this is the currently selected layer, we may need to draw the
				// selection layer over it, like when dragging a selection.
				if (layer == doc.Layers.CurrentUserLayer && doc.Layers.ShowSelectionLayer) {
					active_layer_surface = CairoExtensions.CreateImageSurface (Cairo.Format.Argb32, thumbnail_width, thumbnail_height);
					canvas_renderer.Initialize (doc.ImageSize, new Gdk.Size (thumbnail_width, thumbnail_height));

					var layers = new List<Layer> { layer, doc.Layers.SelectionLayer };
					canvas_renderer.Render (layers, active_layer_surface, Gdk.Point.Zero);

					surf = active_layer_surface;
				}

				store.AppendValues (surf, layer.Name, !layer.Hidden, layer);
			}

			SelectLayerInTreeView (doc.Layers.Count () - doc.Layers.CurrentUserLayerIndex - 1);
		}

		private void SetLayerVisibility (UserLayer layer, bool visibility)
		{
			var doc = PintaCore.Workspace.ActiveDocument;

			var initial = new LayerProperties (layer.Name, visibility, layer.Opacity, layer.BlendMode);
			var updated = new LayerProperties (layer.Name, !visibility, layer.Opacity, layer.BlendMode);

			var historyItem = new UpdateLayerPropertiesHistoryItem (
				Resources.Icons.LayerProperties,
				(visibility) ? Translations.GetString ("Layer Shown") : Translations.GetString ("Layer Hidden"),
				doc.Layers.IndexOf (layer),
				initial,
				updated);
			historyItem.Redo ();

			doc.History.PushNewItem (historyItem);
		}
	}
}


text:
package com.intellij.diff.comparison;

import com.intellij.diff.util.IntPair;
import com.intellij.diff.util.MergeRange;
import com.intellij.diff.util.Range;
import org.jetbrains.annotations.NotNull;

import java.util.List;

import static com.intellij.openapi.util.text.StringUtil.isWhiteSpace;

@SuppressWarnings({"Duplicates", "unused", "TypeParameterExplicitlyExtendsObject"})
public class TrimUtil {
  public static boolean isPunctuation(char c) {
    if (c == '_') return false;
    boolean isPunctuation = false;
    isPunctuation |= c >= 33 & c <= 47; // !"#$%&'()*+,-./
    isPunctuation |= c >= 58 & c <= 64; // :;<=>?@
    isPunctuation |= c >= 91 & c <= 96; // [\]^_`
    isPunctuation |= c >= 123 & c <= 126; // {|}~
    return isPunctuation;
  }

  public static boolean isAlpha(char c) {
    return !isWhiteSpace(c) && !isPunctuation(c);
  }

  //
  // Trim
  //

  @NotNull
  public static Range trim(@NotNull CharSequence text1, @NotNull CharSequence text2,
                           int start1, int start2, int end1, int end2) {
    start1 = trimStart(text1, start1, end1);
    end1 = trimEnd(text1, start1, end1);
    start2 = trimStart(text2, start2, end2);
    end2 = trimEnd(text2, start2, end2);

    return new Range(start1, end1, start2, end2);
  }

  @NotNull
  public static MergeRange trim(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull CharSequence text3,
                                      int start1, int start2, int start3, int end1, int end2, int end3) {
    start1 = trimStart(text1, start1, end1);
    end1 = trimEnd(text1, start1, end1);
    start2 = trimStart(text2, start2, end2);
    end2 = trimEnd(text2, start2, end2);
    start3 = trimStart(text3, start3, end3);
    end3 = trimEnd(text3, start3, end3);

    return new MergeRange(start1, end1, start2, end2, start3, end3);
  }

  @NotNull
  public static IntPair trim(@NotNull CharSequence text, int start, int end) {
    start = trimStart(text, start, end);
    end = trimEnd(text, start, end);

    return new IntPair(start, end);
  }

  public static int trimStart(@NotNull CharSequence text, int start, int end) {
    while (start < end) {
      char c = text.charAt(start);
      if (!isWhiteSpace(c)) break;
      start++;
    }
    return start;
  }

  public static int trimEnd(@NotNull CharSequence text, int start, int end) {
    while (start < end) {
      char c = text.charAt(end - 1);
      if (!isWhiteSpace(c)) break;
      end--;
    }
    return end;
  }

  //
  // Expand
  //

  @NotNull
  public static Range expand(@NotNull List<?> text1, @NotNull List<?> text2,
                             int start1, int start2, int end1, int end2) {
    int count1 = expandForward(text1, text2, start1, start2, end1, end2);
    start1 += count1;
    start2 += count1;

    int count2 = expandBackward(text1, text2, start1, start2, end1, end2);
    end1 -= count2;
    end2 -= count2;

    return new Range(start1, end1, start2, end2);
  }

  @NotNull
  public static Range expand(@NotNull CharSequence text1, @NotNull CharSequence text2,
                             int start1, int start2, int end1, int end2) {
    int count1 = expandForward(text1, text2, start1, start2, end1, end2);
    start1 += count1;
    start2 += count1;

    int count2 = expandBackward(text1, text2, start1, start2, end1, end2);
    end1 -= count2;
    end2 -= count2;

    return new Range(start1, end1, start2, end2);
  }

  @NotNull
  public static Range expandW(@NotNull CharSequence text1, @NotNull CharSequence text2,
                              int start1, int start2, int end1, int end2) {
    int count1 = expandForwardW(text1, text2, start1, start2, end1, end2);
    start1 += count1;
    start2 += count1;

    int count2 = expandBackwardW(text1, text2, start1, start2, end1, end2);
    end1 -= count2;
    end2 -= count2;

    return new Range(start1, end1, start2, end2);
  }

  @NotNull
  public static MergeRange expandW(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull CharSequence text3,
                                   int start1, int start2, int start3, int end1, int end2, int end3) {
    int count1 = expandForwardW(text1, text2, text3, start1, start2, start3, end1, end2, end3);
    start1 += count1;
    start2 += count1;
    start3 += count1;

    int count2 = expandBackwardW(text1, text2, text3, start1, start2, start3, end1, end2, end3);
    end1 -= count2;
    end2 -= count2;
    end3 -= count2;

    return new MergeRange(start1, end1, start2, end2, start3, end3);
  }

  public static int expandForward(@NotNull CharSequence text1, @NotNull CharSequence text2,
                                  int start1, int start2, int end1, int end2) {
    int oldStart1 = start1;
    while (start1 < end1 && start2 < end2) {
      char c1 = text1.charAt(start1);
      char c2 = text2.charAt(start2);
      if (c1 != c2) break;
      start1++;
      start2++;
    }

    return start1 - oldStart1;
  }

  public static int expandForward(@NotNull List<?> text1, @NotNull List<?> text2,
                                  int start1, int start2, int end1, int end2) {
    int oldStart1 = start1;
    while (start1 < end1 && start2 < end2) {
      Object c1 = text1.get(start1);
      Object c2 = text2.get(start2);
      if (!c1.equals(c2)) break;
      start1++;
      start2++;
    }

    return start1 - oldStart1;
  }

  public static int expandForwardW(@NotNull CharSequence text1, @NotNull CharSequence text2,
                                   int start1, int start2, int end1, int end2) {
    int oldStart1 = start1;
    while (start1 < end1 && start2 < end2) {
      char c1 = text1.charAt(start1);
      char c2 = text2.charAt(start2);
      if (c1 != c2 || !isWhiteSpace(c1)) break;
      start1++;
      start2++;
    }

    return start1 - oldStart1;
  }

  public static int expandBackward(@NotNull CharSequence text1, @NotNull CharSequence text2,
                                   int start1, int start2, int end1, int end2) {
    int oldEnd1 = end1;
    while (start1 < end1 && start2 < end2) {
      char c1 = text1.charAt(end1 - 1);
      char c2 = text2.charAt(end2 - 1);
      if (c1 != c2) break;
      end1--;
      end2--;
    }

    return oldEnd1 - end1;
  }

  public static int expandBackward(@NotNull List<?> text1, @NotNull List<?> text2,
                                   int start1, int start2, int end1, int end2) {
    int oldEnd1 = end1;
    while (start1 < end1 && start2 < end2) {
      Object c1 = text1.get(end1 - 1);
      Object c2 = text2.get(end2 - 1);
      if (!c1.equals(c2)) break;
      end1--;
      end2--;
    }

    return oldEnd1 - end1;
  }

  public static int expandBackwardW(@NotNull CharSequence text1, @NotNull CharSequence text2,
                                    int start1, int start2, int end1, int end2) {
    int oldEnd1 = end1;
    while (start1 < end1 && start2 < end2) {
      char c1 = text1.charAt(end1 - 1);
      char c2 = text2.charAt(end2 - 1);
      if (c1 != c2 || !isWhiteSpace(c1)) break;
      end1--;
      end2--;
    }

    return oldEnd1 - end1;
  }

  public static int expandForwardW(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull CharSequence text3,
                                   int start1, int start2, int start3, int end1, int end2, int end3) {
    int oldStart1 = start1;
    while (start1 < end1 && start2 < end2 && start3 < end3) {
      char c1 = text1.charAt(start1);
      char c2 = text2.charAt(start2);
      char c3 = text3.charAt(start3);
      if (c1 != c2 || c1 != c3 || !isWhiteSpace(c1)) break;
      start1++;
      start2++;
      start3++;
    }

    return start1 - oldStart1;
  }

  public static int expandBackwardW(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull CharSequence text3,
                                    int start1, int start2, int start3, int end1, int end2, int end3) {
    int oldEnd1 = end1;
    while (start1 < end1 && start2 < end2 && start3 < end3) {
      char c1 = text1.charAt(end1 - 1);
      char c2 = text2.charAt(end2 - 1);
      char c3 = text3.charAt(end3 - 1);
      if (c1 != c2 || c1 != c3|| !isWhiteSpace(c1)) break;
      end1--;
      end2--;
      end3--;
    }

    return oldEnd1 - end1;
  }

  @NotNull
  public static IntPair expandForwardIW(@NotNull CharSequence text1, @NotNull CharSequence text2,
                                        int start1, int start2, int end1, int end2) {
    while (start1 < end1 && start2 < end2) {
      char c1 = text1.charAt(start1);
      char c2 = text2.charAt(start2);

      if (c1 == c2) {
        start1++;
        start2++;
        continue;
      }

      boolean skipped = false;
      if (isWhiteSpace(c1)) {
        skipped = true;
        start1++;
      }
      if (isWhiteSpace(c2)) {
        skipped = true;
        start2++;
      }
      if (!skipped) break;
    }

    start1 = trimStart(text1, start1, end1);
    start2 = trimStart(text2, start2, end2);

    return new IntPair(start1, start2);
  }

  @NotNull
  public static IntPair expandBackwardIW(@NotNull CharSequence text1, @NotNull CharSequence text2,
                                         int start1, int start2, int end1, int end2) {
    while (start1 < end1 && start2 < end2) {
      char c1 = text1.charAt(end1 - 1);
      char c2 = text2.charAt(end2 - 1);

      if (c1 == c2) {
        end1--;
        end2--;
        continue;
      }

      boolean skipped = false;
      if (isWhiteSpace(c1)) {
        skipped = true;
        end1--;
      }
      if (isWhiteSpace(c2)) {
        skipped = true;
        end2--;
      }
      if (!skipped) break;
    }

    end1 = trimEnd(text1, start1, end1);
    end2 = trimEnd(text2, start2, end2);

    return new IntPair(end1, end2);
  }

  @NotNull
  public static Range expandIW(@NotNull CharSequence text1, @NotNull CharSequence text2,
                               int start1, int start2, int end1, int end2) {
    IntPair start = expandForwardIW(text1, text2, start1, start2, end1, end2);
    start1 = start.val1;
    start2 = start.val2;

    IntPair end = expandBackwardIW(text1, text2, start1, start2, end1, end2);
    end1 = end.val1;
    end2 = end.val2;

    return new Range(start1, end1, start2, end2);
  }

  //
  // Misc
  //

  @NotNull
  public static Range expand(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull Range range) {
    return expand(text1, text2, range.start1, range.start2, range.end1, range.end2);
  }

  @NotNull
  public static Range expandW(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull Range range) {
    return expandW(text1, text2, range.start1, range.start2, range.end1, range.end2);
  }

  @NotNull
  public static Range trim(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull Range range) {
    return trim(text1, text2, range.start1, range.start2, range.end1, range.end2);
  }

  @NotNull
  public static MergeRange trim(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull CharSequence text3,
                                @NotNull MergeRange range) {
    return trim(text1, text2, text3, range.start1, range.start2, range.start3, range.end1, range.end2, range.end3);
  }

  @NotNull
  public static MergeRange expandW(@NotNull CharSequence text1, @NotNull CharSequence text2, @NotNull CharSequence text3,
                                   @NotNull MergeRange range) {
    return expandW(text1, text2, text3, range.start1, range.start2, range.start3, range.end1, range.end2, range.end3);
  }

  @NotNull
  public static Range expandIW(@NotNull CharSequence text1, @NotNull CharSequence text2) {
    return expandIW(text1, text2, 0, 0, text1.length(), text2.length());
  }
}