text:
package fr.pilato.elasticsearch.crawler.fs.test.integration.elasticsearch;

import fr.pilato.elasticsearch.crawler.fs.client.ESSearchRequest;
import fr.pilato.elasticsearch.crawler.fs.settings.Fs;
import fr.pilato.elasticsearch.crawler.fs.test.integration.AbstractFsCrawlerITCase;
import org.junit.Test;

import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Test with symlinks
 */
public class FsCrawlerTestFollowSymlinksIT extends AbstractFsCrawlerITCase {

    @Test
    public void test_follow_symlinks_disabled() throws Exception {
        // We create a symlink
        Path source = currentTestResourceDir.resolve("roottxtfile.txt");
        Path link = currentTestResourceDir.resolve("link_roottxtfile.txt");
        Files.createSymbolicLink(link, source);

        Fs fs = startCrawlerDefinition()
                .setFollowSymlinks(false)
                .build();
        crawler = startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);

        // We should have two docs first
        countTestHelper(new ESSearchRequest().withIndex(getCrawlerName()), 1L, currentTestResourceDir);
    }

    @Test
    public void test_follow_symlinks_enabled() throws Exception {
        // We create a symlink
        Path source = currentTestResourceDir.resolve("roottxtfile.txt");
        Path link = currentTestResourceDir.resolve("link_roottxtfile.txt");
        Files.createSymbolicLink(link, source);

        Fs fs = startCrawlerDefinition()
                .setFollowSymlinks(true)
                .build();
        crawler = startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);

        // We should have two docs first
        countTestHelper(new ESSearchRequest().withIndex(getCrawlerName()), 2L, currentTestResourceDir);
    }
}


text:
<?php

/**
 * @namespace
 */
namespace Zend\Application;

use Zend\Loader\LazyLoadingBroker;

/**
 * Interface for bootstrap classes that utilize resource plugins
 *
 * @category   Zend
 * @package    Zend_Application
 * @subpackage Bootstrap
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface ResourceBootstrapper
{
    /**
     * Set plugin broker to use to fetch resources
     *
     * @param  \Zend\Loader\LazyLoadingBroker $broker
     * @return \Zend\Application\ResourceBootstrapper
     */
    public function setBroker($broker);

    /**
     * Retrieve plugin broker for resources
     *
     * @return \Zend\Loader\LazyLoadingBroker
     */
    public function getBroker();
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Booothy\Photo\Domain\Repository;

use Booothy\Photo\Domain\Model\Photo;

interface Saver
{
    public function __invoke(Photo $photo);
}


text:
(async function() {
  TestRunner.addResult(`Tests that elements panel preserves selected shadow DOM node on page refresh.\n`);
  await TestRunner.loadLegacyModule('elements'); await TestRunner.loadTestModule('elements_test_runner');
  await TestRunner.showPanel('elements');
  await TestRunner.navigatePromise('../resources/elements-panel-shadow-selection-on-refresh.html');

  TestRunner.runTestSuite([
    function setup(next) {
      Common.settingForTest('showUAShadowDOM').set(true);
      ElementsTestRunner.expandElementsTree(next);
    },

    function testOpenShadowRoot(next) {
      ElementsTestRunner.findNode(isOpenShadowRoot, ElementsTestRunner.selectReloadAndDump.bind(null, next));
    },

    function testClosedShadowRoot(next) {
      ElementsTestRunner.findNode(isClosedShadowRoot, ElementsTestRunner.selectReloadAndDump.bind(null, next));
    },
  ]);

  function isOpenShadowRoot(node) {
    return node && node.shadowRootType() === SDK.DOMNode.ShadowRootTypes.Open;
  }

  function isClosedShadowRoot(node) {
    return node && node.shadowRootType() === SDK.DOMNode.ShadowRootTypes.Closed;
  }
})();


text:
"use strict";

describe('videojs.vast plugin', function() {

  var player, isHtmlSupported, oldClearImmediate;

  beforeEach(function() {
    var id = "vid";
    (function() {
      var video = document.createElement("video");
      video.id = id;
      video.src = "http://vjs.zencdn.net/v/oceans.mp4";
      video.setAttribute = "controls";
      document.body.appendChild(video);
      isHtmlSupported = videojs.Html5.isSupported;
      if (/phantomjs/gi.test(window.navigator.userAgent)) {
        // PhantomJS doesn't have a video element implementation
        // force support here so that the HTML5 tech is still used during
        // command-line test runs
        videojs.Html5.isSupported = function() {
          return true;
        };

        // provide implementations for any video element functions that are
        // used in the tests
        video.load = function() {};
        video.play = function() {};

        // see https://github.com/videojs/videojs-contrib-ads/blob/master/test/videojs.ads.test.js#L23
        window.setImmediate = function(callback) {
          callback.call(window);
        };
        oldClearImmediate = window.clearImmediate;
      }
    })();
    player = videojs(id);
    player.ads();
    player.vast({
      url: ""
    });
  });

  afterEach(function() {
    player.dispose();
    videojs.Html5.isSupported = isHtmlSupported;
    window.clearImmediate = oldClearImmediate;
  });

  describe("Requirements", function() {

    beforeEach(function() {
      var video = document.createElement("video");
      video.setAttribute = "controls";
      document.body.appendChild(video);
      this.p = videojs(video);
    });

    afterEach(function() {
      this.p.dispose();
    });

    it("should bail out if player.ads isn't defined", function() {
      spyOn(console, "error");
      this.p.ads = undefined;
      var result = this.p.vast({url:"i wanna go VAST!"});
      expect(result).toBe(null);
      expect(console.error).toHaveBeenCalledWith(jasmine.any(String));
    });

    it("should bail out if no url is provided", function() {
      spyOn(this.p, "trigger");
      this.p.ads();
      var result = this.p.vast({});
      expect(result).toBe(null);
      expect(this.p.trigger).toHaveBeenCalledWith("adtimeout");
    });

    it("should request an ad if a source is already loaded", function() {
      this.p.currentSrc = function() {
        return "video.mp4";
      };
      spyOn(DMVAST.client, "get");
      this.p.ads();
      this.p.vast({url:"i wanna go VAST!"});
      expect(DMVAST.client.get).toHaveBeenCalledWith("i wanna go VAST!", jasmine.any(Function));
    });
  });

  describe("Public methods", function() {

    describe("createSourceObjects", function() {

      it("should return objects with 'src', 'type', 'width', 'height', 'apiFramework', 'bitrate' and 'adParameters properties'", function() {
        player.vast({ url: 'balhbahblhab' });
        var media_files = [
          {
            fileURL: "TRL",
            mimeType: "video/webm",
            width: 640,
            height: 360,
            apiFramework: "example framework",
            bitrate: 800
          },
          {
            fileURL: "BuddhaForRill",
            mimeType: "video/mp4",
            width: 0,
            height: 0,
            apiFramework: "vpaid",
            bitrate: 800
          }
        ],
        creative = {
            mediaFiles: media_files,
            adParameters: "test ad parameter"
        };
        var sources = player.vast.createSourceObjects(creative);
        for (var s in sources) {
          expect(sources[s].src).toBeDefined();
          expect(sources[s].type).toBeDefined();
          expect(sources[s].width).toBeDefined();
          expect(sources[s].height).toBeDefined();
          expect(sources[s].apiFramework).toBeDefined();
          expect(sources[s].bitrate).toBeDefined();
        }
      });
    });

    describe("tearDown", function() {

      it("should end the linear ad", function() {
        player.vast({ url: 'balhbahblhab' });

        spyOn(player.ads, "endLinearAdMode");
        spyOn(player, "off");

        // TODO: fix this
        player.vast.skipButton = document.createElement("div");
        player.el().appendChild(player.vast.skipButton);
        player.vast.blocker = document.createElement("a");
        player.el().insertBefore(player.vast.blocker, player.controlBar.el());

        player.vast.tearDown();
        expect(player.off).toHaveBeenCalledWith("ended", jasmine.any(Function));
        expect(player.ads.endLinearAdMode).toHaveBeenCalled();
      });

    });

    describe("preroll", function() {

      beforeEach(function() {
        player.vast({ url: 'balhbahblhab' });
        player.vastTracker = {
          clickThroughURLTemplate: "a whole new page",
          clickTrackingURLTemplate: "a new fantastic advertisement",
          trackURLs: function(){},
          progressFormated: function(){}
        };
        player.vast.sources = [];
      });

      it("should start the ad", function() {
        spyOn(player.ads, "startLinearAdMode");
        spyOn(player, "src");
        player.vast.sources = [];
        player.vast.preroll();
        expect(player.ads.startLinearAdMode).toHaveBeenCalled();
        expect(player.src).toHaveBeenCalledWith(jasmine.any(Array));
      });

      it("should end the ad", function() {
        spyOn(player, "one");
        player.vast.preroll();
        expect(player.one).toHaveBeenCalledWith("ended", jasmine.any(Function));
      });

    });

    describe("getContent", function() {
      it("should bail out if there aren't playable media files", function() {
        player.vast({ url: 'balhbahblhab' });
        spyOn(DMVAST.client, "get").and.callFake(function(url, callback){
            var fake_response = {
              ads: [{
                creatives:[{
                  type: "linear",
                  mediaFiles: [{fileURL:"0", mimeType:"n0t-r34l"}]
                }]
              }]
            };
            callback(fake_response);
          });

        spyOn(player, "trigger");
        player.vast.getContent("some url");
        expect(player.trigger).toHaveBeenCalledWith("adtimeout");
      });

      describe("linear ads", function() {
        beforeEach(function() {
          spyOn(DMVAST.client, "get")
            .and.callFake(function(url, callback){
              var fake_response = {
                ads: [{
                  creatives:[{
                    type: "linear",
                    mediaFiles: [{fileURL:"hunt", mimeType:"video/webm"}]
                  }]
                }]
              };
              callback(fake_response);
            });
        });
      });

      describe("non-linear ads", function() {
        beforeEach(function() {
          spyOn(DMVAST.client, "get")
            .and.callFake(function(url, callback){
              var fake_response = {
                ads: [{
                  creatives:[{
                    type: "non-linear",
                    mediaFiles: [{}]
                  }],
                  errorURLTemplates: "error!"
                }]
              };
              callback(fake_response);
            });
        });
        it("should do nothing with non-linear ads, and report the error", function() {
          player.vast({ url: 'balhbahblhab' });
          spyOn(DMVAST.util, "track");
          spyOn(player, "trigger");
          player.vast.getContent("some url");
          expect(DMVAST.util.track).toHaveBeenCalledWith(
            jasmine.any(String), jasmine.any(Object)
          );
          expect(player.trigger).toHaveBeenCalledWith("adtimeout");
        });
      });

    });

  });
});


