text:
from itertools import chain

NOT_PRODUCED_BY_TUTTLE = "The existing resource has not been produced by tuttle"
USER_REQUEST = "User request"
PROCESS_HAS_FAILED = "The resource has been produced by a failing process"
NO_LONGER_CREATED = "Resource no longer created by the newer process"
NOT_SAME_INPUTS = "Resource was created with different inputs"
PROCESS_HAS_CHANGED = "Process code has changed"
PROCESSOR_HAS_CHANGED = "Processor has changed"
RESOURCE_HAS_CHANGED = "Resource depends on primary resource {} which has changed"
RESOURCE_INTEGRITY = "Resource has changed outside of tuttle"
NOT_SAME_OUTPUTS = "Other outputs from same process have changed"
DEPENDENCY_CHANGED = "Resource depends on {} which is not valid anymore"
BROTHER_INVALID = "Resource is created along with {} that is invalid"
BROTHER_MISSING = "Resource is created along with {} that is missing"
BROTHER_INTEGRITY = "Resource is created along with {} that have changed outside of tuttle"

# Is it a subscase of NOT_PRODUCED_BY_TUTTLE ?
MUST_CREATE_RESOURCE = "The former primary resource has to be created by tuttle"

class InvalidCollector:
    """ This class class collects the resources to invalidate and their reason, in order to display them to the user
    and remove them all at once.
    Resources can come from several workflows (eg the current and the previous one)
    """
    def __init__(self, previous_workflow):
        self._resources_and_reasons = []
        self._resources_urls = set()
        self._processes = []
        self._previous_processes = []
        self._previous_workflow = previous_workflow

    def iter_urls(self):
        for url in self._resources_urls:
            yield url

    def resource_invalid(self, url):
        return url in self._resources_urls

    def resources_to_invalidate(self):
        return self._resources_urls

    def something_to_invalidate(self):
        return self._resources_urls or self._previous_processes or self._processes

    def duration(self):
        all_processes = (process for process in chain(self._previous_processes, self._processes))
        duration_sum = sum( (process.end - process.start for process in all_processes if process.end is not None) )
        return int(duration_sum)

    def warn_remove_resoures(self):
        print("The following resources are not valid any more and will be removed :")
        for resource, reason in self._resources_and_reasons:
            print("* {} - {}".format(resource.url, reason))

    def remove_resources(self, workflow):
        for resource, reason in self._resources_and_reasons:
            # if resource is from the workflow, we know its availability
            # but we have to check existence if it comes from the previous workflow
            if (workflow.contains_resource(resource) and workflow.resource_available(resource.url)) \
                    or resource.exists():
                try:
                    resource.remove()
                except Exception as e:
                    msg = 'Warning : Removing resource {} has failed. Even if the resource is still available, ' \
                          'it should not be considered valid.'.format(resource.url)
                    print(msg)

    def reset_execution_info(self):
        for process in self._processes:
            process.reset_execution_info()

    def collect_resource(self, resource, reason):
        if resource.url not in self._resources_urls:
            self._resources_and_reasons.append((resource, reason))
            self._resources_urls.add(resource.url)

    def collect_prev_process_and_not_primary_outputs(self, new_workflow, prev_process, reason):
        for resource in prev_process.iter_outputs():
            new_resource = new_workflow.find_resource(resource.url)
            if not (new_resource and new_resource.is_primary()):
                self.collect_resource(resource, reason)
                # Should we check for availability ?
        self._previous_processes.append(prev_process)

    def collect_process_and_available_outputs(self, workflow, process, reason):
        for resource in process.iter_outputs():
            if workflow.resource_available(resource.url):
                self.collect_resource(resource, reason)
        self._processes.append(process)

    def ensure_complete_process_validity(self, workflow, process, invalidate_urls, check_integrity):
        for input_resource in process.iter_inputs():
            if input_resource.is_primary():
                if self._previous_workflow:
                    if self._previous_workflow.signature(input_resource.url) != workflow.signature(input_resource.url):
                        reason = RESOURCE_HAS_CHANGED.format(input_resource.url)
                        self.collect_process_and_available_outputs(workflow, process, reason)
                        # All outputs have been invalidated, no need to dig further
                        return
            elif self.resource_invalid(input_resource.url):
                reason = DEPENDENCY_CHANGED.format(input_resource.url)
                self.collect_process_and_available_outputs(workflow, process, reason)
                # All outputs have been invalidated, no need to dig further
                return
        if process.success is False:
            # Only inputs can invalidate a failing process
            return
        for output_resource in process.iter_outputs():
            if output_resource.url in invalidate_urls:
                self.collect_resource(output_resource, USER_REQUEST)
                reason = BROTHER_INVALID.format(output_resource.url)
                self.collect_process_and_available_outputs(workflow, process, reason)
                # All outputs have been invalidated, no need to dig further
                return
            elif not workflow.resource_available(output_resource.url):
                reason = BROTHER_MISSING.format(output_resource.url)
                self.collect_process_and_available_outputs(workflow, process, reason)
                # All outputs have been invalidated, no need to dig further
                return
            elif check_integrity and not output_resource.is_primary() and \
                    self._previous_workflow.signature(output_resource.url) != workflow.signature(output_resource.url):
                self.collect_resource(output_resource, RESOURCE_INTEGRITY)
                reason = BROTHER_INTEGRITY.format(output_resource.url)
                self.collect_process_and_available_outputs(workflow, process, reason)
                # All outputs have been invalidated, no need to dig further
                return
            # Could check for integrity here

    def ensure_process_validity(self, workflow, process, invalidate_urls, invalidate_failures, check_integrity):
        if not process.start:
            # Process hasn't run yet. So it can't have produced valid outputs
            for resource in process.iter_outputs():
                if workflow.resource_available(resource.url):
                    self.collect_resource(resource, NOT_PRODUCED_BY_TUTTLE)
        else:
            # If process has run, we need to look deeper to check if everything is coherent
            self.ensure_complete_process_validity(workflow, process, invalidate_urls, check_integrity)

            if invalidate_failures and process.success is False:
                # Process has failed. So it can't have produced valid outputs
                for resource in process.iter_outputs():
                    if workflow.resource_available(resource.url):
                        self.collect_resource(resource, PROCESS_HAS_FAILED)
                        #  NB : we don't collect the process itself, in order to be able to check for failing processes

    def insure_dependency_coherence(self, workflow, invalidate_urls, invalidate_failures, check_integrity):
        # Take care of failing processes
        for process in workflow.iter_processes_on_dependency_order():
            self.ensure_process_validity(workflow, process, invalidate_urls, invalidate_failures, check_integrity)

    def retrieve_common_processes_form_previous(self, workflow):
        if not self._previous_workflow:
            return
        for prev_process in self._previous_workflow.iter_processes():
            if prev_process.start:
                # Don't need to retrieve from a process that hasn't run yet
                process = workflow.similar_process(prev_process)
                if not process:
                    self.collect_prev_process_and_not_primary_outputs(workflow, prev_process, NO_LONGER_CREATED)
                else:
                    if process.code != prev_process.code:
                        self.collect_prev_process_and_not_primary_outputs(workflow, prev_process, PROCESS_HAS_CHANGED)
                    elif process.processor.name != prev_process.processor.name:
                        self.collect_prev_process_and_not_primary_outputs(workflow, prev_process, PROCESSOR_HAS_CHANGED)
                    elif process.input_urls() != prev_process.input_urls():
                        self.collect_prev_process_and_not_primary_outputs(workflow, prev_process, NOT_SAME_INPUTS)
                    elif process.output_urls() != prev_process.output_urls():
                        self.collect_prev_process_and_not_primary_outputs(workflow, prev_process, NOT_SAME_OUTPUTS)
                        # We could be less restrictive : if someone adds an output because he discovered his process
                        # produces logs, we'd like to add them to the project without reprocessing
                        # At the condition that no process uses this new output
