text:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using System;
using System.IO;
using System.Threading;
using System.Xml.Linq;
using System.Xml.XPath;
using Wexflow.Core;

namespace Wexflow.Tasks.YouTube
{
    internal enum PrivacyStatus
    {
        Unlisted,
        Private,
        Public
    }

    public class YouTube : Task
    {
        public string User { get; }
        public string ApplicationName { get; }
        public string ClientSecrets { get; }

        public YouTube(XElement xe, Workflow wf)
            : base(xe, wf)
        {
            User = GetSetting("user");
            ApplicationName = GetSetting("applicationName");
            ClientSecrets = GetSetting("clientSecrets");
        }

        public override TaskStatus Run()
        {
            Info("Uploading videos...");

            bool succeeded = true;
            bool atLeastOneSucceed = false;

            try
            {
                var files = SelectFiles();

                foreach (var file in files)
                {
                    try
                    {
                        XDocument xdoc = XDocument.Load(file.Path);

                        foreach (var xvideo in xdoc.XPathSelectElements("/Videos/Video"))
                        {
                            string title = xvideo.Element("Title").Value;
                            string desc = xvideo.Element("Description").Value;
                            string[] tags = xvideo.Element("Tags").Value.Split(',');
                            string categoryId = xvideo.Element("CategoryId").Value;
                            PrivacyStatus ps = (PrivacyStatus)Enum.Parse(typeof(PrivacyStatus), xvideo.Element("PrivacyStatus").Value, true);
                            string filePath = xvideo.Element("FilePath").Value;

                            var succeededTask = UploadVideo(title, desc, tags, categoryId, ps, filePath);
                            succeededTask.Wait();
                            succeeded &= succeededTask.Result;

                            if (succeeded && !atLeastOneSucceed) atLeastOneSucceed = true;
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        throw;
                    }
                    catch (Exception e)
                    {
                        ErrorFormat("An error occured while uploading the file {0}: {1}", file.Path, e.Message);
                        succeeded = false;
                    }
                }

            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                ErrorFormat("An error occured while uploading videos: {0}", e.Message);
                return new TaskStatus(Status.Error);
            }

            var status = Status.Success;

            if (!succeeded && atLeastOneSucceed)
            {
                status = Status.Warning;
            }
            else if (!succeeded)
            {
                status = Status.Error;
            }

            Info("Task finished.");
            return new TaskStatus(status);
        }

        private async System.Threading.Tasks.Task<bool> UploadVideo(string title, string desc, string[] tags, string categoryId, PrivacyStatus ps, string filePath)
        {
            try
            {
                InfoFormat("Uploading the video file {0} to YouTube started...", filePath);
                Info("Authentication started...");
                UserCredential credential;
                using (var stream = new FileStream(ClientSecrets, FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows an application to upload files to the
                        // authenticated user's YouTube channel, but doesn't allow other types of access.
                        new[] { YouTubeService.Scope.YoutubeUpload },
                        User,
                        CancellationToken.None
                        );
                }
                Info("Authentication succeeded.");

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

                var video = new Video
                {
                    Snippet = new VideoSnippet()
                };
                video.Snippet.Title = title;
                video.Snippet.Description = desc;
                video.Snippet.Tags = tags;
                video.Snippet.CategoryId = categoryId; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
                video.Status = new VideoStatus
                {
                    PrivacyStatus = ps.ToString().ToLower() // "unlisted" or "private" or "public"
                };

                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ResponseReceived += VideosInsertRequest_ResponseReceived;

                    var res = videosInsertRequest.Upload();

                    if (res.Exception != null)
                    {
                        ErrorFormat("An error occured while uploading the file {0}: {1}", filePath, res.Exception.Message);
                        return false;
                    }
                }

                InfoFormat("Uploading the video file {0} to YouTube succeeded.", filePath);
                return true;
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                ErrorFormat("An error occured while uploading the video file {0}: {1}", filePath, e.Message);
                return false;
            }
        }

        private void VideosInsertRequest_ResponseReceived(Video video)
        {
            InfoFormat("The video '{0}' was successfully uploaded. Id: '{1}' ", video.Snippet.Title, video.Id);
        }

    }
}


text:
package com.github.ltsopensource.zookeeper.serializer;

/**
 * @author Robert HG (254963746@qq.com) on 5/17/15.
 */
public class ZkMarshallingException extends RuntimeException {

	private static final long serialVersionUID = 2489236644437409454L;

	public ZkMarshallingException() {
        super();
    }

    public ZkMarshallingException(String message) {
        super(message);
    }

    public ZkMarshallingException(String message, Throwable cause) {
        super(message, cause);
    }

    public ZkMarshallingException(Throwable cause) {
        super(cause);
    }

}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "Understand category"
date: "2017-04-20 18:06:35 +0530"
tags: [jekyll]
---

Another series of posts can be written as seperate posts.


text:
#ifndef NRF_AAR_H__
#define NRF_AAR_H__

#include <nrfx.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @defgroup nrf_aar_hal AAR HAL
 * @{
 * @ingroup nrf_aar
 * @brief   Hardware access layer for managing the Accelerated Address Resolver (AAR) peripheral.
 */

/** @brief AAR events. */
typedef enum
{
    NRF_AAR_EVENT_END         = offsetof(NRF_AAR_Type, EVENTS_END),         ///< Address resolution procedure complete.
    NRF_AAR_EVENT_RESOLVED    = offsetof(NRF_AAR_Type, EVENTS_RESOLVED),    ///< Address resolved.
    NRF_AAR_EVENT_NOTRESOLVED = offsetof(NRF_AAR_Type, EVENTS_NOTRESOLVED), ///< Address not resolved.
} nrf_aar_event_t;

/** @brief AAR interrupts. */
typedef enum
{
    NRF_AAR_INT_END_MASK         = AAR_INTENSET_END_Msk,         ///< Interrupt on END event.
    NRF_AAR_INT_RESOLVED_MASK    = AAR_INTENSET_RESOLVED_Msk,    ///< Interrupt on RESOLVED event.
    NRF_AAR_INT_NOTRESOLVED_MASK = AAR_INTENSET_NOTRESOLVED_Msk, ///< Interrupt on NOTRESOLVED event.
} nrf_aar_int_mask_t;

/** @brief AAR tasks. */
typedef enum
{
    NRF_AAR_TASK_START = offsetof(NRF_AAR_Type, TASKS_START), ///< Start address resolution procedure.
    NRF_AAR_TASK_STOP  = offsetof(NRF_AAR_Type, TASKS_STOP),  ///< Stop address resolution procedure.
} nrf_aar_task_t;

/**
 * @brief Function for retrieving the state of the AAR event.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] event Event to be checked.
 *
 * @retval true  Event is set.
 * @retval false Event is not set.
 */
NRF_STATIC_INLINE bool nrf_aar_event_check(NRF_AAR_Type const * p_reg,
                                           nrf_aar_event_t      event);

/**
 * @brief Function for clearing the specified AAR event.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] event Event to be cleared.
 */
NRF_STATIC_INLINE void nrf_aar_event_clear(NRF_AAR_Type *  p_reg,
                                           nrf_aar_event_t event);

/**
 * @brief Function for getting the address of the specified AAR event register.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] event Event to get the address of.
 *
 * @return Address of the specified event register.
 */
NRF_STATIC_INLINE uint32_t nrf_aar_event_address_get(NRF_AAR_Type const * p_reg,
                                                     nrf_aar_event_t      event);

/**
 * @brief Function for enabling the specified interrupts.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] mask  Mask of interrupts to be enabled.
 */
NRF_STATIC_INLINE void nrf_aar_int_enable(NRF_AAR_Type * p_reg, uint32_t mask);

/**
 * @brief Function for checking if the specified interrupts are enabled.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] mask  Mask of interrupts to be checked.
 *
 * @return Mask of enabled interrupts.
 */
NRF_STATIC_INLINE uint32_t nrf_aar_int_enable_check(NRF_AAR_Type const * p_reg, uint32_t mask);

/**
 * @brief Function for disabling the specified interrupts.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] mask  Mask of interrupts to be disabled.
 */
NRF_STATIC_INLINE void nrf_aar_int_disable(NRF_AAR_Type * p_reg, uint32_t mask);

/**
 * @brief Function for starting an AAR task.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] task  Task to be activated.
 */
NRF_STATIC_INLINE void nrf_aar_task_trigger(NRF_AAR_Type * p_reg, nrf_aar_task_t task);

/**
 * @brief Function for getting the address of a specific AAR task register.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 * @param[in] task  Requested AAR task.
 *
 * @return Address of the specified task register.
 */
NRF_STATIC_INLINE uint32_t nrf_aar_task_address_get(NRF_AAR_Type const * p_reg,
                                                    nrf_aar_task_t       task);

/**
 * @brief Function for enabling AAR.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 */
NRF_STATIC_INLINE void nrf_aar_enable(NRF_AAR_Type * p_reg);

/**
 * @brief Function for disabling AAR.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 */
NRF_STATIC_INLINE void nrf_aar_disable(NRF_AAR_Type * p_reg);

/**
 * @brief Function for setting the pointer to the Identity Resolving Keys (IRK) data structure.
 *
 * The size of the provided data structure must correspond to the number of keys available.
 * Each key occupies 16 bytes.
 *
 * @param[in] p_reg   Pointer to the structure of registers of the peripheral.
 * @param[in] irk_ptr Pointer to the IRK data structure. Must point to the Data RAM region.
 *
 * @sa nrf_aar_irk_number_set
 */
NRF_STATIC_INLINE void nrf_aar_irk_pointer_set(NRF_AAR_Type * p_reg, uint8_t const * irk_ptr);

/**
 * @brief Function for getting the pointer to the Identity Resolving Keys
 *        data structure.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 *
 * @return Pointer to the IRK data structure.
 */
NRF_STATIC_INLINE uint8_t const * nrf_aar_irk_pointer_get(NRF_AAR_Type const * p_reg);

/**
 * @brief Function for setting the number of keys available in the Identity Resolving Keys
 *        data structure.
 *
 * @param[in] p_reg   Pointer to the structure of registers of the peripheral.
 * @param[in] irk_num Number of keys available in the IRK data structure. Maximum is 16.
 *                    Must correspond to the size of the provided IRK data structure.
 *
 * @sa nrf_aar_irk_pointer_set
 */
NRF_STATIC_INLINE void nrf_aar_irk_number_set(NRF_AAR_Type * p_reg, uint8_t irk_num);

/**
 * @brief Function for getting the number of keys available in the Identity Resolving Keys
 *        data structure.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 *
 * @return Number of keys in the IRK data structure.
 */
NRF_STATIC_INLINE uint8_t nrf_aar_irk_number_get(NRF_AAR_Type const * p_reg);

/**
 * @brief Function for setting the pointer to the resolvable address.
 *
 * The resolvable address must consist of 6 bytes.
 *
 * @param[in] p_reg    Pointer to the structure of registers of the peripheral.
 * @param[in] addr_ptr Pointer to the address to resolve using the available IRK keys.
 *                     Must point to the Data RAM region.
 */
NRF_STATIC_INLINE void nrf_aar_addr_pointer_set(NRF_AAR_Type * p_reg, uint8_t const * addr_ptr);

/**
 * @brief Function for getting the pointer to the resolvable address.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 *
 * @return Pointer to the address to resolve.
 */
NRF_STATIC_INLINE uint8_t const * nrf_aar_addr_pointer_get(NRF_AAR_Type const * p_reg);

/**
 * @brief Function for setting the pointer to the scratch data area.
 *
 * The scratch data area is used for temporary storage during the address resolution procedure.
 * A space of minimum 3 bytes must be reserved for the scratch data area.
 *
 * @param[in] p_reg       Pointer to the structure of registers of the peripheral.
 * @param[in] scratch_ptr Pointer to the scratch data area. Must point to the Data RAM region.
 */
NRF_STATIC_INLINE void nrf_aar_scratch_pointer_set(NRF_AAR_Type * p_reg, uint8_t * scratch_ptr);

/**
 * @brief Function for getting the pointer to the scratch data area.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 *
 * @return Pointer to the scratch data area.
 */
NRF_STATIC_INLINE uint8_t * nrf_aar_scratch_pointer_get(NRF_AAR_Type const * p_reg);

/**
 * @brief Function for getting the index of the Identity Resolving Key that was used
 *        the last time an address was resolved.
 *
 * This function can be used to get the IRK index that matched the resolvable address,
 * provided that @ref NRF_AAR_EVENT_RESOLVED occured. Otherwise, it will return
 * the index of the last IRK stored in the IRK data structure.
 *
 * @param[in] p_reg Pointer to the structure of registers of the peripheral.
 *
 * @return The index of the IRK that was used the last time an address was resolved.
 */
NRF_STATIC_INLINE uint8_t nrf_aar_resolution_status_get(NRF_AAR_Type const * p_reg);

#ifndef NRF_DECLARE_ONLY
NRF_STATIC_INLINE bool nrf_aar_event_check(NRF_AAR_Type const * p_reg,
                                           nrf_aar_event_t      aar_event)
{
    return (bool)*(volatile uint32_t *)((uint8_t *)p_reg + (uint32_t)aar_event);
}

NRF_STATIC_INLINE void nrf_aar_event_clear(NRF_AAR_Type *  p_reg,
                                           nrf_aar_event_t aar_event)
{
    *((volatile uint32_t *)((uint8_t *)p_reg + (uint32_t)aar_event)) = 0;
#if __CORTEX_M == 0x04
    volatile uint32_t dummy = *((volatile uint32_t *)((uint8_t *)p_reg + (uint32_t)aar_event));
    (void)dummy;
#endif
}

NRF_STATIC_INLINE uint32_t nrf_aar_event_address_get(NRF_AAR_Type const * p_reg,
                                                     nrf_aar_event_t      aar_event)
{
    return (uint32_t)((uint8_t *)p_reg + (uint32_t)aar_event);
}

NRF_STATIC_INLINE void nrf_aar_int_enable(NRF_AAR_Type * p_reg, uint32_t mask)
{
    p_reg->INTENSET = mask;
}

NRF_STATIC_INLINE uint32_t nrf_aar_int_enable_check(NRF_AAR_Type const * p_reg, uint32_t mask)
{
    return p_reg->INTENSET & mask;
}

NRF_STATIC_INLINE void nrf_aar_int_disable(NRF_AAR_Type * p_reg, uint32_t mask)
{
    p_reg->INTENCLR = mask;
}

NRF_STATIC_INLINE void nrf_aar_task_trigger(NRF_AAR_Type * p_reg, nrf_aar_task_t task)
{
    *(volatile uint32_t *)((uint8_t *)p_reg + (uint32_t)task) = 1;
}

NRF_STATIC_INLINE uint32_t nrf_aar_task_address_get(NRF_AAR_Type const * p_reg,
                                                    nrf_aar_task_t       task)
{
    return (uint32_t)((uint8_t *)p_reg + (uint32_t)task);
}

NRF_STATIC_INLINE void nrf_aar_enable(NRF_AAR_Type * p_reg)
{
    p_reg->ENABLE = AAR_ENABLE_ENABLE_Enabled << AAR_ENABLE_ENABLE_Pos;
}

NRF_STATIC_INLINE void nrf_aar_disable(NRF_AAR_Type * p_reg)
{
    p_reg->ENABLE = AAR_ENABLE_ENABLE_Disabled << AAR_ENABLE_ENABLE_Pos;
}

NRF_STATIC_INLINE void nrf_aar_irk_pointer_set(NRF_AAR_Type * p_reg, uint8_t const * irk_ptr)
{
    p_reg->IRKPTR = (uint32_t)irk_ptr;
}

NRF_STATIC_INLINE uint8_t const * nrf_aar_irk_pointer_get(NRF_AAR_Type const * p_reg)
{
    return (uint8_t const *)(p_reg->IRKPTR);
}

NRF_STATIC_INLINE void nrf_aar_irk_number_set(NRF_AAR_Type * p_reg, uint8_t irk_num)
{
    p_reg->NIRK = irk_num;
}

NRF_STATIC_INLINE uint8_t nrf_aar_irk_number_get(NRF_AAR_Type const * p_reg)
{
    return (uint8_t)(p_reg->NIRK);
}

NRF_STATIC_INLINE void nrf_aar_addr_pointer_set(NRF_AAR_Type * p_reg, uint8_t const * addr_ptr)
{
    p_reg->ADDRPTR = (uint32_t)addr_ptr;
}

NRF_STATIC_INLINE uint8_t const * nrf_aar_addr_pointer_get(NRF_AAR_Type const * p_reg)
{
    return (uint8_t const *)(p_reg->ADDRPTR);
}

NRF_STATIC_INLINE void nrf_aar_scratch_pointer_set(NRF_AAR_Type * p_reg, uint8_t * scratch_ptr)
{
    p_reg->SCRATCHPTR = (uint32_t)scratch_ptr;
}

NRF_STATIC_INLINE uint8_t * nrf_aar_scratch_pointer_get(NRF_AAR_Type const * p_reg)
{
    return (uint8_t *)(p_reg->SCRATCHPTR);
}

NRF_STATIC_INLINE uint8_t nrf_aar_resolution_status_get(NRF_AAR_Type const * p_reg)
{
    return (uint8_t)(p_reg->STATUS);
}

#endif // NRF_DECLARE_ONLY

/** @} */

#ifdef __cplusplus
}
#endif