text:
SPAKE2+ Python Tool is a Python script for generating SPAKE2+ protocol
parameters (only Verifier as of today). SPAKE2+ protocol is used during Matter
commissioning to establish a secure session between the commissioner and the
commissionee.

## Usage Examples

To list all available subcommands:

```console
$ ./spake2p.py --help
usage: spake2p.py [-h] subcommand       ...

SPAKE2+ Python Tool

positional arguments:
  subcommand
    gen-verifier    Generate SPAKE2+ Verifier

options:
  -h, --help        show this help message and exit
```

To display parameters of the `gen-verifier` subcommand:

```console
$ ./spake2p.py gen-verifier --help
usage: spake2p.py gen-verifier [-h] -p PASSCODE -s SALT -i count

options:
  -h, --help            show this help message and exit
  -p PASSCODE, --passcode PASSCODE
                        8-digit passcode
  -s SALT, --salt SALT  Salt of length 16 to 32 octets encoded in Base64
  -i count, --iteration-count count
                        Iteration count between 1000 and 100000
```

To generate SPAKE2+ verifier for "SPAKE2P Key Salt" salt and 20202021 passcode,
using 1000 PBKDF2 iterations:

```console
./spake2p.py gen-verifier -p 20202021 -s U1BBS0UyUCBLZXkgU2FsdA== -i 1000
uWFwqugDNGiEck/po7KHwwMwwqZgN10XuyBajPGuyzUEV/iree4lOrao5GuwnlQ65CJzbeUB49s31EH+NEkg0JVI5MGCQGMMT/SRPFNRODm3wH/MBiehuFc6FJ/NH6Rmzw==
```


text:
using Stardust.Particles;
using Stardust.Particles.Collection.Arrays;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
using System.Xml;

namespace Stardust.Aadb2c.AuthenticationFilter.Core
{
    public static class B2CGlobalConfiguration
    {
        /// <summary>
        /// Semicolon separated list of audiences
        /// </summary>
        public static string Audience
        {
            get => ConfigurationManagerHelper.GetValueOnKey("audience");
            set => ConfigurationManagerHelper.SetValueOnKey("audience", value, true);
        }

        public static string AadTenant
        {
            get => ConfigurationManagerHelper.GetValueOnKey("aadTenant");
            set => ConfigurationManagerHelper.SetValueOnKey("aadTenant", value, true);
        }

        public static string AadPolicy
        {
            get => ConfigurationManagerHelper.GetValueOnKey("aadPolicy");
            set => ConfigurationManagerHelper.SetValueOnKey("aadPolicy", value, true);
        }

        /// <summary>
        ///
        /// </summary>
        public static string ValidIssuer
        {
            get => ConfigurationManagerHelper.GetValueOnKey("issuerHostName");
            set => ConfigurationManagerHelper.SetValueOnKey("issuerHostName", value, true);
        }

        public static string ValidIssuerV1
        {
            get => ConfigurationManagerHelper.GetValueOnKey("issuerHostName_v1");
            set => ConfigurationManagerHelper.SetValueOnKey("issuerHostName_v1", value, true);
        }

        public static bool UseSupportCode
        {
            get => ConfigurationManagerHelper.GetValueOnKey("stardust.useSupportCode", true);
            set => ConfigurationManagerHelper.SetValueOnKey("stardust.useSupportCode", value.ToString(), true);
        }

        public static bool AllowClientCredentialsOverV2
        {
            get => ConfigurationManagerHelper.GetValueOnKey("stardust.allowClientCredentialsOverV2", true);
            set => ConfigurationManagerHelper.SetValueOnKey("stardust.allowClientCredentialsOverV2", value.ToString(), true);
        }

        public static string AudienceV1
        {
            get => ConfigurationManagerHelper.GetValueOnKey("audience_v1");
            set => ConfigurationManagerHelper.SetValueOnKey("audience_v1", value, true);
        }

        public static string[] AadTenants
        {
            get => ConfigurationManagerHelper.GetValueOnKey("aadTenants")?.Split(';');
            set
            {
                if (value.ContainsElements())
                    ConfigurationManagerHelper.SetValueOnKey("aadTenants", string.Join(";", value), true);
            }
        }
    }

    //public interface IServiceLocator
    //{
    //    T GetService<T>();

    //    IEnumerable<T> GetServices<T>();
    //}

    //public static class ServiceLocatorFactory
    //{
    //    private static IServiceLocator _serviceLocator;

    //    public static void AddServiceLocator(IServiceLocator locator)
    //    {
    //        _serviceLocator = locator;
    //    }

    //    internal static T GetService<T>()
    //    {
    //        if (_serviceLocator == null) return default(T);
    //        return _serviceLocator.GetService<T>();
    //    }

    //    internal static IEnumerable<T> GetServices<T>()
    //    {
    //        return _serviceLocator?.GetServices<T>();
    //    }
    //}
}


text: soooooo close