#                       What about check-integrity too ?
                    else:
                        # Both process are the same
                        process.retrieve_execution_info(prev_process)

    def straighten_out_signatures(self, workflow):
        if self._previous_workflow:
            workflow.retrieve_signatures(self._previous_workflow)
        workflow.clear_signatures(self.iter_urls())
        failed = {resource.url for resource in workflow.iter_resources()
                  if resource.creator_process and resource.creator_process.success is False}
        workflow.clear_signatures(failed)
        # Assert straight :
        for resource in workflow.iter_resources():
            assert workflow.signature(resource.url) != "DISCOVERED", resource.url
        # Not needed unless we make adding outputs more flexible
        # workflow.fill_missing_availability()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Aspose.Html.Examples.CSharp.ConvertingBetweenFormats
{
    static class ConvertMHTMLToImage
    {
        public static void WithASingleLine()
        {
            //ExStart: WithASingleLine
            string dataDir = RunExamples.GetDataDir_Data();
            // Open an existing MHTML file for reading.
            using (var stream = System.IO.File.OpenRead(dataDir + "sample.mht"))
            {
                // Call the ConvertMHTML method to convert the MHTML file to image.
                Aspose.Html.Converters.Converter.ConvertMHTML(stream, new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg), "output.jpg");
            }
            //ExEnd: WithASingleLine
        }

        public static void ConvertMHTMLToJPG()
        {
            //ExStart: ConvertMHTMLToJPG
            string dataDir = RunExamples.GetDataDir_Data();
            // Open an existing MHTML file for reading.
            using (var stream = System.IO.File.OpenRead(dataDir + "sample.mht"))
            {
                // Initialize ImageSaveOptions
                var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg);

                // Call the ConvertMHTML method to convert the MHTML file to JPG.
                Aspose.Html.Converters.Converter.ConvertMHTML(stream, options, "output.jpg");
            }
            //ExEnd: ConvertMHTMLToJPG
        }

        public static void ConvertMHTMLToPNG()
        {
            //ExStart: ConvertMHTMLToPNG
            string dataDir = RunExamples.GetDataDir_Data();
            // Open an existing MHTML file for reading.
            using (var stream = System.IO.File.OpenRead(dataDir + "sample.mht"))
            {
                // Initialize ImageSaveOptions
                var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Png);

                // Call the ConvertMHTML method to convert the MHTML file to PNG.
                Aspose.Html.Converters.Converter.ConvertMHTML(stream, options, "output.png");
            }
            //ExEnd: ConvertMHTMLToPNG
        }

        public static void ConvertMHTMLToBMP()
        {
            //ExStart: ConvertMHTMLToBMP
            string dataDir = RunExamples.GetDataDir_Data();
            // Open an existing MHTML file for reading.
            using (var stream = System.IO.File.OpenRead(dataDir + "sample.mht"))
            {
                // Initialize ImageSaveOptions
                var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Bmp);

                // Call the ConvertMHTML method to convert the MHTML file to BMP.
                Aspose.Html.Converters.Converter.ConvertMHTML(stream, options, "output.bmp");
            }
            //ExEnd: ConvertMHTMLToBMP
        }

        public static void ConvertMHTMLToGIF()
        {
            //ExStart: ConvertMHTMLToGIF
            string dataDir = RunExamples.GetDataDir_Data();
            // Open an existing MHTML file for reading.
            using (var stream = System.IO.File.OpenRead(dataDir + "sample.mht"))
            {
                // Initialize ImageSaveOptions
                var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Gif);

                // Call the ConvertMHTML method to convert the MHTML file to GIF.
                Aspose.Html.Converters.Converter.ConvertMHTML(stream, options, "output.gif");
            }
            //ExEnd: ConvertMHTMLToGIF
        }

        public static void ConvertMHTMLToTIFF()
        {
            //ExStart: ConvertMHTMLToTIFF
            string dataDir = RunExamples.GetDataDir_Data();
            // Open an existing MHTML file for reading.
            using (var stream = System.IO.File.OpenRead(dataDir + "sample.mht"))
            {
                // Initialize ImageSaveOptions
                var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Tiff);

                // Call the ConvertMHTML method to convert the MHTML file to TIFF.
                Aspose.Html.Converters.Converter.ConvertMHTML(stream, options, "output.tiff");
            }
            //ExEnd: ConvertMHTMLToTIFF
        }

        public static void SpecifyImageSaveOptions()
        {
            //ExStart: SpecifyImageSaveOptions
            string dataDir = RunExamples.GetDataDir_Data();
            // Open an existing MHTML file for reading.
            using (var stream = System.IO.File.OpenRead(dataDir + "sample.mht"))
            {
                // Initailize the ImageSaveOptions with a custom page-size and a background-color.
                var options = new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg)
                {
                    PageSetup =
                    {
                        AnyPage = new Aspose.Html.Drawing.Page()
                        {
                            Size = new Aspose.Html.Drawing.Size(Aspose.Html.Drawing.Length.FromPixels(3000), Aspose.Html.Drawing.Length.FromPixels(1000))
                        }
                    },
                    BackgroundColor = System.Drawing.Color.Green,
                };

                // Call the ConvertMHTML method to convert the MHTML file to JPG.
                Aspose.Html.Converters.Converter.ConvertMHTML(stream, options, "output.jpg");
            }
            //ExEnd: SpecifyImageSaveOptions
        }

        public static void SpecifyCustomStreamProvider()
        {
            //ExStart: SpecifyCustomStreamProvider
            string dataDir = RunExamples.GetDataDir_Data();
            // Open an existing MHTML file for reading.
            using (var stream = System.IO.File.OpenRead(dataDir + "sample.mht"))
            {
                // Create an instance of MemoryStreamProvider
                using (var streamProvider = new MemoryStreamProvider())
                {
                    // Convert MHTML to Image by using the MemoryStreamProvider
                    Aspose.Html.Converters.Converter.ConvertMHTML(stream, new Aspose.Html.Saving.ImageSaveOptions(Aspose.Html.Rendering.Image.ImageFormat.Jpeg),
                        streamProvider);

                    // Get access to the memory streams that contain the resulted data
                    for (int i = 0; i < streamProvider.Streams.Count; i++)
                    {
                        var memory = streamProvider.Streams[i];
                        memory.Seek(0, System.IO.SeekOrigin.Begin);

                        // Flush the page to the output file
                        using (System.IO.FileStream fs = System.IO.File.Create($"page_{i + 1}.jpg"))
                        {
                            memory.CopyTo(fs);
                        }
                    }
                }
            }
            //ExEnd: SpecifyCustomStreamProvider
        }

        class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider
        {
            // List of MemoryStream objects created during the document rendering
            public List<System.IO.MemoryStream> Streams { get; } = new List<System.IO.MemoryStream>();

            public System.IO.Stream GetStream(string name, string extension)
            {
                // This method is called when the only one output stream is required, for instance for XPS, PDF or TIFF formats.
                System.IO.MemoryStream result = new System.IO.MemoryStream();
                Streams.Add(result);
                return result;
            }

            public System.IO.Stream GetStream(string name, string extension, int page)
            {
                // This method is called when the creation of multiple output streams are required. For instance during the rendering HTML to list of the image files (JPG, PNG, etc.)
                System.IO.MemoryStream result = new System.IO.MemoryStream();
                Streams.Add(result);
                return result;
            }

            public void ReleaseStream(System.IO.Stream stream)
            {
                //  Here You can release the stream filled with data and, for instance, flush it to the hard-drive
            }

            public void Dispose()
            {
                // Releasing resources
                foreach (var stream in Streams)
                    stream.Dispose();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace tao
{
   namespace seq
   {
      template< typename OP, std::size_t I, typename T, T... Ns >
      using partial_accumulate = accumulate< OP, first_t< I, T, Ns... > >;

   }  // namespace seq

}  // namespace tao

#endif


text:
<?php

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Psr\Container\ContainerInterface;
use Symfony\Bridge\Twig\AppVariable;
use Symfony\Bridge\Twig\DataCollector\TwigDataCollector;
use Symfony\Bridge\Twig\ErrorRenderer\TwigErrorRenderer;
use Symfony\Bridge\Twig\Extension\AssetExtension;
use Symfony\Bridge\Twig\Extension\CodeExtension;
use Symfony\Bridge\Twig\Extension\ExpressionExtension;
use Symfony\Bridge\Twig\Extension\HttpFoundationExtension;
use Symfony\Bridge\Twig\Extension\HttpKernelExtension;
use Symfony\Bridge\Twig\Extension\HttpKernelRuntime;
use Symfony\Bridge\Twig\Extension\ProfilerExtension;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
use Symfony\Bridge\Twig\Extension\SerializerExtension;
use Symfony\Bridge\Twig\Extension\SerializerRuntime;
use Symfony\Bridge\Twig\Extension\StopwatchExtension;
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Bridge\Twig\Extension\WebLinkExtension;
use Symfony\Bridge\Twig\Extension\WorkflowExtension;
use Symfony\Bridge\Twig\Extension\YamlExtension;
use Symfony\Bridge\Twig\Translation\TwigExtractor;
use Symfony\Bundle\TwigBundle\CacheWarmer\TemplateCacheWarmer;
use Symfony\Bundle\TwigBundle\DependencyInjection\Configurator\EnvironmentConfigurator;
use Symfony\Bundle\TwigBundle\TemplateIterator;
use Twig\Cache\FilesystemCache;
use Twig\Environment;
use Twig\Extension\CoreExtension;
use Twig\Extension\DebugExtension;
use Twig\Extension\EscaperExtension;
use Twig\Extension\OptimizerExtension;
use Twig\Extension\StagingExtension;
use Twig\ExtensionSet;
use Twig\Loader\ChainLoader;
use Twig\Loader\FilesystemLoader;
use Twig\Profiler\Profile;
use Twig\RuntimeLoader\ContainerRuntimeLoader;
use Twig\Template;
use Twig\TemplateWrapper;

return static function (ContainerConfigurator $container) {
    $container->services()
        ->set('twig', Environment::class)
            ->public()
            ->args([service('twig.loader'), abstract_arg('Twig options')])
            ->call('addGlobal', ['app', service('twig.app_variable')])
            ->call('addRuntimeLoader', [service('twig.runtime_loader')])
            ->configurator([service('twig.configurator.environment'), 'configure'])
            ->tag('container.preload', ['class' => FilesystemCache::class])
            ->tag('container.preload', ['class' => CoreExtension::class])
            ->tag('container.preload', ['class' => EscaperExtension::class])
            ->tag('container.preload', ['class' => OptimizerExtension::class])
            ->tag('container.preload', ['class' => StagingExtension::class])
            ->tag('container.preload', ['class' => ExtensionSet::class])
            ->tag('container.preload', ['class' => Template::class])
            ->tag('container.preload', ['class' => TemplateWrapper::class])
            ->tag('container.private', ['package' => 'symfony/twig-bundle', 'version' => '5.2'])

        ->alias('Twig_Environment', 'twig')
        ->alias(Environment::class, 'twig')

        ->set('twig.app_variable', AppVariable::class)
            ->call('setEnvironment', [param('kernel.environment')])
            ->call('setDebug', [param('kernel.debug')])
            ->call('setTokenStorage', [service('security.token_storage')->ignoreOnInvalid()])
            ->call('setRequestStack', [service('request_stack')->ignoreOnInvalid()])

        ->set('twig.template_iterator', TemplateIterator::class)
            ->args([service('kernel'), abstract_arg('Twig paths'), param('twig.default_path')])

        ->set('twig.template_cache_warmer', TemplateCacheWarmer::class)
            ->args([service(ContainerInterface::class), service('twig.template_iterator')])
            ->tag('kernel.cache_warmer')
            ->tag('container.service_subscriber', ['id' => 'twig'])

        ->set('twig.loader.native_filesystem', FilesystemLoader::class)
            ->args([[], param('kernel.project_dir')])
            ->tag('twig.loader')

        ->set('twig.loader.chain', ChainLoader::class)

        ->set('twig.extension.profiler', ProfilerExtension::class)
            ->args([service('twig.profile'), service('debug.stopwatch')->ignoreOnInvalid()])

        ->set('twig.profile', Profile::class)

        ->set('data_collector.twig', TwigDataCollector::class)
            ->args([service('twig.profile'), service('twig')])
            ->tag('data_collector', ['template' => '@WebProfiler/Collector/twig.html.twig', 'id' => 'twig', 'priority' => 257])

        ->set('twig.extension.trans', TranslationExtension::class)
            ->args([service('translator')->nullOnInvalid()])
            ->tag('twig.extension')

        ->set('twig.extension.assets', AssetExtension::class)
            ->args([service('assets.packages')])

        ->set('twig.extension.code', CodeExtension::class)
            ->args([service('debug.file_link_formatter')->ignoreOnInvalid(), param('kernel.project_dir'), param('kernel.charset')])
            ->tag('twig.extension')

        ->set('twig.extension.routing', RoutingExtension::class)
            ->args([service('router')])

        ->set('twig.extension.yaml', YamlExtension::class)

        ->set('twig.extension.debug.stopwatch', StopwatchExtension::class)
            ->args([service('debug.stopwatch')->ignoreOnInvalid(), param('kernel.debug')])

        ->set('twig.extension.expression', ExpressionExtension::class)

        ->set('twig.extension.httpkernel', HttpKernelExtension::class)

        ->set('twig.runtime.httpkernel', HttpKernelRuntime::class)
            ->args([service('fragment.handler'), service('fragment.uri_generator')->ignoreOnInvalid()])

        ->set('twig.extension.httpfoundation', HttpFoundationExtension::class)
            ->args([service('url_helper')])

        ->set('twig.extension.debug', DebugExtension::class)

        ->set('twig.extension.weblink', WebLinkExtension::class)
            ->args([service('request_stack')])

        ->set('twig.translation.extractor', TwigExtractor::class)
            ->args([service('twig')])
            ->tag('translation.extractor', ['alias' => 'twig'])

        ->set('workflow.twig_extension', WorkflowExtension::class)
            ->args([service('workflow.registry')])

        ->set('twig.configurator.environment', EnvironmentConfigurator::class)
            ->args([
                abstract_arg('date format, set in TwigExtension'),
                abstract_arg('interval format, set in TwigExtension'),
                abstract_arg('timezone, set in TwigExtension'),
                abstract_arg('decimals, set in TwigExtension'),
                abstract_arg('decimal point, set in TwigExtension'),
                abstract_arg('thousands separator, set in TwigExtension'),
            ])

        ->set('twig.runtime_loader', ContainerRuntimeLoader::class)
            ->args([abstract_arg('runtime locator')])

        ->set('twig.error_renderer.html', TwigErrorRenderer::class)
            ->decorate('error_renderer.html')
            ->args([
                service('twig'),
                service('twig.error_renderer.html.inner'),
                inline_service(TwigErrorRenderer::class)
                    ->factory([TwigErrorRenderer::class, 'isDebug'])
                    ->args([service('request_stack'), param('kernel.debug')]),
            ])

        ->set('twig.runtime.serializer', SerializerRuntime::class)
            ->args([service('serializer')])

        ->set('twig.extension.serializer', SerializerExtension::class)
    ;
};


text:
package org.wso2.carbon.apimgt.impl.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIMgtDAOException;
import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants;
import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.concurrent.Semaphore;

/**
 * Implementation for SystemConfigurationDAO
 */
public class SystemConfigurationsDAO {

    private static final Logger log = LoggerFactory.getLogger(SystemConfigurationsDAO.class);
    private static Semaphore semaphore = new Semaphore(1);
    private static SystemConfigurationsDAO INSTANCE = null;

    /**
     * A Semaphore object which acts as a lock for doing thread safe invocations of the DAO
     *
     * @return static Semaphore object
     */
    public static Semaphore getLock() {
        return semaphore;
    }

    /**
     * Method to get the instance of the ApiMgtDAO.
     *
     * @return {@link ApiMgtDAO} instance
     */
    public static SystemConfigurationsDAO getInstance() {

        if (INSTANCE == null) {
            INSTANCE = new SystemConfigurationsDAO();
        }

        return INSTANCE;
    }

    /**
     * Add System Configuration
     *
     * @param organization  Organization
     * @param type  Config Type
     * @param config  Configuration to be added
     */
    public void addSystemConfig(String organization, String type, String config) throws APIManagementException {

        try (Connection connection = APIMgtDBUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(
                     SQLConstants.SystemConfigsConstants.ADD_SYSTEM_CONFIG_SQL)) {
            try {
                connection.setAutoCommit(false);
                statement.setString(1, organization);
                statement.setString(2, type);
                statement.setBinaryStream(3, new ByteArrayInputStream(config.getBytes()));
                statement.executeUpdate();
                connection.commit();
            } catch (SQLException e) {
                handleConnectionRollBack(connection);
                throw e;
            }
        } catch (SQLException e) {
            handleException("Failed to add " + type + " Configuration for org: " + organization, e);
        }
    }

    /**
     * Retrieve System Configuration
     *
     * @param organization  Organization
     * @param type  Config Type
     * @return System Configuration
     */
    public String getSystemConfig(String organization, String type) throws APIManagementException {

        ResultSet rs;
        String systemConfig = null;
        try (Connection connection = APIMgtDBUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(
                     SQLConstants.SystemConfigsConstants.GET_SYSTEM_CONFIG_SQL)) {
            statement.setString(1, organization);
            statement.setString(2, type);
            rs = statement.executeQuery();
            if (rs.next()) {
                InputStream systemConfigBlob = rs.getBinaryStream("CONFIGURATION");
                if (systemConfigBlob != null) {
                    systemConfig = APIMgtDBUtil.getStringFromInputStream(systemConfigBlob);
                }
            }
        } catch (SQLException e) {
            handleException("Failed to retrieve " + type + " Configuration for org: " + organization, e);
        }
        return systemConfig;
    }

    /**
     * Update System Configuration
     *
     * @param organization  Organization
     * @param type  Config Type
     * @param config  Configuration to be updated
     */
    public void updateSystemConfig(String organization, String type, String config) throws APIManagementException {

        try (Connection connection = APIMgtDBUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(
                     SQLConstants.SystemConfigsConstants.UPDATE_SYSTEM_CONFIG_SQL)) {
            try {
                connection.setAutoCommit(false);
                statement.setBinaryStream(1, new ByteArrayInputStream(config.getBytes()));
                statement.setString(2, organization);
                statement.setString(3, type);
                statement.executeUpdate();
                connection.commit();
            } catch (SQLException e) {
                handleConnectionRollBack(connection);
                throw e;
            }
        } catch (SQLException e) {
            handleException("Failed to update " + type + " Configuration for org: " + organization, e);
        }
    }

    /**
     * Method to handle the SQL Exception.
     *
     * @param message : Error message.
     * @param e       : Throwable cause.
     * @throws APIMgtDAOException :
     */
    private void handleException(String message, Throwable e) throws APIMgtDAOException {

        throw new APIMgtDAOException(message, e);
    }

    /**
     * This method handles the connection roll back.
     *
     * @param connection Relevant database connection that need to be rolled back.
     */
    private void handleConnectionRollBack(Connection connection) {
        try {
            if (connection != null) {
                connection.rollback();
            } else {
                log.warn("Could not perform rollback since the connection is null.");
            }
        } catch (SQLException e1) {
            log.error("Error while rolling back the transaction.", e1);
        }
    }
}


text:
let me = 'Computer',
    you = 'new friend'

exports.hello = function (output, tokens) {
  me = tokens[0] || me
  output.log('hello ' + you)
}

exports.iam = function (output, tokens) {
  you = tokens[0] || you
  output.log('hello ' + you + '… i am ' + me)
}


text:
/*
 * Copyright 2007-2010 Joern Huxhorn
 *
 * 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 de.huxhorn.sulky.io;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

public class TimeoutOutputStream
	extends OutputStream
{
	private final OutputStream stream;
	private int timeout;
	private AtomicLong operationStartTime;
	private AtomicBoolean closed;
	private Thread watchdogThread;
	private AtomicBoolean watchdogThreadRunning;

	public TimeoutOutputStream(OutputStream stream, int timeout)
	{
		watchdogThreadRunning = new AtomicBoolean(false);
		if(stream == null)
		{
			throw new IllegalArgumentException("stream must not be null!");
		}
		if(timeout <= 0)
		{
			throw new IllegalArgumentException("timeout must be a positive value!");
		}
		this.stream = stream;
		this.timeout = timeout;
		operationStartTime = new AtomicLong(-1);
		closed = new AtomicBoolean(false);

		Runnable timeoutRunnable = new TimeoutRunnable();
		watchdogThread = new Thread(timeoutRunnable, "TimeoutOutputStream Watchdog-Thread");
		watchdogThread.start();
		try
		{
			Thread.sleep(10); // give the watchdog thread a chance to start...
		}
		catch(InterruptedException e)
		{
			Thread.currentThread().interrupt();
		}
	}

	public void write(byte b[])
		throws IOException
	{
		try
		{
			operationStartTime.set(System.currentTimeMillis());
			stream.write(b);
			operationStartTime.set(-1);
		}
		catch(IOException ex)
		{
			internalClose();
			throw ex;
		}
		catch(RuntimeException ex)
		{
			internalClose();
			throw ex;
		}
	}

	public void write(byte b[], int off, int len)
		throws IOException
	{
		try
		{
			operationStartTime.set(System.currentTimeMillis());
			stream.write(b, off, len);
			operationStartTime.set(-1);
		}
		catch(IOException ex)
		{
			internalClose();
			throw ex;
		}
		catch(RuntimeException ex)
		{
			internalClose();
			throw ex;
		}
	}

	public void write(int b)
		throws IOException
	{
		try
		{
			operationStartTime.set(System.currentTimeMillis());
			stream.write(b);
			operationStartTime.set(-1);
		}
		catch(IOException ex)
		{
			internalClose();
			throw ex;
		}
		catch(RuntimeException ex)
		{
			internalClose();
			throw ex;
		}
	}

	public void flush()
		throws IOException
	{
		try
		{
			operationStartTime.set(System.currentTimeMillis());
			stream.flush();
			operationStartTime.set(-1);
		}
		catch(IOException ex)
		{
			internalClose();
			throw ex;
		}
		catch(RuntimeException ex)
		{
			internalClose();
			throw ex;
		}
	}

	public void close()
		throws IOException
	{
		internalClose();
	}

	public boolean isClosed()
	{
		return closed.get();
	}

	private void internalClose()
		throws IOException
	{
		if(!closed.get())
		{
			closed.set(true);
			try
			{
				stream.close();
			}
			finally
			{
				if(watchdogThread != null)
				{
					watchdogThread.interrupt();
					watchdogThread = null;
				}
			}
		}
	}

	boolean isWatchdogThreadRunning()
	{
		return watchdogThreadRunning.get();
	}

	private class TimeoutRunnable
		implements Runnable
	{
		public void run()
		{
			watchdogThreadRunning.set(true);
			try
			{
				for(; ;)
				{
					if(closed.get())
					{
						//if(logger.isInfoEnabled()) logger.info("Stream was closed. Exiting run()-loop.");
						break;
					}
					long start = operationStartTime.get();
					if(start >= 0)
					{
						long since = System.currentTimeMillis() - start;

						if(since > timeout)
						{
							//if(logger.isInfoEnabled()) logger.info("Timeout detected! Exiting run()-loop.");
							internalClose();
							break;
						}
						else
						{
							Thread.sleep(timeout - since);
						}
					}
					else
					{
						Thread.sleep(timeout);
					}
				}
			}
			catch(IOException e)
			{
				IOUtilities.interruptIfNecessary(e);
				//if(logger.isWarnEnabled()) logger.warn("Exception while closing stream.", e);
			}
			catch(InterruptedException e)
			{
				IOUtilities.interruptIfNecessary(e);
				//if(logger.isInfoEnabled()) logger.info("Interrupted....", e);
			}
			catch(RuntimeException e)
			{
				IOUtilities.interruptIfNecessary(e);
				//if(logger.isInfoEnabled()) logger.info("RuntimeException....", e);
			}
			watchdogThreadRunning.set(false);
		}
	}

}


text:
/*
 *
 * This file is part of Libav.
 *
 * Libav is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * Libav is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with Libav; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#ifndef AVFILTER_BUFFERSRC_H
#define AVFILTER_BUFFERSRC_H

/**
 * @file
 * Memory buffer source API.
 */

#include "libavcodec/avcodec.h"
#include "avfilter.h"

enum {

    /**
     * Do not check for format changes.
     */
    AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT = 1,

    /**
     * Do not copy buffer data.
     */
    AV_BUFFERSRC_FLAG_NO_COPY = 2,

};

/**
 * Add buffer data in picref to buffer_src.
 *
 * @param buffer_src  pointer to a buffer source context
 * @param picref      a buffer reference, or NULL to mark EOF
 * @param flags       a combination of AV_BUFFERSRC_FLAG_*
 * @return            >= 0 in case of success, a negative AVERROR code
 *                    in case of failure
 */
int av_buffersrc_add_ref(AVFilterContext *buffer_src,
                         AVFilterBufferRef *picref, int flags);

/**
 * Get the number of failed requests.
 *
 * A failed request is when the request_frame method is called while no
 * frame is present in the buffer.
 * The number is reset when a frame is added.
 */
unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src);

#ifdef FF_API_BUFFERSRC_BUFFER
/**
 * Add a buffer to the filtergraph s.
 *
 * @param buf buffer containing frame data to be passed down the filtergraph.
 * This function will take ownership of buf, the user must not free it.
 * A NULL buf signals EOF -- i.e. no more frames will be sent to this filter.
 * @deprecated Use av_buffersrc_add_ref(s, picref, AV_BUFFERSRC_FLAG_NO_COPY) instead.
 */
attribute_deprecated
int av_buffersrc_buffer(AVFilterContext *s, AVFilterBufferRef *buf);
#endif

/**
 * Add a frame to the buffer source.
 *
 * @param s an instance of the buffersrc filter.
 * @param frame frame to be added.
 *
 * @warning frame data will be memcpy()ed, which may be a big performance
 *          hit. Use av_buffersrc_buffer() to avoid copying the data.
 */
int av_buffersrc_write_frame(AVFilterContext *s, AVFrame *frame);

#endif /* AVFILTER_BUFFERSRC_H */


text:
<?php
// Heading
$_['heading_title'] 				= 'Bulk Listing';
$_['text_openbay'] 					= 'OpenBay Pro';
$_['text_amazon'] 					= 'Amazon EU';

// Text
$_['text_searching'] 				= 'Searching';
$_['text_finished'] 				= 'Finished';
$_['text_marketplace'] 				= 'Marketplace';
$_['text_de'] 						= 'Germany';
$_['text_fr'] 						= 'France';
$_['text_es'] 						= 'Spain';
$_['text_it'] 						= 'Italy';
$_['text_uk'] 						= 'United Kingdom';
$_['text_dont_list'] 				= 'Do not list';
$_['text_listing_values'] 			= 'Listing values';
$_['text_new'] 						= 'New';
$_['text_used_like_new'] 			= 'Used - Like New';
$_['text_used_very_good'] 			= 'Used - Very Good';
$_['text_used_good'] 				= 'Used - Good';
$_['text_used_acceptable'] 			= 'Used - Acceptable';
$_['text_collectible_like_new'] 	= 'Collectible - Like New';
$_['text_collectible_very_good'] 	= 'Collectible - Very Good';
$_['text_collectible_good'] 		= 'Collectible - Good';
$_['text_collectible_acceptable'] 	= 'Collectible - Acceptable';
$_['text_refurbished'] 				= 'Refurbished';

// Entry
$_['entry_condition'] 				= 'Condition';
$_['entry_condition_note'] 			= 'Condition note';
$_['entry_start_selling'] 			= 'Start Selling';

// Column
$_['column_name'] 					= 'Name';
$_['column_image'] 					= 'Image';
$_['column_model'] 					= 'Model';
$_['column_status'] 				= 'Status';
$_['column_matches']				= 'Matches';
$_['column_result'] 				= 'Result';

// Button
$_['button_list'] 					= 'List';

// Error
$_['error_product_sku'] 			= 'Product must have an SKU';
$_['error_searchable_fields'] 		= 'Product must have ISBN, EAN, UPC or JAN field populated';
$_['error_bulk_listing_permission'] = 'Bulk listing is not available on your plan, please upgrade to use this feature.';
$_['error_select_items'] 			= 'You must select at least 1 item to search';


text:
Danh mục loại phòng
			<button type="button" class="btn btn-xs btn-primary" (click)="select(null)" data-toggle="modal" data-target="#editmodal">
                 Thêm mới
            </button>

						 Loại phòng
						 Giá theo giờ
						 Giá 1/2 ngày
						 Giá ngày
						 Trạng thái

                             {{obj.name}}

						{{obj.formulaByHour}}
						{{obj.formulaByHalfDay}}
						{{obj.formulaByDay}}

							<md-slide-toggle [(ngModel)]="obj.active" (change)="updateStatus(obj._id, obj.active)"></md-slide-toggle>

								<button class="btn btn-primary" (click)="select(null)" data-toggle="modal" data-target="#editmodal"></button>
								<button class="btn btn-success" (click)="select(obj)" data-toggle="modal" data-target="#editmodal"></button>
								<button class="btn btn-danger" (click)="delete(obj)"></button>

				<button type="button" class="close" data-dismiss="modal">×</button>

{{modalTitle}}

			<form (ngSubmit)="save()" #editForm="ngForm">

								Tên loại phòng
								<input class="form-control" name="name" required [(ngModel)]="vm.obj.name">

								Màu:
                                <input class="form-control" [(colorPicker)]="vm.obj.color" [style.background]="vm.obj.color" style="width:35px"
                                    [cpPresetColors]="['#428bca', '#5cb85c', '#5bc0de', '#f0ad4e', '#d9534f']"
                                    [cpPosition]="'right'"
                                    [cpPresetLabel]="'Gợi ý'"
                                    [cpCancelButtonText]="'Đóng'"
                                    />

								Công thức giá phòng theo giờ
								<textarea rows="2" class="form-control" name="formulaByHour" required [(ngModel)]="vm.obj.formulaByHour"></textarea>

								Công thức giá phòng 1/2 ngày
								<textarea rows="2" class="form-control" name="formulaByHalfDay" required [(ngModel)]="vm.obj.formulaByHalfDay"></textarea>

								Công thức giá phòng theo ngày
								<textarea rows="2" class="form-control" name="formulaByDay" required [(ngModel)]="vm.obj.formulaByDay"></textarea>

					<button type="button" class="btn btn-success" [disabled]="!editForm.form.valid" (click)="save()">{{modalTextSave}}</button>
					<button type="button" class="btn btn-danger" data-dismiss="modal"> Đóng</button>

			</form>


text:
layout: post
title: "Meetup: Building a Developer Centred Company Culture"
date: 2014-06-21 16:25
comments: false
tags: [gumtree, culture, developer]
image:
  feature: background.jpg
---
I wrote another post for [Gumtree](http://www.gumtree.com/) developer blog. I attended a meetup in StackCareers office in London. I've attended a few meetups (less than I'd like!) since I came to the City and joined Gumtree, but I consider this one to be one of the best.

<!-- more -->

The subject was Building a Developer Centred Company Culture, which is of particular interest to me, but the speakers did good presentations and the ideas they shared captured my attention more than other events I've attended.

I took notes during the talks and I'd like to share a summary of the main points, as it is a relevant subject for many developers.
First of all a disclaimer: the text below tries to be a raw summary of what I understood. Any errors are mine and of my transcription. That said, I hope I could capture the more relevant parts.

You can read it  [here](https://medium.com/@GumtreeDevTeam/meetup-building-a-developer-centred-company-culture-2c9fac60ba9b).

As always, feedback via Twitter/Email is more than welcome.


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef DEVICE_BLUETOOTH_BLUETOOTH_REMOTE_GATT_SERVICE_ANDROID_H_
#define DEVICE_BLUETOOTH_BLUETOOTH_REMOTE_GATT_SERVICE_ANDROID_H_

#include <map>
#include <string>
#include <vector>

#include "base/android/jni_android.h"
#include "base/containers/scoped_ptr_hash_map.h"
#include "device/bluetooth/bluetooth_gatt_service.h"
#include "device/bluetooth/bluetooth_uuid.h"

namespace device {

class BluetoothAdapterAndroid;
class BluetoothDeviceAndroid;
class BluetoothRemoteGattCharacteristicAndroid;

// BluetoothRemoteGattServiceAndroid along with its owned Java class
// org.chromium.device.bluetooth.ChromeBluetoothRemoteGattService implement
// BluetoothGattService.
class DEVICE_BLUETOOTH_EXPORT BluetoothRemoteGattServiceAndroid
    : public device::BluetoothGattService {
 public:
  // Create a BluetoothRemoteGattServiceAndroid instance and associated Java
  // ChromeBluetoothRemoteGattService using the provided
  // |bluetooth_gatt_service_wrapper|.
  //
  // The ChromeBluetoothRemoteGattService instance will hold a Java reference
  // to |bluetooth_gatt_service_wrapper|.
  static scoped_ptr<BluetoothRemoteGattServiceAndroid> Create(
      BluetoothAdapterAndroid* adapter,
      BluetoothDeviceAndroid* device,
      jobject /* BluetoothGattServiceWrapper */ bluetooth_gatt_service_wrapper,
      const std::string& instanceId,
      jobject /* ChromeBluetoothDevice */ chrome_bluetooth_device);

  ~BluetoothRemoteGattServiceAndroid() override;

  // Register C++ methods exposed to Java using JNI.
  static bool RegisterJNI(JNIEnv* env);

  // Returns the associated ChromeBluetoothRemoteGattService Java object.
  base::android::ScopedJavaLocalRef<jobject> GetJavaObject();

  // Returns a BluetoothGattService::GattErrorCode from a given
  // android.bluetooth.BluetoothGatt error code.
  // |bluetooth_gatt_code| must not be 0 == GATT_SUCCESS.
  static BluetoothGattService::GattErrorCode GetGattErrorCode(
      int bluetooth_gatt_code);

  // Returns an android.bluetooth.BluetoothGatt error code for a given
  // BluetoothGattService::GattErrorCode value.
  static int GetAndroidErrorCode(BluetoothGattService::GattErrorCode);

  // device::BluetoothGattService overrides.
  std::string GetIdentifier() const override;
  device::BluetoothUUID GetUUID() const override;
  bool IsLocal() const override;
  bool IsPrimary() const override;
  device::BluetoothDevice* GetDevice() const override;
  std::vector<device::BluetoothGattCharacteristic*> GetCharacteristics()
      const override;
  std::vector<device::BluetoothGattService*> GetIncludedServices()
      const override;
  device::BluetoothGattCharacteristic* GetCharacteristic(
      const std::string& identifier) const override;
  bool AddCharacteristic(
      device::BluetoothGattCharacteristic* characteristic) override;
  bool AddIncludedService(device::BluetoothGattService* service) override;
  void Register(const base::Closure& callback,
                const ErrorCallback& error_callback) override;
  void Unregister(const base::Closure& callback,
                  const ErrorCallback& error_callback) override;

  // Creates a Bluetooth GATT characteristic object and adds it to
  // |characteristics_| if it is not already there.
  void CreateGattRemoteCharacteristic(
      JNIEnv* env,
      jobject caller,
      const jstring& instanceId,
      jobject /* BluetoothGattCharacteristicWrapper */
      bluetooth_gatt_characteristic_wrapper,
      jobject /* ChromeBluetoothDevice */ chrome_bluetooth_device);

 private:
  BluetoothRemoteGattServiceAndroid(BluetoothAdapterAndroid* adapter,
                                    BluetoothDeviceAndroid* device,
                                    const std::string& instanceId);

  // Populates |characteristics_| from Java objects if necessary.
  void EnsureCharacteristicsCreated() const;

  // Java object org.chromium.device.bluetooth.ChromeBluetoothRemoteGattService.
  base::android::ScopedJavaGlobalRef<jobject> j_service_;

  // The adapter associated with this service. It's ok to store a raw pointer
  // here since |adapter_| indirectly owns this instance.
  BluetoothAdapterAndroid* adapter_;

  // The device this GATT service belongs to. It's ok to store a raw pointer
  // here since |device_| owns this instance.
  BluetoothDeviceAndroid* device_;

  // Adapter unique instance ID.
  std::string instanceId_;

  // Map of characteristics, keyed by characteristic identifier.
  base::ScopedPtrHashMap<std::string,
                         scoped_ptr<BluetoothRemoteGattCharacteristicAndroid>>
      characteristics_;

  DISALLOW_COPY_AND_ASSIGN(BluetoothRemoteGattServiceAndroid);
};

}  // namespace device

#endif  // DEVICE_BLUETOOTH_BLUETOOTH_REMOTE_GATT_SERVICE_ANDROID_H_


text:
package org.eligosource.eventsourced.example

import java.io.File

import scala.concurrent.duration._

import akka.actor._
import akka.pattern.ask
import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import akka.util.Timeout

import com.typesafe.config.ConfigFactory

import org.eligosource.eventsourced.core._
import org.eligosource.eventsourced.core.FsmSpec._
import org.eligosource.eventsourced.journal.leveldb._

/**
 * Manages a cluster-wide `Door` singleton. `Door` is a finite state machine (FSM)
 * taken from `FsmSpec`. `NodeActor` listens to cluster events. If it becomes
 * the leader it creates the `Door` instance, otherwise, it obtains a remote `Door`
 * reference from the other leader. Door commands ("open" or "close") received by
 * `NodeActor` are forwarded as event messages to the door singleton.
 *
 * If the JVM of the leader crashes, another `NodeActor` will be determined to be
 * the new leader. The new leader re-creates the `Door` instance and recovers its
 * state by replaying journaled event messages. All other `NodeActor`s update their
 * remote door references.
 *
 * @param selfAddress address of the cluster node this actor is running on.
 * @param destination remote destination actor reference.
 */
class NodeActor(destination: ActorRef, selfAddress: Address) extends Actor {
  val extension = EventsourcingExtension(context.system)

  var door: Option[ActorRef] = None
  var doorCreatedByMe = false

  def receive = {
    case cmd: String =>
      door foreach { _ forward Message(cmd) }
    case state: CurrentClusterState =>
      state.leader.foreach(setupDoor)
    case LeaderChanged(leader) =>
      leader.foreach(setupDoor)
    case door: ActorRef => {
      this.door = Some(door)
      this.doorCreatedByMe = false
    }
  }

  def setupDoor(leaderAddress: Address) {
    if (selfAddress == leaderAddress) {
      // this actor is the leader
      if (!doorCreatedByMe) {
        // Create a new event-sourced Door FSM and recover its state. The "destination"
        // channel is used by the Door FSM to emit events to a remote destination actor.
        extension.channelOf(DefaultChannelProps(1, destination).withName("destination"))
        extension.processorOf(Props(new Door with Emitter with Eventsourced { val id = 1 }), Some("door"))
        extension.recover()
        // Store reference to Door singleton locally
        door = Some(extension.processors(1))
        doorCreatedByMe = true
        println("MASTER: recovered door at %s" format selfAddress)
      }
    } else {
      // another actor is the leader
      if (doorCreatedByMe && door.isDefined) {
        // stop and deregister Door on this node
        context.stop(extension.processors(1))
        // stop and deregister destination channel on this node
        context.stop(extension.channels(1))
      }

      implicit val timeout = Timeout(5 seconds)
      implicit val executor = context.dispatcher

      for { ActorIdentity(1, Some(door)) <- context.actorSelection(self.path.toStringWithAddress(leaderAddress) + "/door") ? Identify(1) } { self ! door }

      println("SLAVE: referenced door at %s" format leaderAddress)
    }
  }
}

/**
 * Application that joins the cluster by subscribing a `NodeActor` to it. It also
 * prompts users to enter door commands ("open" or "close") and sends them to the
 * created `NodeActor`. Users can enter commands on any cluster node. Application
 * argument is an optional port number (needed for seed nodes).
 */
object NodeApp {
  def main(args: Array[String]) {
    if (args.nonEmpty) System.setProperty("akka.remote.netty.tcp.port", args(0))

    // create an actor system with a configuration loaded from "cluster.conf"
    val system = ActorSystem("node", ConfigFactory.load("cluster"))

    implicit val executor = system.dispatcher
    implicit val timeout = Timeout(5 seconds)

    for {
      // lookup remote journal
      ActorIdentity(1, Some(journal)) <- system.actorSelection("akka.tcp://journal@127.0.0.1:2553/user/journal") ? Identify(1)

      // lookup remote destination
      ActorIdentity(2, Some(destination)) <- system.actorSelection("akka.tcp://journal@127.0.0.1:2553/user/destination") ? Identify(2)
    } {
      // initialize cluster extension
      val cluster = Cluster(system)

      // initialize event-sourcing extension
      EventsourcingExtension(system, journal)

      // create an actor that manages the cluster-wide Door singleton
      val nodeActor = system.actorOf(Props(new NodeActor(destination, cluster.selfAddress)))

      // subscribe that actor to the cluster so that it receives cluster events
      cluster.subscribe(nodeActor, classOf[ClusterDomainEvent])

      Thread.sleep(2000)

      // prompt user for "open" and "close" commands on stdin and write responses to stdout
      while (true) {
        print("command (open|close): ")
        val cmd = Console.readLine()
        if (cmd != null) nodeActor ? cmd onSuccess { case r => println(r) }
        Thread.sleep(200)
      }
    }
  }
}

/**
 * Application that starts remote `journal` and `destination` actors which
 * are used by the cluster. This application is a standalone application
 * that is remotely accessed but not part of the cluster.
 */
object DestinationApp extends App {
  // create an actor system with a configruation loaded from "cluster.conf"
  implicit val system = ActorSystem("journal", ConfigFactory.load("journal"))

  // create a journal and register that journal actor actor under name "journal"
  // in the underlying actor system (needed for remote lookup).
  val journal = LeveldbJournalProps(new File("target/cluster")).withName("journal").withNative(false).createJournal

  // create a destination and register that destination actor under name "destination"
  // in the underlying actor system (needed for remote lookup).
  val destination = system.actorOf(Props(new Destination with Receiver with Confirm), "destination")

  /**
   * Receives event messages from the `Door` FSM and responds to the initial sender
   * (which is a future created by `Node`). Responses are written to stdout by the
   * `Node` application.
   */
  class Destination extends Actor {
    def receive = {
      case DoorMoved(state, count) =>
        sender ! ("moved %d times: door now %s" format (count, state.toString.toLowerCase))
      case DoorNotMoved(state, cmd) =>
        sender ! ("%s: door is %s" format (cmd, state.toString.toLowerCase))
      case NotSupported(cmd) =>
        sender ! ("not supported: %s" format cmd)
    }
  }
}


text:
module ActiveSupport
  module Inflector
    extend self

    def constantize(camel_cased_word)
      names = camel_cased_word.split('::')

      # Trigger a built-in NameError exception including the ill-formed constant in the message.
      Object.const_get(camel_cased_word) if names.empty?

      # Remove the first blank element in case of '::ClassName' notation.
      names.shift if names.size > 1 && names.first.empty?

      names.inject(Object) do |constant, name|
        if constant == Object
          constant.const_get(name)
        else
          candidate = constant.const_get(name)
          next candidate if constant.const_defined?(name, false)
          next candidate unless Object.const_defined?(name)

          # Go down the ancestors to check if it is owned directly. The check
          # stops when we reach Object or the end of ancestors tree.
          constant = constant.ancestors.inject do |const, ancestor|
            break const if ancestor == Object
            break ancestor if ancestor.const_defined?(name, false)
            const
          end

          # owner is in Object, so raise
          constant.const_get(name, false)
        end
      end
    end

  end
end


text:
<!---
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
-->

# プラグイン開発者のためのノート

これらのノートは、主に人造人間と iOS 開発者向けファイルのプラグインを使用して、ファイル システムでプラグインのインターフェイスを記述するもの。

## コルドバのファイル システムの Url の操作

バージョン 1.0.0 以降このプラグインが使用した Url とは `cdvfile` raw デバイス ファイル システム パスを JavaScript に公開するのではなく、ブリッジ上のすべての通信方式します。

JavaScript 側認証と DirectoryEntry オブジェクトの HTML ファイル システムのルートからの相対である fullPath 属性があることを意味します。 呼び出す必要がありますプラグインの JavaScript API は、認証または DirectoryEntry オブジェクトを受け入れる場合 `.toURL()` 、橋を渡ってネイティブ コードに渡す前に、そのオブジェクト。

### Cdvfile を変換する://fileystem のパスに Url

ファイルシステムへの書き込みする必要があるプラグインは実際のファイルシステムの場所に受信ファイル用の URL を変換したい可能性があります。ネイティブのプラットフォームによって、これを行うための複数の方法があります。

覚えておくことが重要ですすべてではない `cdvfile://` の Url はデバイス上の実際のファイルをマッピング可能な。 いくつかの Url は、ファイルでは表されないまたはリモートのリソースを参照することができますもをデバイス上の資産を参照できます。 プラグインはこれらの可能性のために彼らの Url パスに変換するしようとしているときに戻って、有意義な結果を得るかどうか常にテスト必要があります。

#### アンドロイド

Android 上で変換する最も簡単な方法は `cdvfile://` を使用してファイルシステムのパスに URL が `org.apache.cordova.CordovaResourceApi` 。 `CordovaResourceApi`扱うことができるいくつかの方法があります `cdvfile://` Url:

    // webView is a member of the Plugin class
    CordovaResourceApi resourceApi = webView.getResourceApi();

    // Obtain a file:/// URL representing this file on the device,
    // or the same URL unchanged if it cannot be mapped to a file
    Uri fileURL = resourceApi.remapUri(Uri.parse(cdvfileURL));

また、ファイル プラグインを直接使用することが可能です。

    import org.apache.cordova.file.FileUtils;
    import org.apache.cordova.file.FileSystem;
    import java.net.MalformedURLException;

    // Get the File plugin from the plugin manager
    FileUtils filePlugin = (FileUtils)webView.pluginManager.getPlugin("File");

    // Given a URL, get a path for it
    try {
        String path = filePlugin.filesystemPathForURL(cdvfileURL);
    } catch (MalformedURLException e) {
        // The filesystem url wasn't recognized
    }

パスから変換する、 `cdvfile://` の URL:

    import org.apache.cordova.file.LocalFilesystemURL;

    // Get a LocalFilesystemURL object for a device path,
    // or null if it cannot be represented as a cdvfile URL.
    LocalFilesystemURL url = filePlugin.filesystemURLforLocalPath(path);
    // Get the string representation of the URL object
    String cdvfileURL = url.toString();

あなたのプラグインは、ファイルを作成し、認証オブジェクトを返す場合ファイルのプラグインを使用:

    // Return a JSON structure suitable for returning to JavaScript,
    // or null if this file is not representable as a cdvfile URL.
    JSONObject entry = filePlugin.getEntryForFile(file);

#### iOS

IOS にコルドバと同じ使用しない `CordovaResourceApi` アンドロイドとして概念。IOS、上ファイル プラグインを使用して Url をファイルシステムのパスに変換する必要があります。

    // Get a CDVFilesystem URL object from a URL string
    CDVFilesystemURL* url = [CDVFilesystemURL fileSystemURLWithString:cdvfileURL];
    // Get a path for the URL object, or nil if it cannot be mapped to a file
    NSString* path = [filePlugin filesystemPathForURL:url];

    // Get a CDVFilesystem URL object for a device path, or
    // nil if it cannot be represented as a cdvfile URL.
    CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
    // Get the string representation of the URL object
    NSString* cdvfileURL = [url absoluteString];

あなたのプラグインは、ファイルを作成し、認証オブジェクトを返す場合ファイルのプラグインを使用:

    // Get a CDVFilesystem URL object for a device path, or
    // nil if it cannot be represented as a cdvfile URL.
    CDVFilesystemURL* url = [filePlugin fileSystemURLforLocalPath:path];
    // Get a structure to return to JavaScript
    NSDictionary* entry = [filePlugin makeEntryForLocalURL:url]

#### Java スクリプトの設定

Java スクリプトの設定を取得するには `cdvfile://` 認証または DirectoryEntry オブジェクトから URL を単に呼び出す `.toURL()` に:

    var cdvfileURL = entry.toURL();

プラグインハンドラーの応答で返された FileEntry 構造体の実際のエントリ オブジェクトを変換するハンドラーのコードする必要がありますファイル プラグインをインポートし、新しいオブジェクトを作成します。

    // create appropriate Entry object
    var entry;
    if (entryStruct.isDirectory) {
        entry = new DirectoryEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
    } else {
        entry = new FileEntry(entryStruct.name, entryStruct.fullPath, new FileSystem(entryStruct.filesystemName));
    }


text:
package com.commonsware.android.tte;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.UriPermission;
import android.net.Uri;
import android.support.v4.provider.DocumentFile;
import android.util.Log;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;

public class DocumentStorageService extends IntentService {
  private static final String EXTRA_CLOSING="isClosing";

  public static void loadDocument(Context ctxt, Uri document) {
    Intent i=new Intent(ctxt, DocumentStorageService.class)
      .setAction(Intent.ACTION_OPEN_DOCUMENT)
      .setData(document);

    ctxt.startService(i);
  }

  public static void saveDocument(Context ctxt, Uri document,
                                  String text, boolean isClosing) {
    Intent i=new Intent(ctxt, DocumentStorageService.class)
      .setAction(Intent.ACTION_EDIT)
      .setData(document)
      .putExtra(Intent.EXTRA_TEXT, text)
      .putExtra(EXTRA_CLOSING, isClosing);

    ctxt.startService(i);
  }

  public DocumentStorageService() {
    super("DocumentStorageService");
  }

  @Override
  protected void onHandleIntent(Intent intent) {
    if (Intent.ACTION_OPEN_DOCUMENT.equals(intent.getAction())) {
      load(intent.getData());
    }
    else if (Intent.ACTION_EDIT.equals(intent.getAction())) {
      save(intent.getData(),
        intent.getStringExtra(Intent.EXTRA_TEXT),
        intent.getBooleanExtra(EXTRA_CLOSING, false));
    }
  }

  private void load(Uri document) {
    int perms=Intent.FLAG_GRANT_READ_URI_PERMISSION
      | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

    try {
      getContentResolver()
        .takePersistableUriPermission(document, perms);

      boolean weHavePermission=false;

      for (UriPermission perm :
        getContentResolver().getPersistedUriPermissions()) {
        if (perm.getUri().equals(document)) {
          weHavePermission=true;
        }
      }

      if (weHavePermission) {
        try {
          InputStream is=
            getContentResolver().openInputStream(document);

          try {
            String text=slurp(is);
            DocumentFile docFile=
              DocumentFile.fromSingleUri(this, document);

            EventBus
              .getDefault()
              .post(
                new DocumentLoadedEvent(document, text,
                  docFile.getName(), docFile.canWrite()));
          }
          finally {
            is.close();
          }
        }
        catch (Exception e) {
          Log.e(getClass().getSimpleName(),
            "Exception loading "+document.toString(), e);
          EventBus
            .getDefault()
            .post(new DocumentLoadErrorEvent(document, e));
        }
      }
      else {
        Log.e(getClass().getSimpleName(),
          "We failed to get permissions for "+document.toString());
        EventBus
          .getDefault()
          .post(new DocumentPermissionFailureEvent(document));
      }
    }
    catch (SecurityException e) {
      Log.e(getClass().getSimpleName(),
        "Exception getting permissions for "+document.toString(), e);
      EventBus
        .getDefault()
        .post(new DocumentPermissionFailureEvent(document));
    }
  }

  private void save(Uri document, String text, boolean isClosing) {
    try {
      OutputStream os=
        getContentResolver().openOutputStream(document, "w");
      OutputStreamWriter osw=new OutputStreamWriter(os);

      try {
        osw.write(text);
        osw.flush();

        if (isClosing) {
          int perms=Intent.FLAG_GRANT_READ_URI_PERMISSION
            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION;

          getContentResolver()
            .releasePersistableUriPermission(document, perms);
        }

        EventBus
          .getDefault()
          .post(new DocumentSavedEvent(document));
      }
      finally {
        osw.close();
      }
    }
    catch (Exception e) {
      Log.e(getClass().getSimpleName(),
        "Exception saving "+document.toString(), e);
      EventBus
        .getDefault()
        .post(new DocumentSaveErrorEvent(document, e));
    }
  }

  // based on http://stackoverflow.com/a/309718/115145

  private static String slurp(final InputStream is)
    throws IOException {
    final char[] buffer=new char[8192];
    final StringBuilder out=new StringBuilder();
    final Reader in=new InputStreamReader(is, "UTF-8");
    int rsz=in.read(buffer, 0, buffer.length);

    while (rsz>0) {
      out.append(buffer, 0, rsz);
      rsz=in.read(buffer, 0, buffer.length);
    }

    return(out.toString());
  }

  public static class DocumentEvent {
    public final Uri document;

    DocumentEvent(Uri document) {
      this.document=document;
    }
  }

  public static class DocumentLoadedEvent extends DocumentEvent {
    public final String text;
    public final String displayName;
    public final boolean canWrite;

    DocumentLoadedEvent(Uri document, String text,
                        String displayName, boolean canWrite) {
      super(document);
      this.text=text;
      this.displayName=displayName;
      this.canWrite=canWrite;
    }
  }

  public static class DocumentErrorEvent extends DocumentEvent {
    public final Exception e;

    DocumentErrorEvent(Uri document, Exception e) {
      super(document);
      this.e=e;
    }
  }

  public static class DocumentLoadErrorEvent
    extends DocumentErrorEvent {
    DocumentLoadErrorEvent(Uri document, Exception e) {
      super(document, e);
    }
  }

  public static class DocumentSaveErrorEvent
    extends DocumentErrorEvent {
    DocumentSaveErrorEvent(Uri document, Exception e) {
      super(document, e);
    }
  }

  public static class DocumentSavedEvent extends DocumentEvent {
    DocumentSavedEvent(Uri document) {
      super(document);
    }
  }

  public static class DocumentPermissionFailureEvent
    extends DocumentEvent {
    DocumentPermissionFailureEvent(Uri document) {
      super(document);
    }
  }
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "py/compile.h"
#include "py/runtime.h"
#include "py/repl.h"
#include "py/gc.h"
#include "py/frozenmod.h"
#include "py/mphal.h"
#if MICROPY_HW_ENABLE_USB
#include "irq.h"
#include "usb.h"
#endif
#include "lib/mp-readline/readline.h"
#include "lib/utils/pyexec.h"
#include "genhdr/mpversion.h"

pyexec_mode_kind_t pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL;
int pyexec_system_exit = 0;

#if MICROPY_REPL_INFO
STATIC bool repl_display_debugging_info = 0;
#endif

#define EXEC_FLAG_PRINT_EOF (1)
#define EXEC_FLAG_ALLOW_DEBUGGING (2)
#define EXEC_FLAG_IS_REPL (4)
#define EXEC_FLAG_SOURCE_IS_RAW_CODE (8)
#define EXEC_FLAG_SOURCE_IS_VSTR (16)
#define EXEC_FLAG_SOURCE_IS_FILENAME (32)

// parses, compiles and executes the code in the lexer
// frees the lexer before returning
// EXEC_FLAG_PRINT_EOF prints 2 EOF chars: 1 after normal output, 1 after exception output
// EXEC_FLAG_ALLOW_DEBUGGING allows debugging info to be printed after executing the code
// EXEC_FLAG_IS_REPL is used for REPL inputs (flag passed on to mp_compile)
STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input_kind, int exec_flags) {
    int ret = 0;
    #if MICROPY_REPL_INFO
    uint32_t start = 0;
    #endif

    // by default a SystemExit exception returns 0
    pyexec_system_exit = 0;

    nlr_buf_t nlr;
    if (nlr_push(&nlr) == 0) {
        mp_obj_t module_fun;
        #if MICROPY_MODULE_FROZEN_MPY
        if (exec_flags & EXEC_FLAG_SOURCE_IS_RAW_CODE) {
            // source is a raw_code object, create the function
            module_fun = mp_make_function_from_raw_code(source, MP_OBJ_NULL, MP_OBJ_NULL);
        } else
        #endif
        {
            #if MICROPY_ENABLE_COMPILER
            mp_lexer_t *lex;
            if (exec_flags & EXEC_FLAG_SOURCE_IS_VSTR) {
                const vstr_t *vstr = source;
                lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, 0);
            } else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) {
                lex = mp_lexer_new_from_file(source);
            } else {
                lex = (mp_lexer_t *)source;
            }
            // source is a lexer, parse and compile the script
            qstr source_name = lex->source_name;
            mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
            module_fun = mp_compile(&parse_tree, source_name, exec_flags & EXEC_FLAG_IS_REPL);
            #else
            mp_raise_msg(&mp_type_RuntimeError, "script compilation not supported");
            #endif
        }

        // execute code
        mp_hal_set_interrupt_char(CHAR_CTRL_C); // allow ctrl-C to interrupt us
        #if MICROPY_REPL_INFO
        start = mp_hal_ticks_ms();
        #endif
        mp_call_function_0(module_fun);
        mp_hal_set_interrupt_char(-1); // disable interrupt
        mp_handle_pending(true); // handle any pending exceptions (and any callbacks)
        nlr_pop();
        ret = 1;
        if (exec_flags & EXEC_FLAG_PRINT_EOF) {
            mp_hal_stdout_tx_strn("\x04", 1);
        }
    } else {
        // uncaught exception
        mp_hal_set_interrupt_char(-1); // disable interrupt
        mp_handle_pending(false); // clear any pending exceptions (and run any callbacks)
        // print EOF after normal output
        if (exec_flags & EXEC_FLAG_PRINT_EOF) {
            mp_hal_stdout_tx_strn("\x04", 1);
        }
        // check for SystemExit
        if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) {
            // at the moment, the value of SystemExit is unused
            ret = pyexec_system_exit;
        } else {
            mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val));
            ret = 0;
        }
    }

    #if MICROPY_REPL_INFO
    // display debugging info if wanted
    if ((exec_flags & EXEC_FLAG_ALLOW_DEBUGGING) && repl_display_debugging_info) {
        mp_uint_t ticks = mp_hal_ticks_ms() - start; // TODO implement a function that does this properly
        printf("took " UINT_FMT " ms\n", ticks);
        // qstr info
        {
            size_t n_pool, n_qstr, n_str_data_bytes, n_total_bytes;
            qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes);
            printf("qstr:\n  n_pool=%u\n  n_qstr=%u\n  "
                "n_str_data_bytes=%u\n  n_total_bytes=%u\n",
                (unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes);
        }

        #if MICROPY_ENABLE_GC
        // run collection and print GC info
        gc_collect();
        gc_dump_info();
        #endif
    }
    #endif

    if (exec_flags & EXEC_FLAG_PRINT_EOF) {
        mp_hal_stdout_tx_strn("\x04", 1);
    }

    return ret;
}