#endif // NRF_AAR_H__


text:
package net.lightbody.bmp.proxy;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.exception.ProxyExistsException;
import net.lightbody.bmp.exception.ProxyPortsExhaustedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

@Singleton
public class ProxyManager {
    private static final Logger LOG = LoggerFactory.getLogger(ProxyManager.class);

    private int lastPort;
    private final int minPort;
    private final int maxPort;
    private final Provider<LegacyProxyServer> proxyServerProvider;
    // retain a reference to the Cache to allow the ProxyCleanupTask to .cleanUp(), since asMap() is just a view into the cache.
    // it would seem to make sense to pass the newly-built Cache directly to the ProxyCleanupTask and have it retain a WeakReference to it, and
    // only maintain a reference to the .asMap() result in this class. puzzlingly, however, the Cache can actually get garbage collected
    // before the .asMap() view of it does.
    private final Cache<Integer, LegacyProxyServer> proxyCache;
    private final ConcurrentMap<Integer, LegacyProxyServer> proxies;

    /**
     * Interval at which expired proxy checks will actively clean up expired proxies. Proxies may still be cleaned up when accessing the
     * proxies map.
     */
    private static final int EXPIRED_PROXY_CLEANUP_INTERVAL_SECONDS = 60;

    // Initialize-on-demand a single thread executor that will create a daemon thread to clean up expired proxies. Since the resulting executor
    // is a singleton, there will at most one thread to service all ProxyManager instances.
    private static class ScheduledExecutorHolder {
        private static final ScheduledExecutorService expiredProxyCleanupExecutor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = Executors.defaultThreadFactory().newThread(r);
                thread.setName("expired-proxy-cleanup-thread");
                thread.setDaemon(true);
                return thread;
            }
        });
    }

    // static inner class to prevent leaking ProxyManager instances to the cleanup task
    private static class ProxyCleanupTask implements Runnable {
        // using a WeakReference that will indicate to us when the Cache (and thus its ProxyManager) has been garbage
        // collected, allowing this cleanup task to kill itself
        private final WeakReference<Cache<Integer, LegacyProxyServer>> proxyCache;

        public ProxyCleanupTask(Cache<Integer, LegacyProxyServer> cache) {
            this.proxyCache = new WeakReference<Cache<Integer, LegacyProxyServer>>(cache);
        }

        @Override
        public void run() {
            Cache<Integer, LegacyProxyServer> cache = proxyCache.get();
            if (cache != null) {
                try {
                    cache.cleanUp();
                } catch (RuntimeException e) {
                    LOG.warn("Error occurred while attempting to clean up expired proxies", e);
                }
            } else {
                // the cache instance was garbage collected, so it no longer needs to be cleaned up. throw an exception
                // to prevent the scheduled executor from re-scheduling this cleanup
                LOG.info("Proxy Cache was garbage collected. No longer cleaning up expired proxies for unused ProxyManager.");

                throw new RuntimeException("Exiting ProxyCleanupTask");
            }
        }
    }

    @Inject
    public ProxyManager(Provider<LegacyProxyServer> proxyServerProvider, @Named("minPort") Integer minPort, @Named("maxPort") Integer maxPort, final @Named("ttl") Integer ttl) {
        this.proxyServerProvider = proxyServerProvider;
        this.minPort = minPort;
        this.maxPort = maxPort;
        this.lastPort = maxPort;
        if (ttl > 0) {
            // proxies should be evicted after the specified ttl, so set up an evicting cache and a listener to stop the proxies when they're evicted
            RemovalListener<Integer, LegacyProxyServer> removalListener = new RemovalListener<Integer, LegacyProxyServer> () {
                public void onRemoval(RemovalNotification<Integer, LegacyProxyServer> removal) {
                    try {
                        LegacyProxyServer proxy = removal.getValue();
                        if (proxy != null) {
                            LOG.info("Expiring ProxyServer on port {} after {} seconds without activity", proxy.getPort(), ttl);
                            proxy.stop();
                        }
                    } catch (Exception ex) {
                        LOG.warn("Error while stopping an expired proxy on port " + removal.getKey(), ex);
                    }
                }
            };

            this.proxyCache = CacheBuilder.newBuilder()
                    .expireAfterAccess(ttl, TimeUnit.SECONDS)
                    .removalListener(removalListener)
                    .build();

            this.proxies = proxyCache.asMap();

            // schedule the asynchronous proxy cleanup task
            ScheduledExecutorHolder.expiredProxyCleanupExecutor.scheduleWithFixedDelay(new ProxyCleanupTask(proxyCache),
                    EXPIRED_PROXY_CLEANUP_INTERVAL_SECONDS, EXPIRED_PROXY_CLEANUP_INTERVAL_SECONDS, TimeUnit.SECONDS);
        } else {
            this.proxies = new ConcurrentHashMap<Integer, LegacyProxyServer>();
            // nothing to timeout, so no Cache
            this.proxyCache = null;
        }
    }

    public LegacyProxyServer create(Map<String, String> options, Integer port, String bindAddr) {
        LOG.debug("Instantiate ProxyServer...");
        LegacyProxyServer proxy = proxyServerProvider.get();

        if (options != null) {
            LOG.debug("Apply options `{}` to new ProxyServer...", options);
            proxy.setOptions(options);
        }

        if (bindAddr != null) {
            LOG.debug("Bind ProxyServer to `{}`...", bindAddr);
            InetAddress inetAddress;
            try {
            	inetAddress = InetAddress.getByName(bindAddr);
            } catch (UnknownHostException e) {
            	LOG.error("Unable to bind proxy to address: " + bindAddr + "; proxy will not be created.", e);

            	throw new RuntimeException("Unable to bind proxy to address: ", e);
            }

            proxy.setLocalHost(inetAddress);
        }

        if (port != null) {
            return startProxy(proxy, port);
        }

        while(proxies.size() <= maxPort-minPort){
            LOG.debug("Use next available port for new ProxyServer...");
            port = nextPort();
            try{
                return startProxy(proxy, port);
            }catch(ProxyExistsException ex){
                LOG.debug("Proxy already exists at port {}", port);
            }
        }
        throw new ProxyPortsExhaustedException();
    }

    public LegacyProxyServer create(Map<String, String> options, Integer port) {
        return create(options, port, null);
    }

    public LegacyProxyServer create(Map<String, String> options) {
        return create(options, null, null);
    }

    public LegacyProxyServer create() {
        return create(null, null, null);
    }

    public LegacyProxyServer create(int port) {
        return create(null, port, null);
    }

    public LegacyProxyServer get(int port) {
        return proxies.get(port);
    }

    private LegacyProxyServer startProxy(LegacyProxyServer proxy, int port) {
        if (port != 0) {
            proxy.setPort(port);
            LegacyProxyServer old = proxies.putIfAbsent(port, proxy);
            if (old != null) {
                LOG.info("Proxy already exists at port {}", port);
                throw new ProxyExistsException(port);
            }
        }

        try{
            proxy.start();
            if (port == 0) {
                int realPort = proxy.getPort();
                proxies.put(realPort, proxy);
            }

            return proxy;
        }catch(Exception ex){
            if (port != 0) {
                proxies.remove(port);
            }
            try{
                proxy.stop();
            }catch(Exception ex2){
                ex.addSuppressed(ex2);
            }
            throw ex;
        }
    }

    private synchronized int nextPort(){
        return lastPort < maxPort? ++lastPort : (lastPort = minPort);
    }

    public Collection<LegacyProxyServer> get() {
        return proxies.values();
    }

    public void delete(int port) {
        LegacyProxyServer proxy = proxies.remove(port);
        if (proxy == null) {
            return;
        }

        // temporary: to avoid stopping an already-stopped BrowserMobProxyServer instance, see if it's stopped before re-stopping it
        if (proxy instanceof ProxyServer || !((BrowserMobProxyServer) proxy).isStopped()) {
            proxy.stop();
        }
    }

}