text:
Deprecated Features
===================

This document lists all deprecated features in Twig. Deprecated features are
kept for backward compatibility and removed in the next major release (a
feature that was deprecated in Twig 1.x is removed in Twig 2.0).

Token Parsers
-------------

* As of Twig 1.x, the token parser broker sub-system is deprecated. The
  following class and interface will be removed in 2.0:

  * ``Twig_TokenParserBrokerInterface``
  * ``Twig_TokenParserBroker``

Extensions
----------

* As of Twig 1.x, the ability to remove an extension is deprecated and the
  ``Twig_Environment::removeExtension()`` method will be removed in 2.0.

PEAR
----

PEAR support has been discontinued in Twig 1.15.1, and no PEAR packages is
provided anymore. Use Composer instead.

Filters
-------

* As of Twig 1.x, use ``Twig_SimpleFilter`` to add a filter. The following
  classes and interfaces will be removed in 2.0:

  * ``Twig_FilterInterface``
  * ``Twig_FilterCallableInterface``
  * ``Twig_Filter``
  * ``Twig_Filter_Function``
  * ``Twig_Filter_Method``
  * ``Twig_Filter_Node``

* As of Twig 2.x, the ``Twig_SimpleFilter`` class is deprecated and will be
  removed in Twig 3.x (use ``Twig_Filter`` instead). In Twig 2.x,
  ``Twig_SimpleFilter`` is just an alias for ``Twig_Filter``.

Functions
---------

* As of Twig 1.x, use ``Twig_SimpleFunction`` to add a function. The following
  classes and interfaces will be removed in 2.0:

  * ``Twig_FunctionInterface``
  * ``Twig_FunctionCallableInterface``
  * ``Twig_Function``
  * ``Twig_Function_Function``
  * ``Twig_Function_Method``
  * ``Twig_Function_Node``

* As of Twig 2.x, the ``Twig_SimpleFunction`` class is deprecated and will be
  removed in Twig 3.x (use ``Twig_Function`` instead). In Twig 2.x,
  ``Twig_SimpleFunction`` is just an alias for ``Twig_Function``.

Tests
-----

* As of Twig 1.x, use ``Twig_SimpleTest`` to add a test. The following classes
  and interfaces will be removed in 2.0:

  * ``Twig_TestInterface``
  * ``Twig_TestCallableInterface``
  * ``Twig_Test``
  * ``Twig_Test_Function``
  * ``Twig_Test_Method``
  * ``Twig_Test_Node``

* As of Twig 2.x, the ``Twig_SimpleTest`` class is deprecated and will be
  removed in Twig 3.x (use ``Twig_Test`` instead). In Twig 2.x,
  ``Twig_SimpleTest`` is just an alias for ``Twig_Test``.

* The ``sameas`` and ``divisibleby`` tests are deprecated in favor of ``same
  as`` and ``divisible by`` respectively.

Interfaces
----------

* As of Twig 2.x, the following interfaces are deprecated and empty (they will
  be removed in Twig 3.0):

* ``Twig_CompilerInterface``     (use ``Twig_Compiler`` instead)
* ``Twig_LexerInterface``        (use ``Twig_Lexer`` instead)
* ``Twig_NodeInterface``         (use ``Twig_Node`` instead)
* ``Twig_ParserInterface``       (use ``Twig_Parser`` instead)
* ``Twig_ExistsLoaderInterface`` (merged with ``Twig_LoaderInterface``)
* ``Twig_TemplateInterface``     (use ``Twig_Template`` instead, and use
  those constants Twig_Template::ANY_CALL, Twig_Template::ARRAY_CALL,
  Twig_Template::METHOD_CALL)

Globals
-------

* As of Twig 2.x, the ability to register a global variable after the runtime
  or the extensions have been initialized is not possible anymore (but
  changing the value of an already registered global is possible).


text:
module ActiveModel
  class Serializer
    module Caching
      extend ActiveSupport::Concern

      included do
        with_options instance_writer: false, instance_reader: false do |serializer|
          serializer.class_attribute :_cache         # @api private : the cache store
          serializer.class_attribute :_fragmented    # @api private : @see ::fragmented
          serializer.class_attribute :_cache_key     # @api private : when present, is first item in cache_key.  Ignored if the serializable object defines #cache_key.
          serializer.class_attribute :_cache_only    # @api private : when fragment caching, whitelists cached_attributes. Cannot combine with except
          serializer.class_attribute :_cache_except  # @api private : when fragment caching, blacklists cached_attributes. Cannot combine with only
          serializer.class_attribute :_cache_options # @api private : used by CachedSerializer, passed to _cache.fetch
          #  _cache_options include:
          #    expires_in
          #    compress
          #    force
          #    race_condition_ttl
          #  Passed to ::_cache as
          #    serializer._cache.fetch(cache_key, @klass._cache_options)
          serializer.class_attribute :_cache_digest # @api private : Generated
        end
      end

      # Matches
      #  "c:/git/emberjs/ember-crm-backend/app/serializers/lead_serializer.rb:1:in `<top (required)>'"
      #  AND
      #  "/c/git/emberjs/ember-crm-backend/app/serializers/lead_serializer.rb:1:in `<top (required)>'"
      #  AS
      #  c/git/emberjs/ember-crm-backend/app/serializers/lead_serializer.rb
      CALLER_FILE = /
        \A       # start of string
        .+       # file path (one or more characters)
        (?=      # stop previous match when
          :\d+     # a colon is followed by one or more digits
          :in      # followed by a colon followed by in
        )
      /x

      module ClassMethods
        def inherited(base)
          super
          caller_line = caller[1]
          base._cache_digest = digest_caller_file(caller_line)
        end

        # Hashes contents of file for +_cache_digest+
        def digest_caller_file(caller_line)
          serializer_file_path = caller_line[CALLER_FILE]
          serializer_file_contents = IO.read(serializer_file_path)
          Digest::MD5.hexdigest(serializer_file_contents)
        rescue TypeError, Errno::ENOENT
          warn <<-EOF.strip_heredoc
            Cannot digest non-existent file: '#{caller_line}'.
            Please set `::_cache_digest` of the serializer
            if you'd like to cache it.
            EOF
          ''.freeze
        end

        def _skip_digest?
          _cache_options && _cache_options[:skip_digest]
        end

        # @api private
        # Used by FragmentCache on the CachedSerializer
        #  to call attribute methods on the fragmented cached serializer.
        def fragmented(serializer)
          self._fragmented = serializer
        end

        # Enables a serializer to be automatically cached
        #
        # Sets +::_cache+ object to <tt>ActionController::Base.cache_store</tt>
        #   when Rails.configuration.action_controller.perform_caching
        #
        # @param options [Hash] with valid keys:
        #   cache_store    : @see ::_cache
        #   key            : @see ::_cache_key
        #   only           : @see ::_cache_only
        #   except         : @see ::_cache_except
        #   skip_digest    : does not include digest in cache_key
        #   all else       : @see ::_cache_options
        #
        # @example
        #   class PostSerializer < ActiveModel::Serializer
        #     cache key: 'post', expires_in: 3.hours
        #     attributes :title, :body
        #
        #     has_many :comments
        #   end
        #
        # @todo require less code comments. See
        # https://github.com/rails-api/active_model_serializers/pull/1249#issuecomment-146567837
        def cache(options = {})
          self._cache =
            options.delete(:cache_store) ||
            ActiveModelSerializers.config.cache_store ||
            ActiveSupport::Cache.lookup_store(:null_store)
          self._cache_key = options.delete(:key)
          self._cache_only = options.delete(:only)
          self._cache_except = options.delete(:except)
          self._cache_options = options.empty? ? nil : options
        end

        # Value is from ActiveModelSerializers.config.perform_caching. Is used to
        # globally enable or disable all serializer caching, just like
        # Rails.configuration.action_controller.perform_caching, which is its
        # default value in a Rails application.
        # @return [true, false]
        # Memoizes value of config first time it is called with a non-nil value.
        # rubocop:disable Style/ClassVars
        def perform_caching
          return @@perform_caching if defined?(@@perform_caching) && !@@perform_caching.nil?
          @@perform_caching = ActiveModelSerializers.config.perform_caching
        end
        alias perform_caching? perform_caching
        # rubocop:enable Style/ClassVars

        # The canonical method for getting the cache store for the serializer.
        #
        # @return [nil] when _cache is not set (i.e. when `cache` has not been called)
        # @return [._cache] when _cache is not the NullStore
        # @return [ActiveModelSerializers.config.cache_store] when _cache is the NullStore.
        #   This is so we can use `cache` being called to mean the serializer should be cached
        #   even if ActiveModelSerializers.config.cache_store has not yet been set.
        #   That means that when _cache is the NullStore and ActiveModelSerializers.config.cache_store
        #   is configured, `cache_store` becomes `ActiveModelSerializers.config.cache_store`.
        # @return [nil] when _cache is the NullStore and ActiveModelSerializers.config.cache_store is nil.
        def cache_store
          return nil if _cache.nil?
          return _cache if _cache.class != ActiveSupport::Cache::NullStore
          if ActiveModelSerializers.config.cache_store
            self._cache = ActiveModelSerializers.config.cache_store
          else
            nil
          end
        end

        def cache_enabled?
          perform_caching? && cache_store && !_cache_only && !_cache_except
        end

        def fragment_cache_enabled?
          perform_caching? && cache_store &&
            (_cache_only && !_cache_except || !_cache_only && _cache_except)
        end
      end
    end
  end