#if MICROPY_ENABLE_COMPILER
#if MICROPY_REPL_EVENT_DRIVEN

typedef struct _repl_t {
    // This structure originally also held current REPL line,
    // but it was moved to MP_STATE_VM(repl_line) as containing
    // root pointer. Still keep structure in case more state
    // will be added later.
    // vstr_t line;
    bool cont_line;
    bool paste_mode;
} repl_t;

repl_t repl;

STATIC int pyexec_raw_repl_process_char(int c);
STATIC int pyexec_friendly_repl_process_char(int c);

void pyexec_event_repl_init(void) {
    MP_STATE_VM(repl_line) = vstr_new(32);
    repl.cont_line = false;
    repl.paste_mode = false;
    // no prompt before printing friendly REPL banner or entering raw REPL
    readline_init(MP_STATE_VM(repl_line), "");
    if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
        pyexec_raw_repl_process_char(CHAR_CTRL_A);
    } else {
        pyexec_friendly_repl_process_char(CHAR_CTRL_B);
    }
}

STATIC int pyexec_raw_repl_process_char(int c) {
    if (c == CHAR_CTRL_A) {
        // reset raw REPL
        mp_hal_stdout_tx_str("raw REPL; CTRL-B to exit\r\n");
        goto reset;
    } else if (c == CHAR_CTRL_B) {
        // change to friendly REPL
        pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL;
        vstr_reset(MP_STATE_VM(repl_line));
        repl.cont_line = false;
        repl.paste_mode = false;
        pyexec_friendly_repl_process_char(CHAR_CTRL_B);
        return 0;
    } else if (c == CHAR_CTRL_C) {
        // clear line
        vstr_reset(MP_STATE_VM(repl_line));
        return 0;
    } else if (c == CHAR_CTRL_D) {
        // input finished
    } else {
        // let through any other raw 8-bit value
        vstr_add_byte(MP_STATE_VM(repl_line), c);
        return 0;
    }

    // indicate reception of command
    mp_hal_stdout_tx_str("OK");

    if (MP_STATE_VM(repl_line)->len == 0) {
        // exit for a soft reset
        mp_hal_stdout_tx_str("\r\n");
        vstr_clear(MP_STATE_VM(repl_line));
        return PYEXEC_FORCED_EXIT;
    }

    int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_FILE_INPUT, EXEC_FLAG_PRINT_EOF | EXEC_FLAG_SOURCE_IS_VSTR);
    if (ret & PYEXEC_FORCED_EXIT) {
        return ret;
    }