text:
@implementation UsernameViewController

- (IBAction)textChanged:(id)sender
{
    self.doneButton.enabled = ([self.usernameField.text length] > 0);
}

- (IBAction)done:(id)sender
{
    [self.delegate controller:self didEndEditingWithUsername:self.usernameField.text];
}

@end


text:
#ifndef ALTERA_MSGDMA_DESCRIPTOR_REGS_H_
#define ALTERA_MSGDMA_DESCRIPTOR_REGS_H_

#include "io.h"

/*
  Descriptor formats:

  Standard Format:

  Offset         |    3                 2                 1                   0
  ------------------------------------------------------------------------------
   0x0           |                      Read Address[31..0]
   0x4           |                      Write Address[31..0]
   0x8           |                      Length[31..0]
   0xC           |                      Control[31..0]

  Extended Format:

Offset|   3                  2                  1                  0
 ------------------------------------------------------------------------------
 0x0  |                      Read Address[31..0]
 0x4  |                      Write Address[31..0]
 0x8  |                      Length[31..0]
 0xC  |Write Burst Count[7..0] | Read Burst Count[7..0] | Sequence Number[15..0]
 0x10 | Write Stride[15..0]           |            Read Stride[15..0]
 0x14 |                      Read Address[63..32]
 0x18 |                      Write Address[63..32]
 0x1C |                      Control[31..0]

  Note:  The control register moves from offset 0xC to 0x1C depending on the
         format used

*/

#define ALTERA_MSGDMA_DESCRIPTOR_READ_ADDRESS_REG                      0x0
#define ALTERA_MSGDMA_DESCRIPTOR_WRITE_ADDRESS_REG                     0x4
#define ALTERA_MSGDMA_DESCRIPTOR_LENGTH_REG                            0x8
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_STANDARD_REG                  0xC
#define ALTERA_MSGDMA_DESCRIPTOR_SEQUENCE_NUMBER_REG                   0xC
#define ALTERA_MSGDMA_DESCRIPTOR_READ_BURST_REG                        0xE
#define ALTERA_MSGDMA_DESCRIPTOR_WRITE_BURST_REG                       0xF
#define ALTERA_MSGDMA_DESCRIPTOR_READ_STRIDE_REG                       0x10
#define ALTERA_MSGDMA_DESCRIPTOR_WRITE_STRIDE_REG                      0x12
#define ALTERA_MSGDMA_DESCRIPTOR_READ_ADDRESS_HIGH_REG                 0x14
#define ALTERA_MSGDMA_DESCRIPTOR_WRITE_ADDRESS_HIGH_REG                0x18
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_ENHANCED_REG                  0x1C

/* masks and offsets for the sequence number and programmable burst counts */
#define ALTERA_MSGDMA_DESCRIPTOR_SEQUENCE_NUMBER_MASK                  0xFFFF
#define ALTERA_MSGDMA_DESCRIPTOR_SEQUENCE_NUMBER_OFFSET                0
#define ALTERA_MSGDMA_DESCRIPTOR_READ_BURST_COUNT_MASK                 0x00FF0000
#define ALTERA_MSGDMA_DESCRIPTOR_READ_BURST_COUNT_OFFSET               16
#define ALTERA_MSGDMA_DESCRIPTOR_WRITE_BURST_COUNT_MASK                0xFF000000
#define ALTERA_MSGDMA_DESCRIPTOR_WRITE_BURST_COUNT_OFFSET              24

/* masks and offsets for the read and write strides */
#define ALTERA_MSGDMA_DESCRIPTOR_READ_STRIDE_MASK                      0xFFFF
#define ALTERA_MSGDMA_DESCRIPTOR_READ_STRIDE_OFFSET                    0
#define ALTERA_MSGDMA_DESCRIPTOR_WRITE_STRIDE_MASK                     0xFFFF0000
#define ALTERA_MSGDMA_DESCRIPTOR_WRITE_STRIDE_OFFSET                   16

/* masks and offsets for the bits in the descriptor control field */
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_TRANSMIT_CHANNEL_MASK         0xFF
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_TRANSMIT_CHANNEL_OFFSET       0
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_GENERATE_SOP_MASK             (1 << 8)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_GENERATE_SOP_OFFSET           8
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_GENERATE_EOP_MASK             (1 << 9)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_GENERATE_EOP_OFFSET           9
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_PARK_READS_MASK               (1 << 10)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_PARK_READS_OFFSET             10
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_PARK_WRITES_MASK              (1 << 11)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_PARK_WRITES_OFFSET            11
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_END_ON_EOP_MASK               (1 << 12)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_END_ON_EOP_OFFSET             12
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_TRANSFER_COMPLETE_IRQ_MASK    (1 << 14)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_TRANSFER_COMPLETE_IRQ_OFFSET  14
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_EARLY_TERMINATION_IRQ_MASK    (1 << 15)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_EARLY_TERMINATION_IRQ_OFFSET  15
/* the read master will use this as the transmit error, the dispatcher will use
this to generate an interrupt if any of the error bits are asserted by the
write master */
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_ERROR_IRQ_MASK                (0xFF << 16)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_ERROR_IRQ_OFFSET              16
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_EARLY_DONE_ENABLE_MASK        (1 << 24)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_EARLY_DONE_ENABLE_OFFSET      24
/* at a minimum you always have to write '1' to this bit as it commits the
descriptor to the dispatcher */
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_GO_MASK                       (1 << 31)
#define ALTERA_MSGDMA_DESCRIPTOR_CONTROL_GO_OFFSET                     31

/* Each register is byte lane accessible so the some of the values that are
 * less than 32 bits wide are written to according to the field width.
 */
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_READ_ADDRESS(base, data)  \
        IOWR_32DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_READ_ADDRESS_REG, data)
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_WRITE_ADDRESS(base, data)  \
        IOWR_32DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_WRITE_ADDRESS_REG, data)
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_LENGTH(base, data)  \
        IOWR_32DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_LENGTH_REG, data)
/* this pushes the descriptor into the read/write FIFOs when standard descriptors
are used */
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_CONTROL_STANDARD(base, data)  \
        IOWR_32DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_CONTROL_STANDARD_REG, data)
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_SEQUENCE_NUMBER(base, data)  \
        IOWR_16DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_SEQUENCE_NUMBER_REG, data)
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_READ_BURST(base, data)  \
        IOWR_8DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_READ_BURST_REG, data)
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_WRITE_BURST(base, data)  \
        IOWR_8DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_WRITE_BURST_REG, data)
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_READ_STRIDE(base, data)  \
        IOWR_16DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_READ_STRIDE_REG, data)
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_WRITE_STRIDE(base, data)  \
        IOWR_16DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_WRITE_STRIDE_REG, data)
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_READ_ADDRESS_HIGH(base, data)  \
        IOWR_32DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_READ_ADDRESS_HIGH_REG, data)
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_WRITE_ADDRESS_HIGH(base, data)  \
        IOWR_32DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_WRITE_ADDRESS_HIGH_REG, data)
/* this pushes the descriptor into the read/write FIFOs when the extended
descriptors are used */
#define IOWR_ALTERA_MSGDMA_DESCRIPTOR_CONTROL_ENHANCED(base, data)  \
        IOWR_32DIRECT(base, ALTERA_MSGDMA_DESCRIPTOR_CONTROL_ENHANCED_REG, data)

#endif /*ALTERA_MSGDMA_ALTERA_MSGDMA_DESCRIPTOR_REGS_H_*/


text:
These notebooks document important parts of the toolkit used in
the project. To open them make sure that ipython and its
dependencies are installed. Then cd in the notebooks dir and
hit `ipython notebook`.

The notebooks can be exported to html using the command

    ipython nbconvert name-of-the-notebook.ipynb

It is possible that one has to install several dependencies for this
command to work (for instance, `pip install pygments` and
`sudo apt-get install pandoc`). Pygments might have to be installed
globally as well (`sudo apt-get install python-pygments`).


text:
/**
 * @format
 * @flow
 */

import * as React from 'react';

declare var MyComponent: React.ComponentType<{foo: number}> & {
  someStatic: boolean,
};

<MyComponent />;


text:
import java_lib_arrays.*;

public class java_lib_arrays_runme {