end


text:
import java.util.function.Function;

class SomeClass implements IdeaBloopers11 {
  void foo(Function<String, String> f) {}

  void bar() {
    fo<caret>o(s -> {
      if (s.contains("a")) {
        throw baz(s);
      }
      return s;
    });
  }

  private NullPointerException baz(String s) {
    return null;
  }
}


text:
/*
 * The code was inspired by the similarly named JCTools class:
 * https://github.com/JCTools/JCTools/blob/master/jctools-core/src/main/java/org/jctools/queues/atomic
 */

package io.reactivesocket.internal.rx;

/**
 * A multi-producer single consumer unbounded queue.
 */
public final class MpscLinkedQueue<T> extends BaseLinkedQueue<T> {

    public MpscLinkedQueue() {
        super();
        LinkedQueueNode<T> node = new LinkedQueueNode<>();
        spConsumerNode(node);
        xchgProducerNode(node);// this ensures correct construction: StoreLoad
    }
    /**
     * {@inheritDoc}

     *

     * IMPLEMENTATION NOTES:

     * Offer is allowed from multiple threads.

     * Offer allocates a new node and:
     *

     *
Swaps it atomically with current producer node (only one producer 'wins')
     *
Sets the new node as the node following from the swapped producer node
     *

     * This works because each producer is guaranteed to 'plant' a new node and link the old node. No 2 producers can
     * get the same producer node as part of XCHG guarantee.
     *
     * @see MessagePassingQueue#offer(Object)
     * @see java.util.Queue#offer(java.lang.Object)
     */
    @Override
    public final boolean offer(final T nextValue) {
        final LinkedQueueNode<T> nextNode = new LinkedQueueNode<>(nextValue);
        final LinkedQueueNode<T> prevProducerNode = xchgProducerNode(nextNode);
        // Should a producer thread get interrupted here the chain WILL be broken until that thread is resumed
        // and completes the store in prev.next.
        prevProducerNode.soNext(nextNode); // StoreStore
        return true;
    }

    /**
     * {@inheritDoc}

     *

     * IMPLEMENTATION NOTES:

     * Poll is allowed from a SINGLE thread.

     * Poll reads the next node from the consumerNode and:
     *

     *
If it is null, the queue is assumed empty (though it might not be).
     *
If it is not null set it as the consumer node and return it's now evacuated value.
     *

     * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null
     * values are not allowed to be offered this is the only node with it's value set to null at any one time.
     *
     * @see MessagePassingQueue#poll()
     * @see java.util.Queue#poll()
     */
    @Override
    public final T poll() {
        LinkedQueueNode<T> currConsumerNode = lpConsumerNode(); // don't load twice, it's alright
        LinkedQueueNode<T> nextNode = currConsumerNode.lvNext();
        if (nextNode != null) {
            // we have to null out the value because we are going to hang on to the node
            final T nextValue = nextNode.getAndNullValue();
            spConsumerNode(nextNode);
            return nextValue;
        }
        else if (currConsumerNode != lvProducerNode()) {
            // spin, we are no longer wait free
            while((nextNode = currConsumerNode.lvNext()) == null);
            // got the next node...

            // we have to null out the value because we are going to hang on to the node
            final T nextValue = nextNode.getAndNullValue();
            spConsumerNode(nextNode);
            return nextValue;
        }
        return null;
    }

    @Override
    public final T peek() {
        LinkedQueueNode<T> currConsumerNode = lpConsumerNode(); // don't load twice, it's alright
        LinkedQueueNode<T> nextNode = currConsumerNode.lvNext();
        if (nextNode != null) {
            return nextNode.lpValue();
        } else
        if (currConsumerNode != lvProducerNode()) {
            // spin, we are no longer wait free
            while ((nextNode = currConsumerNode.lvNext()) == null);
            // got the next node...
            return nextNode.lpValue();
        }
        return null;
    }
}


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

namespace Alicization.Model.Demographics.Players
{
    class CultureWallet : IWallet
    {
        internal double balance { get; private set; }

        internal CultureWallet()
        {
            balance = 0.0;
        }

        internal CultureWallet(double startingBalance)
        {
            balance = startingBalance;
        }

        internal void Earn(double amount)
        {
            balance += amount;
        }
    }
}


text:
int main(int argc, char **argv)
{
	namespace po = boost::program_options;

	po::options_description description("Allowed options");
	description.add_options()
		("help,h", "display this help message")
		("file-prefix,f", po::value<std::string>(), "Ginkgo statistics file prefix");

	po::variables_map variablesMap;
	po::store(po::parse_command_line(argc, argv, description), variablesMap);
	po::notify(variablesMap);

	if (variablesMap.count("help"))
	{
		std::cout << description;
		return EXIT_SUCCESS;
	}

	if (variablesMap.count("file-prefix") > 0)
	{
		const auto filePrefix = variablesMap["file-prefix"].as<std::string>();
		const auto productionStatisticsFile = filePrefix + ".stats-produce";
		const auto consumptionDirectStatisticsFile = filePrefix + ".stats-consume-direct";
		const auto consumptionGeneralizedStatisticsFile = filePrefix + ".stats-consume-generalized";

		if (boost::filesystem::is_regular_file(productionStatisticsFile))
		{
			const auto productionAnalysis = ginkgo::feedbackLoop::analysis::ProductionAnalysis<ginkgo::Plain>::fromRawFile(productionStatisticsFile, 36000.0);
			productionAnalysis.write(filePrefix + ".analysis-produce");
		}

		if (boost::filesystem::is_regular_file(consumptionDirectStatisticsFile))
		{
			const auto consumptionDirectAnalysis = ginkgo::feedbackLoop::analysis::ConsumptionAnalysis<ginkgo::Plain>::fromRawFile(consumptionDirectStatisticsFile, 36000.0);
			consumptionDirectAnalysis.write(filePrefix + ".analysis-consume-direct");
		}

		if (boost::filesystem::is_regular_file(consumptionGeneralizedStatisticsFile))
		{
			const auto consumptionGeneralizedAnalysis = ginkgo::feedbackLoop::analysis::ConsumptionAnalysis<ginkgo::Plain>::fromRawFile(consumptionGeneralizedStatisticsFile, 36000.0);
			consumptionGeneralizedAnalysis.write(filePrefix + ".analysis-consume-generalized");
		}
	}

	return EXIT_SUCCESS;
}