reset:
    vstr_reset(MP_STATE_VM(repl_line));
    mp_hal_stdout_tx_str(">");

    return 0;
}

STATIC int pyexec_friendly_repl_process_char(int c) {
    if (repl.paste_mode) {
        if (c == CHAR_CTRL_C) {
            // cancel everything
            mp_hal_stdout_tx_str("\r\n");
            goto input_restart;
        } else if (c == CHAR_CTRL_D) {
            // end of input
            mp_hal_stdout_tx_str("\r\n");
            int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_FILE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
            if (ret & PYEXEC_FORCED_EXIT) {
                return ret;
            }
            goto input_restart;
        } else {
            // add char to buffer and echo
            vstr_add_byte(MP_STATE_VM(repl_line), c);
            if (c == '\r') {
                mp_hal_stdout_tx_str("\r\n=== ");
            } else {
                char buf[1] = {c};
                mp_hal_stdout_tx_strn(buf, 1);
            }
            return 0;
        }
    }

    int ret = readline_process_char(c);

    if (!repl.cont_line) {

        if (ret == CHAR_CTRL_A) {
            // change to raw REPL
            pyexec_mode_kind = PYEXEC_MODE_RAW_REPL;
            mp_hal_stdout_tx_str("\r\n");
            pyexec_raw_repl_process_char(CHAR_CTRL_A);
            return 0;
        } else if (ret == CHAR_CTRL_B) {
            // reset friendly REPL
            mp_hal_stdout_tx_str("\r\n");
            mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n");
            #if MICROPY_PY_BUILTINS_HELP
            mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n");
            #endif
            goto input_restart;
        } else if (ret == CHAR_CTRL_C) {
            // break
            mp_hal_stdout_tx_str("\r\n");
            goto input_restart;
        } else if (ret == CHAR_CTRL_D) {
            // exit for a soft reset
            mp_hal_stdout_tx_str("\r\n");
            vstr_clear(MP_STATE_VM(repl_line));
            return PYEXEC_FORCED_EXIT;
        } else if (ret == CHAR_CTRL_E) {
            // paste mode
            mp_hal_stdout_tx_str("\r\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\r\n=== ");
            vstr_reset(MP_STATE_VM(repl_line));
            repl.paste_mode = true;
            return 0;
        }

        if (ret < 0) {
            return 0;
        }

        if (!mp_repl_continue_with_input(vstr_null_terminated_str(MP_STATE_VM(repl_line)))) {
            goto exec;
        }

        vstr_add_byte(MP_STATE_VM(repl_line), '\n');
        repl.cont_line = true;
        readline_note_newline("... ");
        return 0;

    } else {

        if (ret == CHAR_CTRL_C) {
            // cancel everything
            mp_hal_stdout_tx_str("\r\n");
            repl.cont_line = false;
            goto input_restart;
        } else if (ret == CHAR_CTRL_D) {
            // stop entering compound statement
            goto exec;
        }

        if (ret < 0) {
            return 0;
        }

        if (mp_repl_continue_with_input(vstr_null_terminated_str(MP_STATE_VM(repl_line)))) {
            vstr_add_byte(MP_STATE_VM(repl_line), '\n');
            readline_note_newline("... ");
            return 0;
        }

    exec:;
        int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_SINGLE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
        if (ret & PYEXEC_FORCED_EXIT) {
            return ret;
        }

    input_restart:
        vstr_reset(MP_STATE_VM(repl_line));
        repl.cont_line = false;
        repl.paste_mode = false;
        readline_init(MP_STATE_VM(repl_line), ">>> ");
        return 0;
    }
}