  static {
    try {
	System.loadLibrary("java_lib_arrays");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[]) {

    // Check array member variables
    ArrayStruct as = new ArrayStruct();

    // Create arrays for all the array types that ArrayStruct can handle
    String array_c = "X";
    byte[] array_c_extra = {11, 22};
    byte[] array_sc = {10, 20};
    short[] array_uc = {101, 201};
    short[] array_s = {1002, 2002};
    int[] array_us = {1003, 2003};
    int[] array_i = {1004, 2004};
    long[] array_ui = {1005, 2005};
    int[] array_l = {1006, 2006};
    long[] array_ul = {1007, 2007};
    long[] array_ll = {1008, 2008};
    float[] array_f = {1009.1f, 2009.1f};
    double[] array_d = {1010.2f, 2010.2f};
    int[] array_finger = {finger.Three, finger.Four};
    int[] array_toe = {toe.Big, toe.Little};

    SimpleStruct[] array_struct={new SimpleStruct(), new SimpleStruct()};
    array_struct[0].setDouble_field(222.333);
    array_struct[1].setDouble_field(444.555);

    AnotherStruct[] array_another_struct={new AnotherStruct(), new AnotherStruct()};
    array_another_struct[0].setSimple(array_struct[0]);
    array_another_struct[1].setSimple(array_struct[1]);

    YetAnotherStruct[] array_yet_another_struct={new YetAnotherStruct(), new YetAnotherStruct()};
    array_yet_another_struct[0].setSimple(array_struct[0]);
    array_yet_another_struct[1].setSimple(array_struct[1]);

    if (array_another_struct[0].getSimple().getDouble_field() != 222.333) throw new RuntimeException("AnotherStruct[0] failed");
    if (array_another_struct[1].getSimple().getDouble_field() != 444.555) throw new RuntimeException("AnotherStruct[1] failed");

    if (java_lib_arrays.extract_ptr(array_yet_another_struct, 0) != 222.333) throw new RuntimeException("extract_ptr 0 failed");
    if (java_lib_arrays.extract_ptr(array_yet_another_struct, 1) != 444.555) throw new RuntimeException("extract_ptr 1 failed");

    java_lib_arrays.modifyYAS(array_yet_another_struct, array_yet_another_struct.length);
    for (int i=0; i<2; ++i) {
      if (array_yet_another_struct[i].getSimple().getDouble_field() != array_struct[i].getDouble_field() * 10.0)
        throw new RuntimeException("modifyYAS failed ");
    }

    java_lib_arrays.toestest(array_toe, array_toe, array_toe);

    // Now set the array members and check that they have been set correctly
    as.setArray_c(array_c);
    check_string(array_c, as.getArray_c());

    as.setArray_sc(array_sc);
    check_byte_array(array_sc, as.getArray_sc());

    as.setArray_uc(array_uc);
    check_short_array(array_uc, as.getArray_uc());

    as.setArray_s(array_s);
    check_short_array(array_s, as.getArray_s());

    as.setArray_us(array_us);
    check_int_array(array_us, as.getArray_us());

    as.setArray_i(array_i);
    check_int_array(array_i, as.getArray_i());

    as.setArray_ui(array_ui);
    check_long_array(array_ui, as.getArray_ui());

    as.setArray_l(array_l);
    check_int_array(array_l, as.getArray_l());

    as.setArray_ul(array_ul);
    check_long_array(array_ul, as.getArray_ul());

    as.setArray_ll(array_ll);
    check_long_array(array_ll, as.getArray_ll());

    as.setArray_f(array_f);
    check_float_array(array_f, as.getArray_f());

    as.setArray_d(array_d);
    check_double_array(array_d, as.getArray_d());

    as.setArray_enum(array_finger);
    check_int_array(array_finger, as.getArray_enum());

    as.setArray_struct(array_struct);
    check_struct_array(array_struct, as.getArray_struct());

    // Extended element (for char[])
    ArrayStructExtra ase = new ArrayStructExtra();
    ase.setArray_c2(array_c_extra);
    check_byte_array(array_c_extra, ase.getArray_c2());

 }

  // Functions to check that the array values were set correctly
  public static void check_string(String original, String checking) {
    if (!checking.equals(original)) {
      throw new RuntimeException("Runtime test failed. checking = [" + checking + "]");
    }
  }
  public static void check_byte_array(byte[] original, byte[] checking) {
    for (int i=0; i<original.length; i++) {
      if (checking[i] != original[i]) {
        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
      }
    }
  }
  public static void check_short_array(short[] original, short[] checking) {
    for (int i=0; i<original.length; i++) {
      if (checking[i] != original[i]) {
        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
      }
    }
  }
  public static void check_int_array(int[] original, int[] checking) {
    for (int i=0; i<original.length; i++) {
      if (checking[i] != original[i]) {
        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
      }
    }
  }
  public static void check_long_array(long[] original, long[] checking) {
    for (int i=0; i<original.length; i++) {
      if (checking[i] != original[i]) {
        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
      }
    }
  }
  public static void check_float_array(float[] original, float[] checking) {
    for (int i=0; i<original.length; i++) {
      if (checking[i] != original[i]) {
        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
      }
    }
  }
  public static void check_double_array(double[] original, double[] checking) {
    for (int i=0; i<original.length; i++) {
      if (checking[i] != original[i]) {
        throw new RuntimeException("Runtime test failed. checking[" + i + "]=" + checking[i]);
      }
    }
  }
  public static void check_struct_array(SimpleStruct[] original, SimpleStruct[] checking) {
    for (int i=0; i<original.length; i++) {
      if (checking[i].getDouble_field() != original[i].getDouble_field()) {
        throw new RuntimeException("Runtime test failed. checking[" + i + "].double_field=" + checking[i].getDouble_field());
      }
    }
  }
}


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'pennies'
require 'spec'
require 'spec/autorun'

RSpec::Runner.configure do |config|

end


text:
package ru.pavlenov.bio.graph2;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Какой сам ⚝
 * Author: Pavlenov Semen
 * Date: 16.01.14
 * <p>
 * E = mc^2
 */
public interface IBaseGraph<N, E extends IBaseEdge> {

    public Map<N,List<E>> getNodes();

    public List<E> getEdges();

    public boolean addNode(N node);

    public boolean addEdge(E edge);

    public boolean addEdge(N sourceNode, N targetNode);

    public boolean addEdge(N sourceNode, N targetNode, E edge);

    /**
     * Отдаёт все ребра связанные с данной вершиной
     *
     * @param node
     * @return
     */
    public Set<E> edgesOf(N node);

    public E edgeOf(N node);

    public E edgeOfAndPassed(N node);

    public void edgePassed(E edge);

    public N getEdgeSource(E edge);

    public N getEdgeTarget(E edge);

    public boolean removeAllEdges(Collection<? extends E> edges);

    public Set<E> removeAllEdges(N sourceNode, N targetNode);

    public boolean removeAllNodes(Collection<? extends N> nodes);

    public E removeEdge(N sourceNode, N targetNode);

    public boolean removeEdge(E edge);

    public boolean removeNode(N node);

    public double getEdgeWeight(E edge);

    /**
     * Считаем сколько у нас отдельных подграфов
     * т.е. несвязанных между собой
     *
     * @return
     */
    public Integer countSub();

}


text:
layout: doc-page
title: "Polymorphic Function Types"
nightlyOf: https://docs.scala-lang.org/scala3/reference/new-types/polymorphic-function-types.html
---

A polymorphic function type is a function type which accepts type parameters.
For example:

```scala
// A polymorphic method:
def foo[A](xs: List[A]): List[A] = xs.reverse

// A polymorphic function value:
val bar: [A] => List[A] => List[A]
//       ^^^^^^^^^^^^^^^^^^^^^^^^^
//       a polymorphic function type
       = [A] => (xs: List[A]) => foo[A](xs)
```

Scala already has _polymorphic methods_, i.e. methods which accepts type parameters.
Method `foo` above is an example, accepting a type parameter `A`.
So far, it
was not possible to turn such methods into polymorphic function values like `bar` above,
which can be passed as parameters to other functions, or returned as results.

In Scala 3 this is now possible. The type of the `bar` value above is

```scala
[A] => List[A] => List[A]
```

This type describes function values which take a type `A` as a parameter,
then take a list of type `List[A]`, and return a list of the same type `List[A]`.

[More details](https://github.com/lampepfl/dotty/pull/4672)

## Example Usage

Polymorphic function type are particularly useful
when callers of a method are required to provide a
function which has to be polymorphic,
meaning that it should accept arbitrary types as part of its inputs.

For instance, consider the situation where we have
a data type to represent the expressions of a simple language
(consisting only of variables and function applications)
in a strongly-typed way:

```scala
enum Expr[A]:
  case Var(name: String)
  case Apply[A, B](fun: Expr[B => A], arg: Expr[B]) extends Expr[A]
```

We would like to provide a way for users to map a function
over all immediate subexpressions of a given `Expr`.
This requires the given function to be polymorphic,
since each subexpression may have a different type.
Here is how to implement this using polymorphic function types:

```scala
def mapSubexpressions[A](e: Expr[A])(f: [B] => Expr[B] => Expr[B]): Expr[A] =
  e match
    case Apply(fun, arg) => Apply(f(fun), f(arg))
    case Var(n) => Var(n)
```

And here is how to use this function to _wrap_ each subexpression
in a given expression with a call to some `wrap` function,
defined as a variable:

```scala
val e0 = Apply(Var("f"), Var("a"))
val e1 = mapSubexpressions(e0)(
  [B] => (se: Expr[B]) => Apply(Var[B => B]("wrap"), se))
println(e1) // Apply(Apply(Var(wrap),Var(f)),Apply(Var(wrap),Var(a)))
```

## Relationship With Type Lambdas

Polymorphic function types are not to be confused with
[_type lambdas_](type-lambdas.md).
While the former describes the _type_ of a polymorphic _value_,
the latter is an actual function value _at the type level_.

A good way of understanding the difference is to notice that
**_type lambdas are applied in types,
whereas polymorphic functions are applied in terms_**:
One would call the function `bar` above
by passing it a type argument `bar[Int]` _within a method body_.
On the other hand, given a type lambda such as `type F = [A] =>> List[A]`,
one would call `F` _within a type expression_, as in `type Bar = F[Int]`.


text:
using Newtonsoft.Json;

namespace IBM.WatsonDeveloperCloud.ToneAnalyzer.v3.Model
{
    /// <summary>
    /// ToneChatScore.
    /// </summary>
    public class ToneChatScore
    {
        /// <summary>
        /// The score for the tone in the range of 0.5 to 1. A score greater than 0.75 indicates a high likelihood that the tone is perceived in the utterance.
        /// </summary>
        /// <value>The score for the tone in the range of 0.5 to 1. A score greater than 0.75 indicates a high likelihood that the tone is perceived in the utterance.</value>
        [JsonProperty("score", NullValueHandling = NullValueHandling.Ignore)]
        public double? Score { get; set; }
        /// <summary>
        /// The unique, non-localized identifier of the tone for the results. The service can return results for the following tone IDs: `sad`, `frustrated`, `satisfied`, `excited`, `polite`, `impolite`, and `sympathetic`. The service returns results only for tones whose scores meet a minimum threshold of 0.5.
        /// </summary>
        /// <value>The unique, non-localized identifier of the tone for the results. The service can return results for the following tone IDs: `sad`, `frustrated`, `satisfied`, `excited`, `polite`, `impolite`, and `sympathetic`. The service returns results only for tones whose scores meet a minimum threshold of 0.5.</value>
        [JsonProperty("tone_id", NullValueHandling = NullValueHandling.Ignore)]
        public string ToneId { get; set; }
        /// <summary>
        /// The user-visible, localized name of the tone.
        /// </summary>
        /// <value>The user-visible, localized name of the tone.</value>
        [JsonProperty("tone_name", NullValueHandling = NullValueHandling.Ignore)]
        public string ToneName { get; set; }
    }

}


text:
using namespace std;
using namespace mfem;

enum class PCType { NONE, LOR, HO };

// Define template parameters for optimized build.
template <int dim> struct geom_t { };
template <>
struct geom_t<2> { static const Geometry::Type value = Geometry::SQUARE; };
template <>
struct geom_t<3> { static const Geometry::Type value = Geometry::CUBE; };

const int mesh_p   = 3; // mesh curvature (default: 3)
const int sol_p    = 3; // solution order (default: 3)

template <int dim>
struct ex1_t
{
   static const Geometry::Type geom = geom_t<dim>::value;
   static const int            rdim     = Geometry::Constants<geom>::Dimension;
   static const int            ir_order = 2*sol_p+rdim-1;

   // Static mesh type
   using mesh_fe_t = H1_FiniteElement<geom,mesh_p>;
   using mesh_fes_t = H1_FiniteElementSpace<mesh_fe_t>;
   using mesh_t = TMesh<mesh_fes_t>;

   // Static solution finite element space type
   using sol_fe_t = H1_FiniteElement<geom,sol_p>;
   using sol_fes_t = H1_FiniteElementSpace<sol_fe_t>;

   // Static quadrature, coefficient and integrator types
   using int_rule_t = TIntegrationRule<geom,ir_order>;
   using coeff_t = TConstantCoefficient<>;
   using integ_t = TIntegrator<coeff_t,TDiffusionKernel>;

   using HPCBilinearForm = TBilinearForm<mesh_t,sol_fes_t,int_rule_t,integ_t>;

   static int run(Mesh *mesh, int ref_levels, int order, int basis,
                  bool static_cond, PCType pc_choice, bool perf,
                  bool matrix_free, bool visualization);
};

int main(int argc, char *argv[])
{
   // 1. Parse command-line options.
   const char *mesh_file = "../../data/fichera.mesh";
   int ref_levels = -1;
   int order = sol_p;
   const char *basis_type = "G"; // Gauss-Lobatto
   bool static_cond = false;
   const char *pc = "none";
   bool perf = true;
   bool matrix_free = true;
   bool visualization = 1;

   OptionsParser args(argc, argv);
   args.AddOption(&mesh_file, "-m", "--mesh",
                  "Mesh file to use.");
   args.AddOption(&ref_levels, "-r", "--refine",
                  "Number of times to refine the mesh uniformly;"
                  " -1 = auto: <= 50,000 elements.");
   args.AddOption(&order, "-o", "--order",
                  "Finite element order (polynomial degree) or -1 for"
                  " isoparametric space.");
   args.AddOption(&basis_type, "-b", "--basis-type",
                  "Basis: G - Gauss-Lobatto, P - Positive, U - Uniform");
   args.AddOption(&perf, "-perf", "--hpc-version", "-std", "--standard-version",
                  "Enable high-performance, tensor-based, assembly/evaluation.");
   args.AddOption(&matrix_free, "-mf", "--matrix-free", "-asm", "--assembly",
                  "Use matrix-free evaluation or efficient matrix assembly in "
                  "the high-performance version.");
   args.AddOption(&pc, "-pc", "--preconditioner",
                  "Preconditioner: lor - low-order-refined (matrix-free) GS, "
                  "ho - high-order (assembled) GS, none.");
   args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
                  "--no-static-condensation", "Enable static condensation.");
   args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
                  "--no-visualization",
                  "Enable or disable GLVis visualization.");
   args.Parse();
   if (!args.Good())
   {
      args.PrintUsage(cout);
      return 1;
   }
   if (static_cond && perf && matrix_free)
   {
      cout << "\nStatic condensation can not be used with matrix-free"
           " evaluation!\n" << endl;
      return 2;
   }
   MFEM_VERIFY(perf || !matrix_free,
               "--standard-version is not compatible with --matrix-free");
   args.PrintOptions(cout);