text:
<!DOCTYPE html>

<title>User Scenarios · Teiid</title>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="" name="description">
<meta content="" name="author">
<link
	href="http://static.jboss.org/theme/css/bootstrap-community/2.3.1.4/bootstrap-community.min.css"
	media="screen" rel="stylesheet">

<link href="http://static.jboss.org/teiid/images/teiid_icon_16x.png"
	rel="shortcut icon">
<link
	href="http://static.jboss.org/teiid/images/apple-touch-icon-144x144-precomposed.png"
	rel="apple-touch-icon-precomposed" sizes="144x144">
<link
	href="http://static.jboss.org/teiid/images/apple-touch-icon-114x114-precomposed.png"
	rel="apple-touch-icon-precomposed" sizes="114x114">
<link
	href="http://static.jboss.org/teiid/images/apple-touch-icon-72x72-precomposed.png"
	rel="apple-touch-icon-precomposed" sizes="72x72">
<link
	href="http://static.jboss.org/teiid/images/apple-touch-icon-precomposed.png"
	rel="apple-touch-icon-precomposed">

Skip
					to navigation

Skip
					to content

A JBoss Project

				Red Hat

The data you want
					from the data you have.

Overview

About
												Teiid

The
												Basics

Quick
												Start

Roadmap

Tools

Downloads

Docs

Community

Wiki

User
												Forum

Mailing
												Lists

Chat

Blog

Twitter

Issues

Source Code

Contribute

GitHub

FishEye

Build

Follow Us

									<form class="navbar-search">
										<input class="search-query" id="projectsearch"
											placeholder="Search" type="text">
									</form>

				Teiid Homepage / About Teiid / User
					Scenarios

User Scenarios

Teiid User Scenarios

Teiid can be used by different people in a variety of
							scenarios. This page describes some of the most common scenarios
							for users of Teiid.

J2EE Developer

The typical Java J2EE developer is expected to have a
							moderate level of experience with Java, JDBC, one or more
							databases, and SQL, and a fair amount of experience specific to
							their current application server (assumed to be Weblogic,
							Websphere, or JBoss).

The J2EE Developer uses some form of IDE (JBDS, WSAD,
							Eclipse, NetBeans, IDEA) the majority of the time while building
							and testing their applications and is fairly dependent on the
							setup of that environment. The development machine is likely to
							be Windows or Linux with deployment occurring on Solaris, Linux,
							or Windows.

J2EE Developers already have the ability to manage and
							retrieve data from multiple JDBC sources via multiple JDBC
							connection pools. Teiid is useful in that it allows the J2EE
							Developer to query over those data sources in tandem without
							writing custom data access code. J2EE Developers expect Teiid to
							integrate smoothly into their application server and operate as a
							JDBC driver with minimal fuss and configuration.

Being able to use existing JDBC connection pools in the
							application server rather than manage new connections would be
							desirable as the system administrators can only see what appears
							via the application server administration tools.

							The J2EE Developer priorities are:

Seamless integration into the app server

Ability to query over multiple databases with one query

Simplicity and minimal configuration

Java Developer

The Java Developer is similar to the J2EE Developer, but
							are working either partially or completely outside a J2EE
							environment. The most common frameworks of use are likely Spring
							and Hibernate.

The Java Developer uses an IDE the majority of the time but
							may not be quite as dependent on it as the J2EE Developer. The
							development machine is likely to be Windows or Linux with
							deployment occurring on Solaris, Linux, or Windows.

The Java Developer is likely to have a higher degree of
							Java proficiency and more detailed knowledge of JDBC than the
							J2EE Developer, as the J2EE Developer is often abstracted from
							JDBC by the app server container. However, they may themselves be
							dependent to some degree on a framework such as Spring or
							Hibernate.

Java Developers want to integrate multiple sources and may
							find abstraction also somewhat compelling depending on the
							project. Like the J2EE Developer, the ability to query against
							multiple data sources in a single SQL statement can potentially
							be a huge benefit in designing their application and getting it
							working quickly.

The Java Developer can use custom JDBC APIs or other Teiid
							features more easily as there is no application server in the
							way, thus they may try a broader range of features.

Experienced Architect

							The Experienced Architect is often evaluating products for use in
							one or more projects. The desired product may actually be Red Hat Data Virtualization Platform in
							this case but the architect is trying out Teiid because it is
							available for download from the web. In any case, their goal is
							to test out what Teiid has to offer and the focus is on rapid
							data integration, not on interoperability with a particular
							existing framework or application.

							Experienced Architects value:

Ease of installation and short time to results

Well organized documentation

Performance

Admin Developer

The Admin Developer is involved in integrating Teiid into
							an existing application using a programmatic API. They are
							focused on how to automate Teiid-related activities necessary to
							the project such as metadata import and assembly, deployment, and
							administration.

							Admin Developers value:

A clean, well-defined API

Descriptive error logging

Thorough documentation in the form of JavaDocs

Tool Smith

The Tool Smith is involved in integrating Teiid into an
							existing application or process. They are focused on how to
							automate Teiid -related activities necessary to the project such
							as metadata import and assembly, deployment, and administration.

The Tool Smith is likely an expert at one or more flavors
							of Linux/Unix and less familiar with Java, other than from an
							invocation point of view. Tool Smiths are likely to be highly
							proficient in Ant, Perl, shell scripting languages, etc. Tool
							Smiths are also proxy users for automation as their engagement is
							typically transitory while things are automated, then hands off
							after that.

Tool Smiths value:

Scriptable execution (Ant tasks, command line
									utilities, etc)

Descriptive error logging

Thorough documentation

							Looking for a fully supported, certified Data Virtualization
							Platform?

tei·id (TEE-id)

									adj.     pertaining to a family of tropical
										American whip-tailed lizards noted for speed and agility.

									n.     a set of open source enterprise
										information integration tools noted for their ability to
										rapidly create data services that can quickly adapt to changes
										in your IT environment.

Blog Posts

Useful links

  About Teiid

  The Basics

										 Quick Start

  Tools

  Downloads

  Source Code

  Roadmap

 Apache
												License, Version 2.0

Managed
											by RHQ

								Desktop
									Wallpaper |  Project
									Swag

Navigate

Learn

Get Started

Forums

Get Involved

Download

Follow Us

Blog

Twitter

Google+

Contribute

Submit a bug

Write Code

Join the team

ASL 2.0 License

Dependencies of this project are primarily available under
						the ASL 2.0 and other open source licenses.

		 back to top


text:
package org.hipparchus.analysis.polynomials;

import org.hipparchus.exception.LocalizedCoreFormats;
import org.hipparchus.exception.MathIllegalArgumentException;
import org.hipparchus.exception.NullArgumentException;

/**
 * Smoothstep function factory.
 *

 * It allows for quick creation of common and generic smoothstep functions as defined here.
 */
public class SmoothStepFactory {

    /**
     * Private constructor.
     *

     * This class is a utility class, it should neither have a public nor a default constructor. This private
     * constructor prevents the compiler from generating one automatically.
     */
    private SmoothStepFactory() {
        // Empty constructor
    }

    /**
     * Get the {@link SmoothStepFunction clamping smoothstep function}.
     *
     * @return clamping smoothstep function
     */
    public static SmoothStepFunction getClamp() {
        return getGeneralOrder(0);
    }

    /**
     * Get the {@link SmoothStepFunction cubic smoothstep function}.
     *
     * @return cubic smoothstep function
     */
    public static SmoothStepFunction getCubic() {
        return getGeneralOrder(1);
    }