uint8_t pyexec_repl_active;
int pyexec_event_repl_process_char(int c) {
    pyexec_repl_active = 1;
    int res;
    if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
        res = pyexec_raw_repl_process_char(c);
    } else {
        res = pyexec_friendly_repl_process_char(c);
    }
    pyexec_repl_active = 0;
    return res;
}

#else // MICROPY_REPL_EVENT_DRIVEN

int pyexec_raw_repl(void) {
    vstr_t line;
    vstr_init(&line, 32);

raw_repl_reset:
    mp_hal_stdout_tx_str("raw REPL; CTRL-B to exit\r\n");

    for (;;) {
        vstr_reset(&line);
        mp_hal_stdout_tx_str(">");
        for (;;) {
            int c = mp_hal_stdin_rx_chr();
            if (c == CHAR_CTRL_A) {
                // reset raw REPL
                goto raw_repl_reset;
            } else if (c == CHAR_CTRL_B) {
                // change to friendly REPL
                mp_hal_stdout_tx_str("\r\n");
                vstr_clear(&line);
                pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL;
                return 0;
            } else if (c == CHAR_CTRL_C) {
                // clear line
                vstr_reset(&line);
            } else if (c == CHAR_CTRL_D) {
                // input finished
                break;
            } else {
                // let through any other raw 8-bit value
                vstr_add_byte(&line, c);
            }
        }

        // indicate reception of command
        mp_hal_stdout_tx_str("OK");

        if (line.len == 0) {
            // exit for a soft reset
            mp_hal_stdout_tx_str("\r\n");
            vstr_clear(&line);
            return PYEXEC_FORCED_EXIT;
        }

        int ret = parse_compile_execute(&line, MP_PARSE_FILE_INPUT, EXEC_FLAG_PRINT_EOF | EXEC_FLAG_SOURCE_IS_VSTR);
        if (ret & PYEXEC_FORCED_EXIT) {
            return ret;
        }
    }
}