   PCType pc_choice;
   if (!strcmp(pc, "ho")) { pc_choice = PCType::HO; }
   else if (!strcmp(pc, "lor")) { pc_choice = PCType::LOR; }
   else if (!strcmp(pc, "none")) { pc_choice = PCType::NONE; }
   else
   {
      mfem_error("Invalid Preconditioner specified");
      return 3;
   }

   cout << "\nMFEM SIMD width: " << MFEM_SIMD_BYTES/sizeof(double)
        << " doubles\n" << endl;

   // See class BasisType in fem/fe_coll.hpp for available basis types
   int basis = BasisType::GetType(basis_type[0]);
   cout << "Using " << BasisType::Name(basis) << " basis ..." << endl;

   // 2. Read the mesh from the given mesh file. We can handle triangular,
   //    quadrilateral, tetrahedral, hexahedral, surface and volume meshes with
   //    the same code.
   Mesh *mesh = new Mesh(mesh_file, 1, 1);
   int dim = mesh->Dimension();

   if (dim == 2)
   {
      return ex1_t<2>::run(mesh, ref_levels, order, basis, static_cond,
                           pc_choice, perf, matrix_free, visualization);
   }
   else if (dim == 3)
   {
      return ex1_t<3>::run(mesh, ref_levels, order, basis, static_cond,
                           pc_choice, perf, matrix_free, visualization);
   }
   else
   {
      MFEM_ABORT("Dimension must be 2 or 3.")
   }

   return 0;
}

template <int dim>
int ex1_t<dim>::run(Mesh *mesh, int ref_levels, int order, int basis,
                    bool static_cond, PCType pc_choice, bool perf,
                    bool matrix_free, bool visualization)
{
   // 3. Check if the optimized version matches the given mesh
   if (perf)
   {
      cout << "High-performance version using integration rule with "
           << int_rule_t::qpts << " points ..." << endl;
      if (!mesh_t::MatchesGeometry(*mesh))
      {
         cout << "The given mesh does not match the optimized 'geom' parameter.\n"
              << "Recompile with suitable 'geom' value." << endl;
         delete mesh;
         return 4;
      }
      else if (!mesh_t::MatchesNodes(*mesh))
      {
         cout << "Switching the mesh curvature to match the "
              << "optimized value (order " << mesh_p << ") ..." << endl;
         mesh->SetCurvature(mesh_p, false, -1, Ordering::byNODES);
      }
   }

   // 4. Refine the mesh to increase the resolution. In this example we do
   //    'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
   //    largest number that gives a final mesh with no more than 50,000
   //    elements, or as specified on the command line with the option
   //    '--refine'.
   {
      ref_levels = (ref_levels != -1) ? ref_levels :
                   (int)floor(log(50000./mesh->GetNE())/log(2.)/dim);
      for (int l = 0; l < ref_levels; l++)
      {
         mesh->UniformRefinement();
      }
   }
   if (mesh->MeshGenerator() & 1) // simplex mesh
   {
      MFEM_VERIFY(pc_choice != PCType::LOR, "triangle and tet meshes do not "
                  " support the LOR preconditioner yet");
   }

   // 5. Define a finite element space on the mesh. Here we use continuous
   //    Lagrange finite elements of the specified order. If order < 1, we
   //    instead use an isoparametric/isogeometric space.
   FiniteElementCollection *fec;
   if (order > 0)
   {
      fec = new H1_FECollection(order, dim, basis);
   }
   else if (mesh->GetNodes())
   {
      fec = mesh->GetNodes()->OwnFEC();
      cout << "Using isoparametric FEs: " << fec->Name() << endl;
   }
   else
   {
      fec = new H1_FECollection(order = 1, dim, basis);
   }
   FiniteElementSpace *fespace = new FiniteElementSpace(mesh, fec);
   cout << "Number of finite element unknowns: "
        << fespace->GetTrueVSize() << endl;

   // Create the LOR mesh and finite element space. In the settings of this
   // example, we can transfer between HO and LOR with the identity operator.
   Mesh mesh_lor;
   FiniteElementCollection *fec_lor = NULL;
   FiniteElementSpace *fespace_lor = NULL;
   if (pc_choice == PCType::LOR)
   {
      int basis_lor = basis;
      if (basis == BasisType::Positive) { basis_lor=BasisType::ClosedUniform; }
      mesh_lor = Mesh::MakeRefined(*mesh, order, basis_lor);
      fec_lor = new H1_FECollection(1, dim);
      fespace_lor = new FiniteElementSpace(&mesh_lor, fec_lor);
   }

   // 6. Check if the optimized version matches the given space
   if (perf && !sol_fes_t::Matches(*fespace))
   {
      cout << "The given order does not match the optimized parameter.\n"
           << "Recompile with suitable 'sol_p' value." << endl;
      delete fespace;
      delete fec;
      delete mesh;
      return 5;
   }

   // 7. Determine the list of true (i.e. conforming) essential boundary dofs.
   //    In this example, the boundary conditions are defined by marking all
   //    the boundary attributes from the mesh as essential (Dirichlet) and
   //    converting them to a list of true dofs.
   Array<int> ess_tdof_list;
   if (mesh->bdr_attributes.Size())
   {
      Array<int> ess_bdr(mesh->bdr_attributes.Max());
      ess_bdr = 1;
      fespace->GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
   }

   // 8. Set up the linear form b(.) which corresponds to the right-hand side of
   //    the FEM linear system, which in this case is (1,phi_i) where phi_i are
   //    the basis functions in the finite element fespace.
   LinearForm *b = new LinearForm(fespace);
   ConstantCoefficient one(1.0);
   b->AddDomainIntegrator(new DomainLFIntegrator(one));
   b->Assemble();

   // 9. Define the solution vector x as a finite element grid function
   //    corresponding to fespace. Initialize x with initial guess of zero,
   //    which satisfies the boundary conditions.
   GridFunction x(fespace);
   x = 0.0;

   // 10. Set up the bilinear form a(.,.) on the finite element space that will
   //     hold the matrix corresponding to the Laplacian operator -Delta.
   //     Optionally setup a form to be assembled for preconditioning (a_pc).
   BilinearForm *a = new BilinearForm(fespace);
   BilinearForm *a_pc = NULL;
   if (pc_choice == PCType::LOR) { a_pc = new BilinearForm(fespace_lor); }
   if (pc_choice == PCType::HO)  { a_pc = new BilinearForm(fespace); }

   // 11. Assemble the bilinear form and the corresponding linear system,
   //     applying any necessary transformations such as: eliminating boundary
   //     conditions, applying conforming constraints for non-conforming AMR,
   //     static condensation, etc.
   if (static_cond)
   {
      a->EnableStaticCondensation();
      MFEM_VERIFY(pc_choice != PCType::LOR,
                  "cannot use LOR preconditioner with static condensation");
   }

   cout << "Assembling the bilinear form ..." << flush;
   tic_toc.Clear();
   tic_toc.Start();
   // Pre-allocate sparsity assuming dense element matrices
   a->UsePrecomputedSparsity();

   HPCBilinearForm *a_hpc = NULL;
   Operator *a_oper = NULL;

   if (!perf)
   {
      // Standard assembly using a diffusion domain integrator
      a->AddDomainIntegrator(new DiffusionIntegrator(one));
      a->Assemble();
   }
   else
   {
      // High-performance assembly/evaluation using the templated operator type
      a_hpc = new HPCBilinearForm(integ_t(coeff_t(1.0)), *fespace);
      if (matrix_free)
      {
         a_hpc->Assemble(); // partial assembly
      }
      else
      {
         a_hpc->AssembleBilinearForm(*a); // full matrix assembly
      }
   }
   tic_toc.Stop();
   cout << " done, " << tic_toc.RealTime() << "s." << endl;

   // 12. Solve the system A X = B with CG. In the standard case, use a simple
   //     symmetric Gauss-Seidel preconditioner.

   // Setup the operator matrix (if applicable)
   SparseMatrix A;
   Vector B, X;
   if (perf && matrix_free)
   {
      a_hpc->FormLinearSystem(ess_tdof_list, x, *b, a_oper, X, B);
      cout << "Size of linear system: " << a_hpc->Height() << endl;
   }
   else
   {
      a->FormLinearSystem(ess_tdof_list, x, *b, A, X, B);
      cout << "Size of linear system: " << A.Height() << endl;
      a_oper = &A;
   }

   // Setup the matrix used for preconditioning
   cout << "Assembling the preconditioning matrix ..." << flush;
   tic_toc.Clear();
   tic_toc.Start();

   SparseMatrix A_pc;
   if (pc_choice == PCType::LOR)
   {
      // TODO: assemble the LOR matrix using the performance code
      a_pc->AddDomainIntegrator(new DiffusionIntegrator(one));
      a_pc->UsePrecomputedSparsity();
      a_pc->Assemble();
      a_pc->FormSystemMatrix(ess_tdof_list, A_pc);
   }
   else if (pc_choice == PCType::HO)
   {
      if (!matrix_free)
      {
         A_pc.MakeRef(A); // matrix already assembled, reuse it
      }
      else
      {
         a_pc->UsePrecomputedSparsity();
         a_hpc->AssembleBilinearForm(*a_pc);
         a_pc->FormSystemMatrix(ess_tdof_list, A_pc);
      }
   }

   tic_toc.Stop();
   cout << " done, " << tic_toc.RealTime() << "s." << endl;

   // Solve with CG or PCG, depending if the matrix A_pc is available
   if (pc_choice != PCType::NONE)
   {
      GSSmoother M(A_pc);
      PCG(*a_oper, M, B, X, 1, 500, 1e-12, 0.0);
   }
   else
   {
      CG(*a_oper, B, X, 1, 500, 1e-12, 0.0);
   }

   // 13. Recover the solution as a finite element grid function.
   if (perf && matrix_free)
   {
      a_hpc->RecoverFEMSolution(X, *b, x);
   }
   else
   {
      a->RecoverFEMSolution(X, *b, x);
   }

   // 14. Save the refined mesh and the solution. This output can be viewed later
   //     using GLVis: "glvis -m refined.mesh -g sol.gf".
   ofstream mesh_ofs("refined.mesh");
   mesh_ofs.precision(8);
   mesh->Print(mesh_ofs);
   ofstream sol_ofs("sol.gf");
   sol_ofs.precision(8);
   x.Save(sol_ofs);

   // 15. Send the solution by socket to a GLVis server.
   if (visualization)
   {
      char vishost[] = "localhost";
      int  visport   = 19916;
      socketstream sol_sock(vishost, visport);
      sol_sock.precision(8);
      sol_sock << "solution\n" << *mesh << x << flush;
   }

   // 16. Free the used memory.
   delete a;
   delete a_hpc;
   if (a_oper != &A) { delete a_oper; }
   delete a_pc;
   delete b;
   delete fespace;
   delete fespace_lor;
   delete fec_lor;
   if (order > 0) { delete fec; }
   delete mesh;

   return 0;
}