    /**
     * Get the {@link SmoothStepFunction quintic smoothstep function}.
     *
     * @return quintic smoothstep function
     */
    public static SmoothStepFunction getQuintic() {
        return getGeneralOrder(2);
    }

    /**
     * Create a {@link SmoothStepFunction smoothstep function} of order 2N + 1.
     *

     * It uses the general smoothstep equation presented here :
     * $S_{N}(x) = \sum_{n=0}^{N} \begin{pmatrix} -N-1 \\ n \end{pmatrix} \begin{pmatrix} 2N+1 \\ N-n \end{pmatrix} x^{N+n+1}$
     *
     * @param N determines the order of the output smoothstep function (=2N + 1)
     * @return smoothstep function of order 2N + 1
     */
    public static SmoothStepFunction getGeneralOrder(final int N) {

        final int twoNPlusOne = 2 * N + 1;

        final double[] coefficients = new double[twoNPlusOne + 1];

        int n = N;
        for (int i = twoNPlusOne; i > N; i--) {
            coefficients[i] = pascalTriangle(-N - 1, n) * pascalTriangle(2 * N + 1, N - n);
            n--;
        }

        return new SmoothStepFunction(coefficients);
    }

    /**
     * Returns binomial coefficient without explicit use of factorials, which can't be used with negative integers
     *
     * @param k subset in set
     * @param n set
     * @return number of subset {@code k} in global set {@code n}
     */
    private static int pascalTriangle(final int k, final int n) {

        int result = 1;
        for (int i = 0; i < n; i++) {
            result *= (k - i) / (i + 1);
        }

        return result;
    }

    /**
     * Check that input is between [0:1].
     *
     * @param input input to be checked
     * @throws MathIllegalArgumentException if input is not between [0:1]
     */
    public static void checkBetweenZeroAndOneIncluded(final double input) throws MathIllegalArgumentException {
        if (input < 0 || input > 1) {
            throw new MathIllegalArgumentException(
                    LocalizedCoreFormats.INPUT_EXPECTED_BETWEEN_ZERO_AND_ONE_INCLUDED);
        }
    }

    /**
     * Smoothstep function as defined here.
     *

     * It is used to do a smooth transition between the "left edge" and the "right edge" with left edge assumed to be
     * smaller than right edge.
     *

     * By definition, for order n > 1 and input x, a smoothstep function respects at least the following properties :
     *

     *
f(x <= leftEdge) = 0 and f(x >= rightEdge) = 1

     *
f'(leftEdge) = f'(rightEdge) = 0

     *

     * If x is normalized between edges, we have at least :
     *

     *
f(x <= 0) = 0 and f(x >= 1) = 1

     *
f'(0) = f'(1) = 0

     *

     * Smoothstep functions of higher order n will have their higher time derivatives also equal to zero at edges...
     */
    public static class SmoothStepFunction extends PolynomialFunction {

        /**
         * Construct a smoothstep with the given coefficients. The first element of the coefficients array is the
         * constant term.  Higher degree coefficients follow in sequence.  The degree of the resulting polynomial is the
         * index of the last non-null element of the array, or 0 if all elements are null.
         *

         * The constructor makes a copy of the input array and assigns the copy to the coefficients property.

         *
         * @param c Smoothstep polynomial coefficients.
         * @throws NullArgumentException if {@code c} is {@code null}.
         * @throws MathIllegalArgumentException if {@code c} is empty.
         */
        private SmoothStepFunction(final double[] c) throws MathIllegalArgumentException, NullArgumentException {
            super(c);
        }

        /**
         * Compute the value of the smoothstep for the given argument normalized between edges.
         *
         * @param xNormalized Normalized argument for which the function value should be computed. It is
         *         expected to be between [0:1] and will throw an exception otherwise.
         * @return the value of the polynomial at the given point.
         * @see org.hipparchus.analysis.UnivariateFunction#value(double)
         */
        @Override
        public double value(final double xNormalized) {
            checkBetweenZeroAndOneIncluded(xNormalized);
            return super.value(xNormalized);
        }

        /**
         * Compute the value of the smoothstep function for the given edges and argument.
         *

         * Note that right edge is expected to be greater than left edge. It will throw an exception otherwise.
         *
         * @param leftEdge left edge
         * @param rightEdge right edge
         * @param x Argument for which the function value should be computed
         * @return the value of the polynomial at the given point
         * @throws MathIllegalArgumentException if right edge is greater than left edge
         * @see org.hipparchus.analysis.UnivariateFunction#value(double)
         */
        public double value(final double leftEdge, final double rightEdge, final double x)
                throws MathIllegalArgumentException {

            checkInputEdges(leftEdge, rightEdge);

            final double xClamped = clampInput(leftEdge, rightEdge, x);

            final double xNormalized = normalizeInput(leftEdge, rightEdge, xClamped);

            return super.value(xNormalized);
        }

        /**
         * Check that left edge is lower than right edge. Otherwise, throw an exception.
         *
         * @param leftEdge left edge
         * @param rightEdge right edge
         */
        private void checkInputEdges(final double leftEdge, final double rightEdge) {
            if (leftEdge > rightEdge) {
                throw new MathIllegalArgumentException(LocalizedCoreFormats.RIGHT_EDGE_GREATER_THAN_LEFT_EDGE,
                                                       leftEdge, rightEdge);
            }
        }

        /**
         * Clamp input between edges.
         *
         * @param leftEdge left edge
         * @param rightEdge right edge
         * @param x input to clamp
         * @return clamped input
         */
        private double clampInput(final double leftEdge, final double rightEdge, final double x) {
            if (x <= leftEdge) {
                return leftEdge;
            }
            if (x >= rightEdge) {
                return rightEdge;
            }
            return x;
        }

        /**
         * Normalize input between left and right edges.
         *
         * @param leftEdge left edge
         * @param rightEdge right edge
         * @param x input to normalize
         * @return normalized input
         */
        private double normalizeInput(final double leftEdge, final double rightEdge, final double x) {
            return (x - leftEdge) / (rightEdge - leftEdge);
        }
    }

}


text:
package cmwell.bg

import cmwell.domain._
import cmwell.common._
import com.typesafe.config.{Config, ConfigFactory}
import com.typesafe.scalalogging.LazyLogging
import org.joda.time.{DateTime, DateTimeZone}

import scala.annotation.tailrec

/**
  * Created by israel on 12/8/15.
  */
object Merger {
  def apply() = new Merger(ConfigFactory.load())
}

sealed trait MergeResponse {
  def tids: Seq[String]
  def evictions: Seq[(String, Option[String])]
  def merged: Option[Infoton]
  def path: String
  def extra: Option[String]
}
final case class NullUpdate(path: String, tids: Seq[String], evictions: Seq[(String, Option[String])], extra: Option[String])
  extends MergeResponse {
  override def merged = None
}
final case class RealUpdate(infoton: Infoton, tids: Seq[String], evictions: Seq[(String, Option[String])], extra: Option[String])
  extends MergeResponse {
  override lazy val merged = Some(infoton)

  override def path: String = infoton.path
}

class Merger(config: Config) extends LazyLogging {

  val defaultDC = config.getString("cmwell.dataCenter.id")

  private def merge_f(last_fields: Option[Map[String, Set[FieldValue]]],
                      current_fields: Option[Map[String, Set[FieldValue]]]): Option[Map[String, Set[FieldValue]]] = {

    val previousFields = if (last_fields.exists(_.isEmpty)) None else last_fields
    val currentFields = if (current_fields.exists(_.isEmpty)) None else current_fields

    (previousFields, currentFields) match {
      case (None, current)  => current
      case (previous, None) => previous
      case (Some(last), Some(curr)) => {
        val keys = last.keySet ++ curr.keySet
        val f: Map[String, Set[FieldValue]] = keys.map { k =>
          val v1 = last.getOrElse(k, Set.empty[FieldValue])
          val v2 = curr.getOrElse(k, Set.empty[FieldValue])
          k -> (v1 ++ v2)
        }(collection.breakOut)
        Some(f)
      }
    }
  }