int pyexec_friendly_repl(void) {
    vstr_t line;
    vstr_init(&line, 32);

    #if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD
    // in host mode, we enable the LCD for the repl
    mp_obj_t lcd_o = mp_call_function_0(mp_load_name(qstr_from_str("LCD")));
    mp_call_function_1(mp_load_attr(lcd_o, qstr_from_str("light")), mp_const_true);
    #endif

friendly_repl_reset:
    mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n");
    #if MICROPY_PY_BUILTINS_HELP
    mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n");
    #endif

    // to test ctrl-C
    /*
    {
        uint32_t x[4] = {0x424242, 0xdeaddead, 0x242424, 0xdeadbeef};
        for (;;) {
            nlr_buf_t nlr;
            printf("pyexec_repl: %p\n", x);
            mp_hal_set_interrupt_char(CHAR_CTRL_C);
            if (nlr_push(&nlr) == 0) {
                for (;;) {
                }
            } else {
                printf("break\n");
            }
        }
    }
    */

    for (;;) {
    input_restart:

        #if MICROPY_HW_ENABLE_USB
        if (usb_vcp_is_enabled()) {
            // If the user gets to here and interrupts are disabled then
            // they'll never see the prompt, traceback etc. The USB REPL needs
            // interrupts to be enabled or no transfers occur. So we try to
            // do the user a favor and reenable interrupts.
            if (query_irq() == IRQ_STATE_DISABLED) {
                enable_irq(IRQ_STATE_ENABLED);
                mp_hal_stdout_tx_str("MPY: enabling IRQs\r\n");
            }
        }
        #endif

        // If the GC is locked at this point there is no way out except a reset,
        // so force the GC to be unlocked to help the user debug what went wrong.
        if (MP_STATE_MEM(gc_lock_depth) != 0) {
            MP_STATE_MEM(gc_lock_depth) = 0;
        }

        vstr_reset(&line);
        int ret = readline(&line, ">>> ");
        mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT;

        if (ret == CHAR_CTRL_A) {
            // change to raw REPL
            mp_hal_stdout_tx_str("\r\n");
            vstr_clear(&line);
            pyexec_mode_kind = PYEXEC_MODE_RAW_REPL;
            return 0;
        } else if (ret == CHAR_CTRL_B) {
            // reset friendly REPL
            mp_hal_stdout_tx_str("\r\n");
            goto friendly_repl_reset;
        } else if (ret == CHAR_CTRL_C) {
            // break
            mp_hal_stdout_tx_str("\r\n");
            continue;
        } else if (ret == CHAR_CTRL_D) {
            // exit for a soft reset
            mp_hal_stdout_tx_str("\r\n");
            vstr_clear(&line);
            return PYEXEC_FORCED_EXIT;
        } else if (ret == CHAR_CTRL_E) {
            // paste mode
            mp_hal_stdout_tx_str("\r\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\r\n=== ");
            vstr_reset(&line);
            for (;;) {
                char c = mp_hal_stdin_rx_chr();
                if (c == CHAR_CTRL_C) {
                    // cancel everything
                    mp_hal_stdout_tx_str("\r\n");
                    goto input_restart;
                } else if (c == CHAR_CTRL_D) {
                    // end of input
                    mp_hal_stdout_tx_str("\r\n");
                    break;
                } else {
                    // add char to buffer and echo
                    vstr_add_byte(&line, c);
                    if (c == '\r') {
                        mp_hal_stdout_tx_str("\r\n=== ");
                    } else {
                        mp_hal_stdout_tx_strn(&c, 1);
                    }
                }
            }
            parse_input_kind = MP_PARSE_FILE_INPUT;
        } else if (vstr_len(&line) == 0) {
            continue;
        } else {
            // got a line with non-zero length, see if it needs continuing
            while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) {
                vstr_add_byte(&line, '\n');
                ret = readline(&line, "... ");
                if (ret == CHAR_CTRL_C) {
                    // cancel everything
                    mp_hal_stdout_tx_str("\r\n");
                    goto input_restart;
                } else if (ret == CHAR_CTRL_D) {
                    // stop entering compound statement
                    break;
                }
            }
        }

        ret = parse_compile_execute(&line, parse_input_kind, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR);
        if (ret & PYEXEC_FORCED_EXIT) {
            return ret;
        }
    }
}