text:
package org.vertexium.query;

import org.vertexium.Authorizations;
import org.vertexium.VertexiumObject;

public interface QueryableIterable<T extends VertexiumObject> extends Iterable<T> {
    /**
     * Creates a query for this iterable.
     *
     * @param authorizations The authorizations used to find the edges and vertices.
     * @return The query builder.
     */
    Query query(Authorizations authorizations);

    /**
     * Creates a query for this iterable.
     *
     * @param queryString    The string to search for.
     * @param authorizations The authorizations used to find the edges and vertices.
     * @return The query builder.
     */
    Query query(String queryString, Authorizations authorizations);
}


text:
#import <Foundation/NSArchiver.h>
#import <Foundation/NSRaise.h>
#import <Foundation/NSMutableData.h>
#import <Foundation/NSMutableDictionary.h>
#import <Foundation/NSByteOrder.h>
#import <string.h>

@implementation NSArchiver

-init {
   _data=[NSMutableData new];
   _bytes=[_data mutableBytes];
   _position=0;
   _pass=0;

   _conditionals=NSCreateHashTable(NSNonOwnedPointerHashCallBacks,0);
   _objects=NSCreateHashTable(NSNonOwnedPointerHashCallBacks,0);
   _classes=NSCreateHashTable(NSNonOwnedPointerHashCallBacks,0);
   _cStrings=NSCreateHashTable(NSObjectHashCallBacks,0);

   return self;
}

-(void)dealloc {
   [_data release];
   NSFreeHashTable(_conditionals);
   NSFreeHashTable(_objects);
   NSFreeHashTable(_classes);
   NSFreeHashTable(_cStrings);
   [super dealloc];
}

-(NSData *)data {
   return [[_data copy] autorelease];
}

+(NSData *)archivedDataWithRootObject:(id)rootObject {
   NSArchiver *archiver=[[[self allocWithZone:NULL] init] autorelease];

   [archiver encodeRootObject:rootObject];
   return [archiver data];
}

+(BOOL)archiveRootObject:rootObject toFile:(NSString *)path {
   NSData *data=[self archivedDataWithRootObject:rootObject];

   return [data writeToFile:path atomically:YES];
}

-(NSMutableData *)archiverData {
   return _data;
}

-(void)cannotEncodeType:(const char *)type {
   [NSException raise:@"NSArchiverCannotEncodeException"
               format:@"NSArchiver cannot encode type=%s",type];
}

-(void)_ensureLength:(NSUInteger)length {
   [_data setLength:[_data length]+length];
   _bytes=[_data mutableBytes];
}

-(void)_appendData:(NSData *)data {
   if(_pass==0)
    return;

   [_data appendData:data];
   _bytes=[_data mutableBytes];
   _position=[_data length];
}

-(void)_appendWordOne:(uint8_t)value {
   if(_pass==0)
    return;

   [self _ensureLength:1];
   _bytes[_position++]=value;
}

-(void)_appendWordTwo:(uint16_t)value {
   if(_pass==0)
    return;

   [self _ensureLength:2];
   _bytes[_position++]=(value>>8)&0xFF;
   _bytes[_position++]=value&0xFF;
}

-(void)_appendWordFour:(uint32_t)value {
   if(_pass==0)
    return;

   [self _ensureLength:4];
   _bytes[_position++]=(value>>24)&0xFF;
   _bytes[_position++]=(value>>16)&0xFF;
   _bytes[_position++]=(value>>8)&0xFF;
   _bytes[_position++]=value&0xFF;
}

-(void)_appendFloat:(float)value {
   [self _appendWordFour:NSConvertHostFloatToSwapped(value).floatWord];
}

-(void)_appendWordEight:(uint64_t)value {
   if(_pass==0)
    return;

   [self _ensureLength:8];
   _bytes[_position++]=(value>>56)&0xFF;
   _bytes[_position++]=(value>>48)&0xFF;
   _bytes[_position++]=(value>>40)&0xFF;
   _bytes[_position++]=(value>>32)&0xFF;
   _bytes[_position++]=(value>>24)&0xFF;
   _bytes[_position++]=(value>>16)&0xFF;
   _bytes[_position++]=(value>>8)&0xFF;
   _bytes[_position++]=value&0xFF;
}

-(void)_appendBytes:(const uint8_t *)bytes length:(NSUInteger)length {
   int i;

   if(_pass==0)
    return;

   [self _ensureLength:length];
   for(i=0;i<length;i++)
    _bytes[_position++]=bytes[i];
}

-(void)_appendCStringBytes:(const char *)cString {
   [self _ensureLength:strlen(cString)+1];

   for(;*cString!='\0';cString++)
    _bytes[_position++]=*cString;

   _bytes[_position++]='\0';
}

-(void)_appendCString:(const char *)cString {
   NSString *string,*lookup;

   if(_pass==0)
    return;

   //NSLog(@"cString=%s",cString);
   string=[NSString stringWithCString:cString];
   //NSLog(@"string=%@",string);

   if((lookup=NSHashGet(_cStrings,string))!=nil)
    [self _appendWordFour:(unsigned)lookup];
   else {
    NSHashInsert(_cStrings,string);

    [self _appendWordFour:(unsigned)string];
    [self _appendCStringBytes:[string cString]];
   }
}

-(void)_appendClassVersion:(Class)class {
   if(class==[NSObject class]){
    [self _appendWordFour:0];
    return;
   }

   [self _appendWordFour:(unsigned)class];

   if(NSHashGet(_classes,class)==NULL){
    NSHashInsert(_classes,class);
    [self _appendCString:[NSStringFromClass(class) cString]];
    [self _appendWordFour:[class version]];
    [self _appendClassVersion:[class superclass]];
   }
}

-(void)_appendObject:(id)object conditional:(BOOL)conditional {
   if(_pass==0){

    if(object!=nil){
     //NSLog(@"%@ conditional=%s", NSStringFromClass([object class]) ,conditional?"YES":"NO");

     if(!conditional){
      if(NSHashGet(_conditionals,object)==NULL){
       NSHashInsert(_conditionals,object);
       [object encodeWithCoder:self];
      }
     }
    }

   }
   else {
    if(conditional && (NSHashGet(_conditionals,object)==NULL))
     object=nil;

    if(object==nil)
     [self _appendWordFour:0];
    else if(NSHashGet(_objects,object)!=NULL)
     [self _appendWordFour:(unsigned)object];
    else { // FIX do replacementForCoder ?
     Class class=[object classForArchiver];

     NSHashInsert(_objects,object);

     [self _appendWordFour:(unsigned)object];
     [self _appendClassVersion:class];

     [object encodeWithCoder:self];
    }
   }
}

-(void)_appendArrayOfObjCType:(const char *)type length:(NSUInteger)length
  at:(const void *)addr {

   if(_pass==0)
    return;

   switch(*type){
    case 'c':
    case 'C':{
      const unsigned char *values=addr;
      NSInteger i;

      for(i=0;i<length;i++)
       [self _appendWordOne:values[i]];
     }
     break;

    case 's':
    case 'S':{
      const unsigned short *values=addr;
      NSInteger i;

      for(i=0;i<length;i++)
       [self _appendWordTwo:values[i]];
     }
     break;

    default:
     [self cannotEncodeType:type];
     break;
   }
}

-(void)encodeValueOfObjCType:(const char *)type at:(const void *)addr {
   //NSLog(@"type=%s",type);

   [self _appendCString:type];

   switch(*type){
    case 'c':
    case 'C':{
      unsigned char value=*(const unsigned char *)addr;
      [self _appendWordOne:value];
     }
     break;

    case 's':
    case 'S':{
      unsigned short value=*(const unsigned short *)addr;
      [self _appendWordTwo:value];
     }
     break;

    case 'i':
    case 'I':{
      unsigned int value=*(const unsigned int *)addr;
      [self _appendWordFour:value];
     }
     break;

    case 'l':
    case 'L':{
      unsigned long value=*(const unsigned long *)addr;
      [self _appendWordFour:value];
     }
     break;

    case 'q':
    case 'Q':{
      unsigned long long value=*(const unsigned long long *)addr;
      [self _appendWordEight:value];
     }
     break;

    case 'f':{
      float value=*(const float *)addr;
      [self _appendFloat:value];
     }
     break;

    case 'd':{
      double value=*(const double *)addr;
      [self _appendWordEight:NSConvertHostDoubleToSwapped(value).doubleWord];
     }
     break;

    case '*':{
      const char * const *cString=addr;

      [self _appendCString:*cString];
     }
     break;

    case '@':{
      id object=*(const id *)addr;

      [self _appendObject:object conditional:NO];
     }
     break;

    case '#':
     [self cannotEncodeType:type];
     break;

    case ':':{
      SEL selector=*(const SEL *)addr;

      [self _appendCString:sel_getName(selector)];
     }
     break;

    case '[':{
      const char *tmp=type;
      unsigned    length=0;

      tmp++; // skip [
      for(;*tmp>='0' && *tmp<='9';tmp++)
       length=(length*10)+(*tmp-'0');

      [self _appendArrayOfObjCType:tmp length:length at:addr];
     }
     break;

    case '{': // this is extremely lame
     if(strcmp(type,@encode(NSRange))==0){
      NSRange value=*(const NSRange *)addr;

      [self _appendWordFour:value.location];
      [self _appendWordFour:value.length];
      break;
     }
     if(strcmp(type,@encode(NSPoint))==0){
      NSPoint value=*(const NSPoint *)addr;

      [self _appendFloat:value.x];
      [self _appendFloat:value.y];
      break;
     }
     if(strcmp(type,@encode(NSSize))==0){
      NSSize value=*(const NSSize *)addr;

      [self _appendFloat:value.width];
      [self _appendFloat:value.height];
      break;
     }
     if(strcmp(type,@encode(NSRect))==0){
      NSRect value=*(const NSRect *)addr;

      [self _appendFloat:value.origin.x];
      [self _appendFloat:value.origin.y];
      [self _appendFloat:value.size.width];
      [self _appendFloat:value.size.height];
      break;
     }
     [self cannotEncodeType:type];
     break;

    case '(':
    case 'b':
    case '^':
    case '?':
    default:
     [self cannotEncodeType:type];
     break;
   }

}