  private def delete_f(current_fields: Option[Map[String, Set[FieldValue]]],
                       deleteFields: Map[String, Set[FieldValue]]): Option[Map[String, Set[FieldValue]]] = {
    val (asterix, filterQuad): (Boolean, Option[String] => Boolean) = deleteFields.get("*") match {
      case Some(quads) if quads.contains(FNull(Some("*"))) =>
        true -> { _ =>
          true
        }
      case Some(quads) => true -> { quads.collect { case FNull(q) => q } }
      case None =>
        false -> { _ =>
          false
        }
    }
    val delete_fields: Map[String, Set[FieldValue]] = deleteFields.filterKeys(_ != "*")

    current_fields.map(_.map {
      case (k, vs) =>
        //if we have a wild card field delete, we must check every value for it's quad (that's why we added the `|| asterix`)
        if (delete_fields.keySet(k) || asterix) {
          if (delete_fields.get(k).collect { case xs => xs.isEmpty }.getOrElse(false))
            (k, Set.empty[FieldValue])
          else {
            val v = vs.filterNot(
              fv =>
                filterQuad(fv.quad) || (delete_fields.contains(k) && delete_fields(k).exists {
                  case FNull(Some("*")) => true
                  case FNull(q)         => fv.quad == q
                  case fvtd =>
                    fvtd.value == fv.value && (fvtd.quad match {
                      case None      => fv.quad.isEmpty
                      case Some("*") => true
                      case Some(q)   => fv.quad.fold(false)(q.==)
                    })
                })
            )
            (k, v)
          }
        } else {
          (k, vs)
        }
    }.filterNot { case (_, s) => s.isEmpty })
  }

  private def update_f(current_fields: Option[Map[String, Set[FieldValue]]],
                       delete_fields: Map[String, Set[FieldValue]],
                       add_fields: Map[String, Set[FieldValue]]): Option[Map[String, Set[FieldValue]]] = {
    val after_delete = delete_f(current_fields, delete_fields)
    val after_update = merge_f(after_delete, Some(add_fields))
    after_update
  }

  private def delete_merge(prev_infoton: Infoton,
                           fields: Map[String, Set[FieldValue]],
                           lastModified: DateTime,
                           protocol: Option[String]): Infoton = {
    prev_infoton match {
      case ObjectInfoton(path, _, _, _, current_fields, _, _) =>
        val newFields = delete_f(current_fields, fields)
        if (newFields.nonEmpty) ObjectInfoton(path, defaultDC, None, lastModified, newFields, protocol = protocol)
        else DeletedInfoton(path, defaultDC, None, lastModified)
      case f @ FileInfoton(_, _, _, _, current_fields, _, _, _) =>
        f.copy(indexTime = None, lastModified = lastModified, fields = delete_f(current_fields, fields), protocol = protocol)
      case l @ LinkInfoton(_, _, _, _, current_fields, _, _, _, _) =>
        l.copy(indexTime = None, lastModified = lastModified, fields = delete_f(current_fields, fields), protocol = protocol)
      case i: DeletedInfoton => i // if we got a delete on delete we need ignore the create of delete
      case j =>
        throw new NotImplementedError(s"kind [${j.kind}] uuid [${prev_infoton.uuid}] info [$j]")
    }
  }

  private def update_merge(current_infoton: Infoton,
                           delete_fields: Map[String, Set[FieldValue]],
                           add_fields: Map[String, Set[FieldValue]],
                           lastModified: DateTime,
                           protocol: Option[String]): Infoton = {
    val u_f = update_f(current_infoton.fields, delete_fields, add_fields)
    current_infoton match {
      case ObjectInfoton(path, dc, idxT, lm, current_fields, _, _) if u_f.exists(_.nonEmpty) =>
        ObjectInfoton(path, defaultDC, None, lastModified, u_f, protocol = protocol)
      case ObjectInfoton(path, dc, idxT, lm, current_fields, _, _) =>
        DeletedInfoton(path, defaultDC, None, lastModified)
      case FileInfoton(path, dc, idxT, lm, current_fields, c_fc, _, _) =>
        FileInfoton(path, defaultDC, None, lastModified, u_f, c_fc, protocol = protocol)
      case LinkInfoton(path, dc, idxT, lm, current_fields, c_to, c_linkType, _, _) =>
        LinkInfoton(path, defaultDC, None, lastModified, u_f, c_to, c_linkType, protocol = protocol)
      case DeletedInfoton(path, dc, idxT, lm, _) if u_f.exists(_.nonEmpty) =>
        // if we got update after a delete infoton we create a new one
        ObjectInfoton(path, defaultDC, None, lastModified, u_f, protocol = protocol)
      case _ =>
        // might happen when e.g: writing a "skeleton" on top of a deleted infoton.
        logger.warn(s"kind [${current_infoton.kind}] uuid [${current_infoton.uuid}] info [$current_infoton]")
        current_infoton
    }
  }

  private def write_merge(prev_infoton: Infoton, current_infoton: Infoton): Infoton = {
    // we build the new infoton based on the old one first we need to merge the fields
    current_infoton match {
      case ObjectInfoton(path, dc, _, lastModified, current_fields, _, protocol) =>
        prev_infoton match {
          case ObjectInfoton(_, _, _, _, prev_fields, _, _) =>
            ObjectInfoton(path, defaultDC, None, lastModified, merge_f(prev_fields, current_fields), protocol = protocol)
          case FileInfoton(_, _, _, _, prev_fields, perv_fc, _, protocol) =>
            FileInfoton(path, defaultDC, None, lastModified, merge_f(prev_fields, current_fields), perv_fc, protocol = protocol)
          case LinkInfoton(_, _, _, _, prev_fields, prev_to, prev_linkType, _, protocol) =>
            LinkInfoton(path, defaultDC, None, lastModified, merge_f(prev_fields, current_fields), prev_to, prev_linkType, protocol = protocol)
          case DeletedInfoton(_, _, _, _, _) =>
            current_infoton
          case _ =>
            throw new NotImplementedError(s"was trying to write_merge o[ $current_infoton ] on top of[ $prev_infoton ]")
        }
      case FileInfoton(path, dc, _, lastModified, current_fields, c_fc, _, protocol) =>
        prev_infoton match {
          case ObjectInfoton(_, _, _, _, prev_fields, _, _) =>
            FileInfoton(path, defaultDC, None, lastModified, merge_f(prev_fields, current_fields), c_fc, protocol = protocol)
          case FileInfoton(_, _, _, _, prev_fields, prev_fc, _, _) =>
            FileInfoton(path,
              defaultDC,
              None,
              lastModified,
              merge_f(if (prev_fields.exists(_.nonEmpty)) prev_fields else None, current_fields),
              c_fc.orElse(prev_fc),
              protocol = protocol)
          case LinkInfoton(_, _, _, _, prev_fields, _, _, _, _) if prev_fields.exists(_.nonEmpty) =>
            FileInfoton(path, defaultDC, None, lastModified, merge_f(prev_fields, current_fields), c_fc, protocol = protocol)
          case _: LinkInfoton | _: DeletedInfoton =>
            current_infoton
          case _ =>
            throw new NotImplementedError(s"was trying to write_merge f[ $current_infoton ] on top of[ $prev_infoton ]")

        }
      case LinkInfoton(path, dc, _, lastModified, current_fields, c_to, c_linkType, _, protocol) =>
        prev_infoton match {
          case ObjectInfoton(_, _, _, _, prev_fields, _, _) =>
            LinkInfoton(path, defaultDC, None, lastModified, merge_f(prev_fields, current_fields), c_to, c_linkType, protocol = protocol)
          case LinkInfoton(_, _, _, _, prev_fields, _, _, _, _) =>
            LinkInfoton(path, defaultDC, None, lastModified, merge_f(prev_fields, current_fields), c_to, c_linkType, protocol = protocol)
          case FileInfoton(_, _, _, _, prev_fields, _, _, _) if prev_fields.exists(_.nonEmpty) =>
            LinkInfoton(path, defaultDC, None, lastModified, merge_f(prev_fields, current_fields), c_to, c_linkType, protocol = protocol)
          case _: DeletedInfoton | _: FileInfoton =>
            current_infoton
          case _ =>
            throw new NotImplementedError(s"was trying to write_merge l[ $current_infoton ] on top of[ $prev_infoton ]")
        }
      case _ =>
        throw new NotImplementedError(s"was trying to write_merge [ $current_infoton ] on top of[ $prev_infoton ]")
    }
  }