#endif // MICROPY_REPL_EVENT_DRIVEN
#endif // MICROPY_ENABLE_COMPILER

int pyexec_file(const char *filename) {
    return parse_compile_execute(filename, MP_PARSE_FILE_INPUT, EXEC_FLAG_SOURCE_IS_FILENAME);
}

int pyexec_file_if_exists(const char *filename) {
    #if MICROPY_MODULE_FROZEN
    if (mp_frozen_stat(filename) == MP_IMPORT_STAT_FILE) {
        return pyexec_frozen_module(filename);
    }
    #endif
    if (mp_import_stat(filename) != MP_IMPORT_STAT_FILE) {
        return 1; // success (no file is the same as an empty file executing without fail)
    }
    return pyexec_file(filename);
}

#if MICROPY_MODULE_FROZEN
int pyexec_frozen_module(const char *name) {
    void *frozen_data;
    int frozen_type = mp_find_frozen_module(name, strlen(name), &frozen_data);

    switch (frozen_type) {
        #if MICROPY_MODULE_FROZEN_STR
        case MP_FROZEN_STR:
            return parse_compile_execute(frozen_data, MP_PARSE_FILE_INPUT, 0);
        #endif

        #if MICROPY_MODULE_FROZEN_MPY
        case MP_FROZEN_MPY:
            return parse_compile_execute(frozen_data, MP_PARSE_FILE_INPUT, EXEC_FLAG_SOURCE_IS_RAW_CODE);
        #endif

        default:
            printf("could not find module '%s'\n", name);
            return false;
    }
}
#endif

#if MICROPY_REPL_INFO
mp_obj_t pyb_set_repl_info(mp_obj_t o_value) {
    repl_display_debugging_info = mp_obj_get_int(o_value);
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_1(pyb_set_repl_info_obj, pyb_set_repl_info);
#endif