-(void)encodeBytes:(const void *)byteaddr length:(NSUInteger)length {
   [self _appendWordFour:length];
   [self _appendBytes: byteaddr length:length];
}

-(void)encodeDataObject:(NSData *)data {
   [self cannotEncodeType:"encodeDataObject"];
}

-(void)encodeRootObject:(id)rootObject {
   _position=0;
   _pass=0;
   [self _appendObject:rootObject conditional:NO];
   if(_position!=0)
    NSLog(@"_position=%d",_position);

   if(NSHashGet(_conditionals,rootObject)==NULL)
    NSLog(@"rootObject not in conditionals");

   _position=0;
   _pass=1;
   [self _appendCStringBytes:"~V1~"];
   [self _appendWordFour:0]; // archive version

   [self _appendCString:"@"];
   [self _appendObject:rootObject conditional: NO];
}

-(void)encodeConditionalObject:(id)object {
   [self _appendCString:"@"];
   [self _appendObject:object conditional:YES];
}

-(void)encodeClassName:(NSString *)runtime intoClassName:(NSString *)archive {
   NSUnimplementedMethod();
}

-(void)replaceObject:original withObject:replacement {
   NSUnimplementedMethod();
}

@end


text:
using Avalonia.Controls;

namespace Avalonia.Layout.UnitTests
{
    internal class TestLayoutRoot : Decorator, ILayoutRoot
    {
        public TestLayoutRoot()
        {
            ClientSize = new Size(500, 500);
        }

        public Size ClientSize
        {
            get;
            set;
        }

        public Size MaxClientSize => Size.Infinity;
        public double LayoutScaling => 1;
    }
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.camunda.bpm.engine.test.history;

import static org.junit.Assert.assertEquals;

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

import org.apache.commons.lang.time.DateUtils;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.ProcessEngineConfiguration;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.exception.NotValidException;
import org.camunda.bpm.engine.history.CleanableHistoricProcessInstanceReport;
import org.camunda.bpm.engine.history.CleanableHistoricProcessInstanceReportResult;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.RequiredHistoryLevel;
import org.camunda.bpm.engine.test.util.ProcessEngineTestRule;
import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;

@RequiredHistoryLevel(ProcessEngineConfiguration.HISTORY_FULL)
public class CleanableHistoricProcessInstanceReportTest {
  public ProcessEngineRule engineRule = new ProvidedProcessEngineRule();
  public ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule);

  @Rule
  public RuleChain ruleChain = RuleChain.outerRule(testRule).around(engineRule);

  protected ProcessEngineConfiguration processEngineConfiguration;
  protected HistoryService historyService;
  protected TaskService taskService;
  protected RepositoryService repositoryService;
  protected RuntimeService runtimeService;

  protected static final String PROCESS_DEFINITION_KEY = "HISTORIC_INST";
  protected static final String SECOND_PROCESS_DEFINITION_KEY = "SECOND_HISTORIC_INST";
  protected static final String THIRD_PROCESS_DEFINITION_KEY = "THIRD_HISTORIC_INST";
  protected static final String FOURTH_PROCESS_DEFINITION_KEY = "FOURTH_HISTORIC_INST";

  @Before
  public void setUp() {
    historyService = engineRule.getHistoryService();
    processEngineConfiguration = engineRule.getProcessEngineConfiguration();
    taskService = engineRule.getTaskService();
    repositoryService = engineRule.getRepositoryService();
    runtimeService = engineRule.getRuntimeService();

    testRule.deploy(createProcessWithUserTask(PROCESS_DEFINITION_KEY));
  }

  @After
  public void cleanUp() {
    List<Task> list = taskService.createTaskQuery().list();
    for (Task task : list) {
      taskService.deleteTask(task.getId(), true);
    }

    List<HistoricProcessInstance> historicProcessInstances = historyService.createHistoricProcessInstanceQuery().list();
    for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
      historyService.deleteHistoricProcessInstance(historicProcessInstance.getId());
    }
  }

  protected BpmnModelInstance createProcessWithUserTask(String key) {
    return Bpmn.createExecutableProcess(key)
        .startEvent()
        .userTask(key + "_task1")
          .name(key + " Task 1")
        .endEvent()
        .done();
  }

  protected void prepareProcessInstances(String key, int daysInThePast, Integer historyTimeToLive, int instanceCount) {
    List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().processDefinitionKey(key).list();
    assertEquals(1, processDefinitions.size());
    repositoryService.updateProcessDefinitionHistoryTimeToLive(processDefinitions.get(0).getId(), historyTimeToLive);

    Date oldCurrentTime = ClockUtil.getCurrentTime();
    ClockUtil.setCurrentTime(DateUtils.addDays(oldCurrentTime, daysInThePast));

    List<String> processInstanceIds = new ArrayList<String>();
    for (int i = 0; i < instanceCount; i++) {
      ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(key);
      processInstanceIds.add(processInstance.getId());
    }
    runtimeService.deleteProcessInstances(processInstanceIds, null, true, true);

    ClockUtil.setCurrentTime(oldCurrentTime);
  }

  @Test
  public void testReportComplex() {
    testRule.deploy(createProcessWithUserTask(SECOND_PROCESS_DEFINITION_KEY));
    testRule.deploy(createProcessWithUserTask(THIRD_PROCESS_DEFINITION_KEY));
    testRule.deploy(createProcessWithUserTask(FOURTH_PROCESS_DEFINITION_KEY));
    // given
    prepareProcessInstances(PROCESS_DEFINITION_KEY, 0, 5, 10);
    prepareProcessInstances(PROCESS_DEFINITION_KEY, -6, 5, 10);
    prepareProcessInstances(SECOND_PROCESS_DEFINITION_KEY, -6, 5, 10);
    prepareProcessInstances(THIRD_PROCESS_DEFINITION_KEY, -6, null, 10);
    prepareProcessInstances(FOURTH_PROCESS_DEFINITION_KEY, -6, 0, 10);

    repositoryService.deleteProcessDefinition(
        repositoryService.createProcessDefinitionQuery().processDefinitionKey(SECOND_PROCESS_DEFINITION_KEY).singleResult().getId(), false);

    // when
    List<CleanableHistoricProcessInstanceReportResult> reportResults = historyService.createCleanableHistoricProcessInstanceReport().list();
    CleanableHistoricProcessInstanceReportResult secondReportResult = historyService.createCleanableHistoricProcessInstanceReport().processDefinitionIdIn(repositoryService.createProcessDefinitionQuery().processDefinitionKey(THIRD_PROCESS_DEFINITION_KEY).singleResult().getId()).singleResult();
    CleanableHistoricProcessInstanceReportResult thirdReportResult = historyService.createCleanableHistoricProcessInstanceReport().processDefinitionKeyIn(FOURTH_PROCESS_DEFINITION_KEY).singleResult();

    // then
    assertEquals(3, reportResults.size());
    for (CleanableHistoricProcessInstanceReportResult result : reportResults) {
      if (result.getProcessDefinitionKey().equals(PROCESS_DEFINITION_KEY)) {
        checkResultNumbers(result, 10, 20);
      } else if (result.getProcessDefinitionKey().equals(THIRD_PROCESS_DEFINITION_KEY)) {
        checkResultNumbers(result, 0, 10);
      } else if (result.getProcessDefinitionKey().equals(FOURTH_PROCESS_DEFINITION_KEY)) {
        checkResultNumbers(result, 10, 10);
      }
    }
    checkResultNumbers(secondReportResult, 0, 10);
    checkResultNumbers(thirdReportResult, 10, 10);
  }

  private void checkResultNumbers(CleanableHistoricProcessInstanceReportResult result, int expectedCleanable, int expectedFinished) {
    assertEquals(expectedCleanable, result.getCleanableProcessInstanceCount());
    assertEquals(expectedFinished, result.getFinishedProcessInstanceCount());
  }

  @Test
  public void testReportWithAllCleanableInstances() {
    // given
    prepareProcessInstances(PROCESS_DEFINITION_KEY, -6, 5, 10);

    // when
    List<CleanableHistoricProcessInstanceReportResult> reportResults = historyService.createCleanableHistoricProcessInstanceReport().list();
    long count = historyService.createCleanableHistoricProcessInstanceReport().count();

    // then
    assertEquals(1, reportResults.size());
    assertEquals(1, count);

    checkResultNumbers(reportResults.get(0), 10, 10);
  }

  @Test
  public void testReportWithPartiallyCleanableInstances() {
    // given
    prepareProcessInstances(PROCESS_DEFINITION_KEY, -6, 5, 5);
    prepareProcessInstances(PROCESS_DEFINITION_KEY, 0, 5, 5);

    // when
    List<CleanableHistoricProcessInstanceReportResult> reportResults = historyService.createCleanableHistoricProcessInstanceReport().list();

    // then
    assertEquals(1, reportResults.size());

    checkResultNumbers(reportResults.get(0), 5, 10);
  }

  @Test
  public void testReportWithZeroHistoryTTL() {
    // given
    prepareProcessInstances(PROCESS_DEFINITION_KEY, -6, 0, 5);
    prepareProcessInstances(PROCESS_DEFINITION_KEY, 0, 0, 5);

    // when
    CleanableHistoricProcessInstanceReportResult result = historyService.createCleanableHistoricProcessInstanceReport().singleResult();

    // then
    checkResultNumbers(result, 10, 10);
  }

  @Test
  public void testReportWithNullHistoryTTL() {
    // given
    prepareProcessInstances(PROCESS_DEFINITION_KEY, -6, null, 5);
    prepareProcessInstances(PROCESS_DEFINITION_KEY, 0, null, 5);

    // when
    List<CleanableHistoricProcessInstanceReportResult> reportResults = historyService.createCleanableHistoricProcessInstanceReport().list();

    // then
    assertEquals(1, reportResults.size());

    checkResultNumbers(reportResults.get(0), 0, 10);
  }

  @Test
  public void testReportByInvalidProcessDefinitionId() {
    CleanableHistoricProcessInstanceReport report = historyService.createCleanableHistoricProcessInstanceReport();

    try {
      report.processDefinitionIdIn((String) null);
    } catch (NotValidException e) {
    }

    try {
      report.processDefinitionIdIn("abc", (String) null, "def");
    } catch (NotValidException e) {
    }
  }

  public void testReportByInvalidProcessDefinitionKey() {
    CleanableHistoricProcessInstanceReport report = historyService.createCleanableHistoricProcessInstanceReport();

    try {
      report.processDefinitionKeyIn((String) null);
    } catch (NotValidException e) {
    }

    try {
      report.processDefinitionKeyIn("abc", (String) null, "def");
    } catch (NotValidException e) {
    }
  }
}