  def merge(baseInfoton: Option[Infoton], cmds: Seq[SingleCommand]): MergeResponse = {

    def ensurePrevUUID(base: Infoton, prevUUID: Option[String])(
      getMerged: Infoton => Option[Infoton]
    ): (Option[Infoton], Option[String]) = {
      lazy val merged: (Option[Infoton], Option[String]) = getMerged(base) -> None
      prevUUID.fold(merged) { pUUID =>
        if (base.uuid == pUUID) merged
        else Some(base) -> Some(s"expected:$pUUID,actual:${base.uuid}")
      }
    }

    def ensurePrevNone(prevUUID: Option[String])(getApplied: => Option[Infoton]): (Option[Infoton], Option[String]) =
      prevUUID match {
        case None | Some("")      => getApplied -> None
        case Some(someMadeUpUUID) => None -> Some(s"expected:$someMadeUpUUID,actual:none")
      }

    /**
      * @return a tuple of the merged infoton (or prev version if wasn't merged)
      *         and option containing eviction reson if was evicted
      */
    def do_merge(base: Option[Infoton], cmd: SingleCommand): (Option[Infoton], Option[String]) = {
      cmd match {
        case WriteCommand(currInfoton, _, prevUUID) =>
          base match {
            case Some(last_infoton) => ensurePrevUUID(last_infoton, prevUUID)(i => Some(write_merge(i, currInfoton)))
            case None               => ensurePrevNone(prevUUID)(Some(currInfoton))
          }
        case DeleteAttributesCommand(_, fields, lastModified, _, prevUUID, protocol) =>
          base match {
            case Some(last_infoton) =>
              ensurePrevUUID(last_infoton, prevUUID)(i => Some(delete_merge(i, fields, lastModified, protocol)))
            case None => ensurePrevNone(prevUUID)(None)
          }
        case UpdatePathCommand(path, deleteFields, updateFields, lastModified, _, prevUUID, protocol) =>
          base match {
            case Some(last_infoton) =>
              ensurePrevUUID(last_infoton, prevUUID)(
                i => Some(update_merge(i, deleteFields, updateFields, lastModified, protocol))
              )
            case None =>
              ensurePrevNone(prevUUID)(Some(ObjectInfoton(path, defaultDC, None, lastModified, Some(updateFields), protocol = protocol)))
          }
        case DeletePathCommand(path, lastModified, _, prevUUID) =>
          base match {
            case sdi @ Some(di: DeletedInfoton) => ensurePrevUUID(di, prevUUID)(_ => sdi)
            case Some(infoton) =>
              ensurePrevUUID(infoton, prevUUID)(_ => Some(DeletedInfoton(path, defaultDC, None, lastModified)))
            case None => ensurePrevNone(prevUUID)(None)
          }
        case _ => throw new NotImplementedError(s"no impl for [ $cmd ]")
      }
    }

    /**
      * @param prev optional previous infoton
      * @param cmds commands to apply on prev
      * @param evictionsAcc evictions accumulator
      * @return a tuple of the merged infoton and:
      *         list of either:
      *         - eviction reason with optional TID
      *         - TID
      *
      *         note that the returned list may be smaller than the number of commands.
      *         a command which went smoothly and is not tracked,
      *         won't contribute any element to this list.
      */
    @tailrec
    def merge_recurse(
                       prev: Option[Infoton],
                       cmds: Seq[SingleCommand],
                       evictionsAcc: List[Either[(String, Option[String]), String]] = Nil
                     ): (Option[Infoton], List[Either[(String, Option[String]), String]]) = {

      if (cmds.isEmpty) None -> evictionsAcc
      else {
        val (merged, eviction) = do_merge(prev, cmds.head)
        val tid = cmds.head.trackingID
        val evAcc = eviction.fold(tid.fold(evictionsAcc)(Right(_) :: evictionsAcc))(e => Left((e, tid)) :: evictionsAcc)
        if (cmds.size == 1) merged -> evAcc
        else merge_recurse(merged, cmds.tail, evAcc)
      }
    }

    val (merged, evictionsAndTIDs) = merge_recurse(baseInfoton, cmds)

    val (evictions, trackingIds) = cmwell.util.collections.partitionWith(evictionsAndTIDs)(identity)

    merged match {
      case Some(i) if !baseInfoton.exists(_.isSameAs(i)) =>
        val (infoton, extraData) = baseInfoton.fold(i -> Option.empty[String]) { j =>
          if (j.lastModified.getMillis < i.lastModified.getMillis) i -> None
          else {
            logger.info(s"PlusDebug: There was an infoton [$j] in the system that is not the same as the merged one [$i] but has earlier lastModified. " +
              s"Adding 1 milli")
            val newLastModified = new DateTime(j.lastModified.getMillis + 1L, DateTimeZone.UTC)
            i.copyInfoton(lastModified = newLastModified) -> Some(newLastModified.getMillis.toString)
          }
        }
        RealUpdate(infoton, trackingIds, evictions, extraData)
      case Some(i) if baseInfoton.exists(bi => bi.isSameAs(i)
        && bi.indexTime.isEmpty
        && new DateTime(bi.lastModified, DateTimeZone.UTC) == new DateTime(cmds.last.lastModified, DateTimeZone.UTC)) =>
        //We are also testing for indexTime in order to handle BG recovery mode.
        //The merge process sets the last modified to be as the base one (in case they are the same).
        //If the merged infoton is the same as the the base one but the "should be" lastModified is different it means it's a null update
        //and not a replay after crash (it happens a lot with parents in clustered env.). This is the reason the the last command modified check
        logger.warn(s"Merged infoton [$i] is the same as the base infoton [${baseInfoton.get}] but the base infoton doesn't have index time!")
        RealUpdate(i.copyInfoton(lastModified = baseInfoton.get.lastModified), trackingIds, evictions, extra = None)
      case _ => NullUpdate(baseInfoton.fold(cmds.head.path)(_.path), trackingIds, evictions, extra = None)
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<root>
	<servlet name="wiki" uri-pattern="*.htm|*.html">
		<headers>
			<property name="Content-Type" value="text/html;${env:prop:wikiup.charset}"/>
		</headers>
		<processor class="chain">
			<module name="file-resource" class="file-resource"/>
			<module name="ssi" class="ssi"/>
			<module name="wikiup" class="wikiup"/>
		</processor>
		<context name="param" class="parameter"/>
		<context name="i18n" class="i18n" locale="$param.locale"/>
	</servlet>
	<servlet name="do" uri-pattern="*.do">
		<context name="param" class="parameter"/>
	</servlet>
	<servlet name="x" uri-pattern="*.x" extends="do">
		<headers>
			<property name="Content-Type" value="text/xml;${env:prop:wikiup.charset}"/>
		</headers>
		<processor class="xml"/>
	</servlet>
	<servlet name="json" uri-pattern="*.json" extends="do">
		<headers>
			<property name="Content-Type" value="text/javascript;${env:prop:wikiup.charset}"/>
		</headers>
		<processor class="json"/>
	</servlet>
</root>