text:
function __processArg(obj, key) {
    var arg = null;
    if (obj) {
        arg = obj[key] || null;
        delete obj[key];
    }
    return arg;
}

function Controller() {
    function doOpen(e) {
        var actionBar = e.source.activity.actionBar;
        if (actionBar) {
            actionBar.displayHomeAsUp = true;
            actionBar.onHomeIconItemSelected = function() {
                e.source.close();
            };
            e.source.activity.invalidateOptionsMenu();
        }
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "contact";
    if (arguments[0]) {
        {
            __processArg(arguments[0], "__parentSymbol");
        }
        {
            __processArg(arguments[0], "$model");
        }
        {
            __processArg(arguments[0], "__itemTemplate");
        }
    }
    var $ = this;
    var exports = {};
    var __defers = {};
    $.__views.contact = Ti.UI.createWindow({
        backgroundColor: "#fff",
        id: "contact",
        title: "Contact Us"
    });
    $.__views.contact && $.addTopLevelView($.__views.contact);
    doOpen ? $.__views.contact.addEventListener("open", doOpen) : __defers["$.__views.contact!open!doOpen"] = true;
    $.__views.__alloyId1 = Ti.UI.createLabel({
        color: "#600",
        text: "Please feel free to contact us if you are interested or have any questions!",
        top: "15",
        center: "0",
        id: "__alloyId1"
    });
    $.__views.contact.add($.__views.__alloyId1);
    $.__views.textField1 = Ti.UI.createTextArea({
        id: "textField1",
        hintText: "First Name",
        top: "65",
        center: "0",
        width: "75%",
        height: "40"
    });
    $.__views.contact.add($.__views.textField1);
    $.__views.textField2 = Ti.UI.createTextArea({
        id: "textField2",
        hintText: "Last Name",
        top: "105",
        center: "0",
        width: "75%",
        height: "40"
    });
    $.__views.contact.add($.__views.textField2);
    $.__views.textField3 = Ti.UI.createTextArea({
        id: "textField3",
        hintText: "Emai Address",
        top: "145",
        center: "0",
        width: "75%",
        height: "40"
    });
    $.__views.contact.add($.__views.textField3);
    $.__views.textField4 = Ti.UI.createTextArea({
        id: "textField4",
        hintText: "Phone Number",
        top: "185",
        center: "0",
        width: "75%",
        height: "40"
    });
    $.__views.contact.add($.__views.textField4);
    $.__views.submit = Ti.UI.createButton({
        id: "submit",
        title: "Submit",
        bottom: "150"
    });
    $.__views.contact.add($.__views.submit);
    exports.destroy = function() {};
    _.extend($, $.__views);
    arguments[0] || {};
    $.contact.open();
    __defers["$.__views.contact!open!doOpen"] && $.__views.contact.addEventListener("open", doOpen);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
import numpy as np
import cv2
from common import draw_str

# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

# Change thresholds
params.minThreshold = 10;
params.maxThreshold = 200;

# Filter by Area.
params.filterByArea = True
params.maxArea = 1500

# Filter by Circularity
params.filterByCircularity = True
params.minCircularity = 0.1

# Filter by Convexity
params.filterByConvexity = True
params.minConvexity = 0.9

# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.01

# Create a detector with the parameters
ver = (cv2.__version__).split('.')
if int(ver[0]) < 3 :
    detector = cv2.SimpleBlobDetector(params)
else :
    detector = cv2.SimpleBlobDetector_create(params)

cap = cv2.VideoCapture('test_video.3gp')

while(cap.isOpened()):
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    keypoints = detector.detect(frame)
    im_with_keypoints = cv2.drawKeypoints(frame, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

    numkey = len(keypoints)
    for i in range(numkey):
        draw_str(im_with_keypoints, (20, 20*(i+1)), '%4.4f,%4.4f' % (keypoints[i].pt[0],keypoints[i].pt[1]))

    cv2.imshow('frame',im_with_keypoints)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


text:
package org.nanocontainer.remoting.jmx;

import javax.management.DynamicMBean;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

/**
 * Core interface for generating ObjectName instances for a DynamicMBean.
 * @author Jörg Schaible
 * @since 1.0
 */
public interface ObjectNameFactory {

    /**
     * Create an ObjectName.
     * @param key The key of the component within PicoContainer.
     * @param mBean The instance of the DynamicMBean.
     * @return Returns the Object Name for the DynamicMBean.
     * @throws MalformedObjectNameException Thrown for an invalid part in the {@link ObjectName}.
     */
    ObjectName create(Object key, DynamicMBean mBean) throws MalformedObjectNameException;
}


text:
==========
## Web Design Weekly #245
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/l0jiKEj--TM/

==========

====
## Web Design Weekly #244
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/DD2E4zC6d-M/

==========

====
## Web Design Weekly #243
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/jXceZ_S9r3o/

==========

====
## Adding Google Analytics to your React Application
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/38LoJKxZTqE/

==========

====
## Web Design Weekly #242
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/d8qep_L5jBA/

==========

====
## Install Google Fonts
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/79YJn2YObL4/

==========
  1. [http://font.google.com](http://font.google.com)

====
## Integration and Comparison for ES6
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/Gbndkp8IrYo/

==========
  1. [http://www.ecmascript.org/docs.php](http://www.ecmascript.org/docs.php)

====
## Web Design Weekly #241
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/1oGOW0eiCdM/

==========

====
## Web Design Weekly #240
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/coaXUUNiSJM/

==========

====
## Integrate Stylelint Into Your Workflow For Better CSS
#### http://feedproxy.google.com/~r/WebDesignWeekly/~3/0Goz3oPQKic/

==========
  1. [http://stylelint.io/](http://stylelint.io/)

====


text:
package org.apache.commons.io.monitor;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadFactory;
import java.util.stream.Stream;

/**
 * A runnable that spawns a monitoring thread triggering any
 * registered {@link FileAlterationObserver} at a specified interval.
 *
 * @see FileAlterationObserver
 * @since 2.0
 */
public final class FileAlterationMonitor implements Runnable {

    private static final FileAlterationObserver[] EMPTY_ARRAY = {};

    private final long intervalMillis;
    private final List<FileAlterationObserver> observers = new CopyOnWriteArrayList<>();
    private Thread thread;
    private ThreadFactory threadFactory;
    private volatile boolean running;

    /**
     * Constructs a monitor with a default interval of 10 seconds.
     */
    public FileAlterationMonitor() {
        this(10_000);
    }

    /**
     * Constructs a monitor with the specified interval.
     *
     * @param intervalMillis The amount of time in milliseconds to wait between
     * checks of the file system.
     */
    public FileAlterationMonitor(final long intervalMillis) {
        this.intervalMillis = intervalMillis;
    }

    /**
     * Constructs a monitor with the specified interval and collection of observers.
     *
     * @param interval The amount of time in milliseconds to wait between
     * checks of the file system.
     * @param observers The collection of observers to add to the monitor.
     * @since 2.9.0
     */
    public FileAlterationMonitor(final long interval, final Collection<FileAlterationObserver> observers) {
        // @formatter:off
        this(interval,
            Optional
                .ofNullable(observers)
                .orElse(Collections.emptyList())
                .toArray(EMPTY_ARRAY)
        );
        // @formatter:on
    }

    /**
     * Constructs a monitor with the specified interval and set of observers.
     *
     * @param interval The amount of time in milliseconds to wait between
     * checks of the file system.
     * @param observers The set of observers to add to the monitor.
     */
    public FileAlterationMonitor(final long interval, final FileAlterationObserver... observers) {
        this(interval);
        if (observers != null) {
            Stream.of(observers).forEach(this::addObserver);
        }
    }

    /**
     * Adds a file system observer to this monitor.
     *
     * @param observer The file system observer to add
     */
    public void addObserver(final FileAlterationObserver observer) {
        if (observer != null) {
            observers.add(observer);
        }
    }

    /**
     * Returns the interval.
     *
     * @return the interval
     */
    public long getInterval() {
        return intervalMillis;
    }

    /**
     * Returns the set of {@link FileAlterationObserver} registered with
     * this monitor.
     *
     * @return The set of {@link FileAlterationObserver}
     */
    public Iterable<FileAlterationObserver> getObservers() {
        return observers;
    }

    /**
     * Removes a file system observer from this monitor.
     *
     * @param observer The file system observer to remove
     */
    public void removeObserver(final FileAlterationObserver observer) {
        if (observer != null) {
            observers.removeIf(observer::equals);
        }
    }

    /**
     * Runs this monitor.
     */
    @Override
    public void run() {
        while (running) {
            observers.forEach(FileAlterationObserver::checkAndNotify);
            if (!running) {
                break;
            }
            try {
                Thread.sleep(intervalMillis);
            } catch (final InterruptedException ignored) {
                // ignore
            }
        }
    }

    /**
     * Sets the thread factory.
     *
     * @param threadFactory the thread factory
     */
    public synchronized void setThreadFactory(final ThreadFactory threadFactory) {
        this.threadFactory = threadFactory;
    }

    /**
     * Starts monitoring.
     *
     * @throws Exception if an error occurs initializing the observer
     */
    public synchronized void start() throws Exception {
        if (running) {
            throw new IllegalStateException("Monitor is already running");
        }
        for (final FileAlterationObserver observer : observers) {
            observer.initialize();
        }
        running = true;
        if (threadFactory != null) {
            thread = threadFactory.newThread(this);
        } else {
            thread = new Thread(this);
        }
        thread.start();
    }

    /**
     * Stops monitoring.
     *
     * @throws Exception if an error occurs initializing the observer
     */
    public synchronized void stop() throws Exception {
        stop(intervalMillis);
    }

    /**
     * Stops monitoring.
     *
     * @param stopInterval the amount of time in milliseconds to wait for the thread to finish.
     * A value of zero will wait until the thread is finished (see {@link Thread#join(long)}).
     * @throws Exception if an error occurs initializing the observer
     * @since 2.1
     */
    public synchronized void stop(final long stopInterval) throws Exception {
        if (!running) {
            throw new IllegalStateException("Monitor is not running");
        }
        running = false;
        try {
            thread.interrupt();
            thread.join(stopInterval);
        } catch (final InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        for (final FileAlterationObserver observer : observers) {
            observer.destroy();
        }
    }
}


text:
package org.uberfire.client.workbench.events;

import org.uberfire.mvp.PlaceRequest;
import org.uberfire.workbench.events.UberFireEvent;

import static org.kie.soup.commons.validation.PortablePreconditions.checkNotNull;

/**
 * Created by Cristiano Nicolai.
 */
public abstract class AbstractPlaceEvent implements UberFireEvent {

    private final PlaceRequest place;

    public AbstractPlaceEvent(final PlaceRequest place) {
        checkNotNull("place",
                     place);
        this.place = place;
    }

    public PlaceRequest getPlace() {
        return place;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="tests/bootstrap.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
>

  <!-- Test suites to be run -->
  <testsuites>
    <testsuite name="restler">
      <directory suffix="Test.php">tests</directory>
    </testsuite>
  </testsuites>

  <!-- Filters for code coverage reporting -->
  <filter>
    <whitelist>
      <directory>./</directory>
      <exclude>
        <directory>./tests</directory>
        <directory>./vendor</directory>
      </exclude>
    </whitelist>
  </filter>

</phpunit>