namespace dawn_native { namespace null {

    using BindGroup = BindGroupBase;
    using BindGroupLayout = BindGroupLayoutBase;
    using BlendState = BlendStateBase;
    class Buffer;
    using BufferView = BufferViewBase;
    class CommandBuffer;
    using ComputePipeline = ComputePipelineBase;
    using DepthStencilState = DepthStencilStateBase;
    class Device;
    using InputState = InputStateBase;
    using PipelineLayout = PipelineLayoutBase;
    class Queue;
    using RenderPassDescriptor = RenderPassDescriptorBase;
    using RenderPipeline = RenderPipelineBase;
    using Sampler = SamplerBase;
    using ShaderModule = ShaderModuleBase;
    class SwapChain;
    using Texture = TextureBase;
    using TextureView = TextureViewBase;

    struct NullBackendTraits {
        using BindGroupType = BindGroup;
        using BindGroupLayoutType = BindGroupLayout;
        using BlendStateType = BlendState;
        using BufferType = Buffer;
        using BufferViewType = BufferView;
        using CommandBufferType = CommandBuffer;
        using ComputePipelineType = ComputePipeline;
        using DepthStencilStateType = DepthStencilState;
        using DeviceType = Device;
        using InputStateType = InputState;
        using PipelineLayoutType = PipelineLayout;
        using QueueType = Queue;
        using RenderPassDescriptorType = RenderPassDescriptor;
        using RenderPipelineType = RenderPipeline;
        using SamplerType = Sampler;
        using ShaderModuleType = ShaderModule;
        using SwapChainType = SwapChain;
        using TextureType = Texture;
        using TextureViewType = TextureView;
    };

    template <typename T>
    auto ToBackend(T&& common) -> decltype(ToBackendBase<NullBackendTraits>(common)) {
        return ToBackendBase<NullBackendTraits>(common);
    }

    struct PendingOperation {
        virtual ~PendingOperation() = default;
        virtual void Execute() = 0;
    };

    class Device : public DeviceBase {
      public:
        Device();
        ~Device();

        BindGroupBase* CreateBindGroup(BindGroupBuilder* builder) override;
        BlendStateBase* CreateBlendState(BlendStateBuilder* builder) override;
        BufferViewBase* CreateBufferView(BufferViewBuilder* builder) override;
        CommandBufferBase* CreateCommandBuffer(CommandBufferBuilder* builder) override;
        DepthStencilStateBase* CreateDepthStencilState(DepthStencilStateBuilder* builder) override;
        InputStateBase* CreateInputState(InputStateBuilder* builder) override;
        RenderPassDescriptorBase* CreateRenderPassDescriptor(
            RenderPassDescriptorBuilder* builder) override;
        RenderPipelineBase* CreateRenderPipeline(RenderPipelineBuilder* builder) override;
        SwapChainBase* CreateSwapChain(SwapChainBuilder* builder) override;
        TextureViewBase* CreateTextureView(TextureViewBuilder* builder) override;

        void TickImpl() override;

        void AddPendingOperation(std::unique_ptr<PendingOperation> operation);
        std::vector<std::unique_ptr<PendingOperation>> AcquirePendingOperations();

      private:
        ResultOrError<BindGroupLayoutBase*> CreateBindGroupLayoutImpl(
            const BindGroupLayoutDescriptor* descriptor) override;
        ResultOrError<BufferBase*> CreateBufferImpl(const BufferDescriptor* descriptor) override;
        ResultOrError<ComputePipelineBase*> CreateComputePipelineImpl(
            const ComputePipelineDescriptor* descriptor) override;
        ResultOrError<PipelineLayoutBase*> CreatePipelineLayoutImpl(
            const PipelineLayoutDescriptor* descriptor) override;
        ResultOrError<QueueBase*> CreateQueueImpl() override;
        ResultOrError<SamplerBase*> CreateSamplerImpl(const SamplerDescriptor* descriptor) override;
        ResultOrError<ShaderModuleBase*> CreateShaderModuleImpl(
            const ShaderModuleDescriptor* descriptor) override;
        ResultOrError<TextureBase*> CreateTextureImpl(const TextureDescriptor* descriptor) override;

        std::vector<std::unique_ptr<PendingOperation>> mPendingOperations;
    };

    class Buffer : public BufferBase {
      public:
        Buffer(Device* device, const BufferDescriptor* descriptor);
        ~Buffer();

        void MapReadOperationCompleted(uint32_t serial, void* ptr, bool isWrite);

      private:
        void SetSubDataImpl(uint32_t start, uint32_t count, const uint8_t* data) override;
        void MapReadAsyncImpl(uint32_t serial, uint32_t start, uint32_t count) override;
        void MapWriteAsyncImpl(uint32_t serial, uint32_t start, uint32_t count) override;
        void UnmapImpl() override;

        void MapAsyncImplCommon(uint32_t serial, uint32_t start, uint32_t count, bool isWrite);

        std::unique_ptr<char[]> mBackingData;
    };

    class CommandBuffer : public CommandBufferBase {
      public:
        CommandBuffer(CommandBufferBuilder* builder);
        ~CommandBuffer();

      private:
        CommandIterator mCommands;
    };

    class Queue : public QueueBase {
      public:
        Queue(Device* device);
        ~Queue();

      private:
        void SubmitImpl(uint32_t numCommands, CommandBufferBase* const* commands) override;
    };

    class SwapChain : public SwapChainBase {
      public:
        SwapChain(SwapChainBuilder* builder);
        ~SwapChain();

      protected:
        TextureBase* GetNextTextureImpl(const TextureDescriptor* descriptor) override;
        void OnBeforePresent(TextureBase*) override;
    };

}}  // namespace dawn_native::null

#endif  // DAWNNATIVE_NULL_NULLBACKEND_H_


A great community awaits.

Join

  		<img src="<?php echo get_template_directory_uri();; ?>/assets/img/logoespacio.png">

        <?php
          if (has_nav_menu('primary_navigation')) :
            wp_nav_menu(array('theme_location' => 'primary_navigation', 'menu_class' => 'nav navbar-nav'));
          endif;
        ?>

<?php wp_footer(); ?>


import sys
import os
import re
import subprocess as sp

try:
    from .version import __version__
except ImportError:
    __version__ = 'unknown'

def indent_level(line):
    """Get the indent level for a line of mkvinfo output.
    Returns -1 if *line* is not the correct format."""
    m = re.search(r'^\|( *)\+', line)
    if not m:
        return -1
    return len(m.group(1))

class TrackLineHandler:
    'Parse a line of (English) mkvinfo output inside "A track".'
    _number = '|  + Track number: '
    _type = '|  + Track type: '
    _codec = '|  + Codec ID: '
    _lang = '|  + Language: '
    _duration = '|  + Default duration: '
    fps = r'\((.*?) frames/fields per second for a video track\)'
    _fps_re = re.compile(fps)

    def __init__(self, infodict):
        self._info = infodict

    def _findvalue(self, key, s):
        idx = s.find(key)
        if idx != -1:
            return s[idx + len(key):]
        return None

    def line(self, handlers, l):
        self._track = self._info['tracks'][-1]
        cls = TrackLineHandler
        ind = indent_level(l)
        if ind == -1 or ind < 2:
            handlers.pop(-1)
            return False
        number = self._findvalue(cls._number, l)
        if number:
            endidx = number.find(' ')
            if endidx == -1:
                number = int(number)
            else:
                number = int(number[:endidx])
            self._track['number'] = number - 1
            return True
        typ = self._findvalue(cls._type, l)
        if typ:
            self._track['type'] = typ
            return True
        codec = self._findvalue(cls._codec, l)
        if codec:
            if codec[0] in ('V', 'A', 'S') and len(codec) > 1 and codec[1] == '_':
                codec = codec[2:]
            self._track['codec'] = codec
            return True
        lang = self._findvalue(cls._lang, l)
        if lang:
            self._track['language'] = lang
            return True
        if self._track.get('type', '') == 'video':
            duration = self._findvalue(cls._duration, l)
            if duration:
                match = cls._fps_re.search(l)
                if match:
                    self._track['fps'] = float(match.group(1))
                    return True
        return True

class MainLineHandler:
    "Parse a line of (locale='en_US') mkvinfo output."
    def __init__(self, infodict):
        self._info = infodict
        self._track = TrackLineHandler(infodict)

    def line(self, handlers, l):
        if l.startswith('|+ Segment tracks'):
            self._info.setdefault('tracks', [])
            return True
        elif l.startswith('| + Track'):
            self._info.setdefault('tracks', [])
            self._info['tracks'].append({})
            handlers.append(self._track)
            return True
        return True

def info_locale_opts(locale):
    """Example usage with *infostring*::

        opts = info_locale_opts('en_US')
        opts.setdefault('arguments', [])
        opts['arguments'].extend(['-x', '-r', 'mkvinfo.log'])
        opts.setdefault('env', {})
        opts['env']['MTX_DEBUG'] = 'topic'
        print infostring(mkv, **opts)
    """
    return {'arguments': ['--ui-language', locale]}

def infostring(mkv, env=None, arguments=[], errorfunc=sys.exit, mkvinfo=None):
    """Run mkvinfo on the given *mkv* and returns stdout as a single string.

    On failure, calls *errorfunc* with an error string.

    It's likely you'll want to set *env* or *arguments* to use ``'en_US'``
    locale, since that is what *infodict* requires. See
    *info_locale_opts*.
    """
    if not mkvinfo:
        mkvinfo = 'mkvinfo'
    cmd = [mkvinfo] + arguments + [mkv]
    opts = {}
    if env is not None:
        env.setdefault('PATH', os.environ.get('PATH', ''))
        env.setdefault('SystemRoot', os.environ.get('SystemRoot', ''))
        opts = {'env': env}
    proc = sp.Popen(
        cmd, stdout=sp.PIPE, stderr=sp.PIPE, close_fds=True, **opts
    )
    out, err = proc.communicate()
    if proc.returncode != 0:
        if err is not str:
            err = err.decode('utf_8')
        errorfunc('command failed: ' + err.rstrip('\n'))
    if out is not str:
        out = out.decode('utf_8')
    return out

def infodict(lines):
    """Take a list of *lines* of ``locale='en_US'`` mkvinfo output and return a
    dictionary of info."""
    infod = {'lines': lines}
    handlers = [MainLineHandler(infod)]
    for l in lines:
        while not handlers[-1].line(handlers, l):
            if not handlers:
                break
        if not handlers:
            break
    return infod

if __name__ == '__main__':
    from pprint import pprint
    mkv = sys.argv[1]
    s = infostring(mkv, arguments=['--ui-language', 'en_US'])
    d = infodict(s.rstrip('\n').split('\n'))
    del d['lines']
    pprint(d)


> ## Note: Yosemite (and later)
>
> Starting in Yosemite (10.10), the wrapper program does not seem to
> be needed for pasteboard access. It may still be useful for some
> [other services][other], however.

[other]: #beyond-pasteboard-access

The basic configuration is to set *tmux*’s `default-command` so that
your interactive shell ends up reattached to the user bootstrap
namespace:

    set-option -g default-command 'reattach-to-user-namespace -l zsh'

Since the “attachment status” is inherited by child processes, this
configuration will ensure that all the commands started from your
shell will also be properly attached.

# Configuration Alternatives

## Cross-Platform Conditional Usage

Some users like to share identical configuration files (including
`.tmux.conf`) with systems where the wrapper program is not
available (e.g. same files on both OS X and Linux). Starting with
*tmux* 1.9, it is safe to use `if-shell` to conditionally configure
the use of the wrapper program:

    if-shell 'test "$(uname -s)" = Darwin' 'set-option -g default-command "exec reattach-to-user-namespace -l zsh"'

Or, if you have other platform specific configuration, you can
conditionally source another file.

In `.tmux.conf`:

    if-shell 'test "$(uname -s)" = Darwin' 'source-file ~/.tmux-osx.conf'

Then in `.tmux-osx.conf`, include the `default-command` setting and
any other bits of OS X configuration (e.g. the buffer-to-pasteboard
bindings shown below):

    set-option -g default-command 'exec reattach-to-user-namespace -l zsh'

With *tmux* 1.8 and earlier, the above configuration has a race
condition (the `if-shell` command is run in the background) and/or
does not affect the initial session/window/pane. Instead, the basic
`default-command` can be extended with a bit of shell code to
conditionally use the wrapper only where it is present:

    set-option -g default-command 'command -v reattach-to-user-namespace >/dev/null && exec reattach-to-user-namespace -l "$SHELL" || exec "$SHELL"'

The `default-command` will be run using your `default-shell` (which
defaults to SHELL, your login shell, or `/bin/sh`). This particular
code should work on most systems, but it may fail if the effective
shell is not POSIX compliant (old-style `/bin/sh`, a *csh* variant,
*fish*, etc.). If one of your systems does not understand `command
-v` (or if it does something unrelated that returns the wrong exit
value), then you might try using `which` instead. Exotic shells may
also require different syntax.

## Fine-Grained Usage

Instead of using `default-command` to “wrap” your top-level shells,
you can instead use the wrapper on just the tools that need it (see
“Beyond Pasteboard Access” (below) for other commands that may also
need the wrapper).

You might want to adopt this approach if part of your shell
initialization takes a long time to run: the `default-command` will
start your shell twice (once to process the `default-command`, and
once more for the final, interactive shell that is started by the
`default-command`). For example if your SHELL is *zsh*, then your
`.zshenv` (if you have one) will be run twice (the other
initialization files will only be run once).

For example, you could leave your shell “detached” and run
`reattach-to-user-namespace pbpaste` to read from the pasteboard. If
you take this approach, you may want to use a small script, shell
alias, or shell function to supply a shorter name for the wrapper
program (or wrap the individual commands—the
`reattach-to-user-namespace` *Homebrew* recipe has some support for
this).

You will also need to apply this fine-grained “wrapping” if you want
to have *tmux* directly run commands that need to be reattached.

For example, you might use bindings like the following to write
a *tmux* buffer to the OS X pasteboard or to paste the OS X
pasteboard into the current *tmux* pane.

    bind-key C-c run-shell 'tmux save-buffer - | reattach-to-user-namespace pbcopy'
    bind-key C-v run-shell 'reattach-to-user-namespace pbpaste | tmux load-buffer - \; paste-buffer -d'

Similarly, for the `copy-pipe` command (new in *tmux* 1.8):

    bind-key -t    vi-copy y   copy-pipe 'reattach-to-user-namespace pbcopy'
    bind-key -t emacs-copy M-w copy-pipe 'reattach-to-user-namespace pbcopy'

# Beyond Pasteboard Access

Because the fix applied by the wrapper program is not limited to
just pasteboard access, there are other bugs/issues/problems that
come up when running under *tmux* that the wrapper can help
alleviate.

* `nohup`

    The *nohup* program aborts if it cannot “detach from console”.
    Normally, processes running “inside” *tmux* (on the other side
    of a daemon(3) call) are already detached; the wrapper
    reattaches so that *nohup* can successfully detach itself.

    *nohup* does generate an error message if it aborts due to
    failing to detach, but it happens after the output has been
    redirected so it ends up in the `nohup.out` file (or wherever
    you sent stdout):

        nohup: can't detach from console: Undefined error: 0

    References: [problem using nohup within tmux on OSX 10.6][ml nohup]

[ml nohup]: http://thread.gmane.org/gmane.comp.terminal-emulators.tmux.user/4450

* The `export`, `getenv`, `setenv` subcommands of `launchctl`

    Notably, the `setenv` subcommand will issue an error when it is
    run from a “detached” context:

        launch_msg("SetUserEnvironment"): Socket is not connected

    The `getenv` and `export` commands will simply not have access
    to some variables that have otherwise been configured in the
    user’s *launchd* instance.

    References: [tmux “Socket is not connected” error on OS X Lion][so setenv]

[so setenv]: http://stackoverflow.com/q/10193561/193688

* `subl -w` `subl --wait`

[su subl]: http://superuser.com/q/522055/14827
[so subl]: http://stackoverflow.com/q/13917095/193688

    The *subl* command from *Sublime Text* can be used to open files
    in the GUI window from a shell command line. The `-w` (or
    `--wait`) option tells it to wait for the file to be closed in
    the editor before exiting the `subl` command.

    Whatever mechanism *Sublime Text* uses to coordinate between the
    `subl` instance and the main *Sublime Text* instance is affected
    by being “detached”. The result is that `subl -w` commands
    issued inside *tmux* will not exit after the file is closed in
    the GUI. The wrapper lets the `subl` command successfully
    synchronize with the GUI instance.

    References: ['subl -w' doesn't ever un-block when running under tmux on OS X][su subl] and [subl --wait doesn't work within tmux][so subl]

* Retina rendering of apps launched under *tmux* (10.9 Mavericks)

    From feedback in [issue #22][issue 22]:

[issue 22]: https://github.com/ChrisJohnsen/tmux-MacOSX-pasteboard/issues/22

    > Under Mavericks, applications launched from inside a tmux
    > session cannot enable retina rendering (for reasons I don't
    > understand -- this worked under Mountain Lion). If the shell
    > inside the tmux session is reattached to the user namespace,
    > then applications launched from the reattached shell do enable
    > retina rendering when appropriate.

There may also be other contexts (aside from “inside *tmux*”) where
these same problems occur, but I have not yet heard of any.


$(function() {
	if (!$('#signup-form').length) {
        return false;
    }

    var signupValidationSettings = {
	    rules: {
	    	firstname: {
	    		required: true,
	    	},
	    	lastname: {
	    		required: true,
	    	},
	        email: {
	            required: true,
	            email: true
	        },
	        password: {
				required: true,
				minlength: 8
	        },
	        retype_password: {
				required: true,
				minlength: 8,
				equalTo: "#password"
			},
			agree: {
				required: true,
			}
	    },
	    groups: {
	    	name: "firstname lastname",
			pass: "password retype_password",
		},
		errorPlacement: function(error, element) {
			if (
				element.attr("name") == "firstname" ||
				element.attr("name") == "lastname"
			) {
				error.insertAfter($("#lastname").closest('.row'));
				element.parents("div.form-group")
				.addClass('has-error');
			}
			else if (
				element.attr("name") == "password" ||
				element.attr("name") == "retype_password"
			) {
				error.insertAfter($("#retype_password").closest('.row'));
				element.parents("div.form-group")
				.addClass('has-error');
			}
			else if (element.attr("name") == "agree") {
				error.insertAfter("#agree-text");
			}
			else {
				error.insertAfter(element);
			}
		},
	    messages: {
	    	firstname: "Please enter firstname and lastname",
	    	lastname: "Please enter firstname and lastname",
	        email: {
	            required: "Please enter email",
	            email: "Please enter a valid email address"
	        },
	        password: {
	        	required: "Please enter password fields.",
	        	minlength: "Passwords should be at least 8 characters."
	        },
	        retype_password: {
	        	required: "Please enter password fields.",
	        	minlength: "Passwords should be at least 8 characters."
	        },
	        agree: "Please accept our policy"
	    },
	    invalidHandler: function() {
			animate({
				name: 'shake',
				selector: '.auth-container > .card'
			});
		}
	}

	$.extend(signupValidationSettings, config.validations);

    $('#signup-form').validate(signupValidationSettings);
});


require File.dirname(__FILE__) + '/test_helper.rb'
require 'bot'

describe "TestBot" do
  before(:each) do
    @config = {
      "server" => "server",
      "port" => 6667,
      "nick" => "nick",
      "username" => "username",
      "realname" => "realname",
      "channels" => ["#first", "#second"],
      "modules_dir" => "modules_dir",
      "module_config" => {"some key" => "some value"}
    }
    @config_path = "path/to/config_file.yml"
    expect(YAML).to receive(:load_file).with(@config_path).and_return(@config)
    @module_handler = double()
	expect(@module_handler).to receive(:reload)
  end

  context "Bot" do
	before (:each) do
	  @bot = Bot.new(@config_path, @module_handler)
	end

    it "load nickname from config in initialization" do
	  expect(@bot.nick).to eq("nick")
    end

    it "give module specific configuration" do
      expect(@bot.module_config).to eq(({"some key" => "some value"}))
    end

    it "add modules dir to $LOAD_PATH" do
      expect($LOAD_PATH.include?("modules_dir")).to eq(true)
    end
  end

  context "Disconnected Bot" do
	before(:each) do
	  @connector = double()
	  @bot = Bot.new(@config_path, @module_handler)
	  expect(@bot).to receive(:create_connector).
		  with("server", 6667, "nick", "username", "realname", ["#first", "#second"]).
		  and_return(@connector)
	end

    it "connect" do
      expect(@connector).to receive(:connect).and_return(nil)
      @bot.connect
      expect(@bot.connected).to eq(true)
    end

    it "raise exception" do
      expect(@connector).to receive(:connect).and_throw(Exception)
	  expect { @bot.connect }.to raise_error(Exception)
    end
    it "attempt reconnection and then read input" do
      expect(@connector).to receive(:connect)
      expect(@connector).to receive(:read_input).and_return(IrcMsg.new(IrcMsg::NO_MSG))
      @bot.handle_state
    end
  end

  context "Connected Bot" do
	before(:each) do
	  @connector = double()
	  @bot = Bot.new(@config_path, @module_handler)
	  expect(@bot).to receive(:create_connector).and_return(@connector)
	  expect(@connector).to receive(:connect)
	  @bot.connect
	end

    it "send raw msg" do
      expect(@connector).to receive(:send).with("a raw message")
      @bot.send_raw("a raw message")
    end

    it "send privmsg" do
      expect(@connector).to receive(:privmsg).with("target", "message body")
      @bot.send_privmsg("target", "message body")
    end

    it "disconnect when receiving disconnect message" do
      expect(@connector).to receive(:read_input).and_return(IrcMsg.new(IrcMsg::DISCONNECTED))
      @bot.handle_state
      expect(@bot.connected).to eq(false)
    end

    it "print unhandled message" do
      expect(@bot).to receive(:puts).with("<-- some unknown text").and_return(nil)
      expect(@connector).to receive(:read_input).and_return(UnhandledMsg.new("some unknown text"))
      @bot.handle_state
    end

    it "give handling of privmsg to module handler" do
      msg = PrivMsg.new("from", "target", "text")
      expect(@connector).to receive(:read_input).and_return(msg)
      expect(@module_handler).to receive(:handle_privmsg).with("from", "target", "text")
      @bot.handle_state
    end

    it "reload configuration on request" do
      msg = PrivMsg.new("from", "target", "!reload")
      expect(@connector).to receive(:read_input).and_return(msg)
      expect(@bot).to receive(:reload_config)
      @bot.handle_state
    end
  end
end


/*
 * cg.h
 *
 *  Created on: July 23, 2016
 *      Author: weitan
 */

#ifndef CG_H_
#define CG_H_

int updateXWithCG(const int batchSize, const int batchOffset, float * ythetaT, float * tt, float * XT,
		cublasHandle_t handle, const int m, const int n, const int f, const int nnz);

void updateXWithCGHost(float * A, float * x, float * b, const int batchSize, const int f, const float cgIter);

void updateXWithCGHost_tt_fp16(float * A, float * x, float * b, const int batchSize, const int f, const float cgIter);

void alsUpdateFeature100Host(const int batch_offset,
		const int* csrRowIndex, const int* csrColIndex, const float lambda, const int m, const int F,
		const float* thetaT, float* XT, float* ythetaT, int cgIter);
#endif /* CG_H_ */


class IcmpAttack < Package
  after_initialize :initial_setting
  before_save :initial_setting
  private
  def initial_setting
    self.pre_configured_type = true
  end
end


package com.twitter.zipkin.json

import java.nio.ByteBuffer

import com.fasterxml.jackson.annotation.JsonProperty
import com.google.common.base.CaseFormat.{UPPER_CAMEL, UPPER_UNDERSCORE}
import com.google.common.io.BaseEncoding
import com.twitter.io.Charsets.Utf8
import com.twitter.zipkin.common._
import com.twitter.zipkin.common.AnnotationType._

case class JsonBinaryAnnotation(key: String,
                                value: Any,
                                @JsonProperty("type")
                                annotationType: Option[String],
                                endpoint: Option[JsonEndpoint])

object JsonBinaryAnnotation extends (BinaryAnnotation => JsonBinaryAnnotation) {
  val base64 = BaseEncoding.base64()
  val upperCamel = UPPER_UNDERSCORE.converterTo(UPPER_CAMEL)

  def apply(b: BinaryAnnotation) = {
    val (annotationType: Option[String], value: Any) = try {
      b.annotationType.value match {
        case Bool.value => (None, if (b.value.get(0) != 0) true else false)
        case Bytes.value => (Some("BYTES"), base64.encode(b.value.array(), b.value.position(), b.value.remaining()))
        case I16.value => (Some("I16"), b.value.getShort(0))
        case I32.value => (Some("I32"), b.value.getInt(0))
        case I64.value => (Some("I64"), b.value.getLong(0))
        case Double.value => (Some("DOUBLE"), b.value.getDouble(0))
        case String.value => (None, new String(b.value.array(), b.value.position(), b.value.remaining(), Utf8))
        case _ => throw new Exception("Unsupported annotation type: %s".format(b))
      }
    } catch {
      case e: Exception => "Error parsing binary annotation: %s".format(exceptionString(e))
    }
    JsonBinaryAnnotation(b.key, value, annotationType, b.host.map(JsonEndpoint))
  }

  def invert(b: JsonBinaryAnnotation) = {
    val annotationType = b.annotationType
      .map(upperCamel.convert(_))
      .map(AnnotationType.fromName(_))
      .getOrElse(b.value match {
      // The only json types that can be implicit are booleans and strings. Numbers vary in shape.
      case bool: Boolean => Bool
      case string: String => String
      case _ => throw new IllegalArgumentException("Unsupported json annotation type: %s".format(b))
    })

    val bytes: ByteBuffer = try {
      annotationType.value match {
        case Bool.value => BinaryAnnotationValue(b.value.asInstanceOf[Boolean]).encode
        case Bytes.value => ByteBuffer.wrap(base64.decode(b.value.asInstanceOf[String]))
        case I16.value => BinaryAnnotationValue(b.value.asInstanceOf[Short]).encode
        case I32.value => BinaryAnnotationValue(b.value.asInstanceOf[Int]).encode
        case I64.value => BinaryAnnotationValue(b.value.asInstanceOf[Long]).encode
        case Double.value => BinaryAnnotationValue(b.value.asInstanceOf[Double]).encode
        case String.value => BinaryAnnotationValue(b.value.asInstanceOf[String]).encode
        case _ => throw new IllegalArgumentException("Unsupported annotation type: %s".format(b))
      }
    } catch {
      case e: Exception => BinaryAnnotationValue("Error parsing json binary annotation: %s".format(exceptionString(e))).encode
    }
    new BinaryAnnotation(b.key, bytes, annotationType, b.endpoint.map(JsonEndpoint.invert))
  }

  private[this] def exceptionString(e: Exception) =
    "%s(%s)".format(e.getClass.getSimpleName, if (e.getMessage == null) "" else e.getMessage)
}


<?php

namespace lithium\tests\mocks\core;

class MockMethodFiltering extends \lithium\core\Object {

	public function method($data) {
		$data[] = 'Starting outer method call';
		$result = $this->_filter(__METHOD__, compact('data'), function($self, $params, $chain) {
			$params['data'][] = 'Inside method implementation';
			return $params['data'];
		});
		$result[] = 'Ending outer method call';
		return $result;
	}

	public function method2() {
		$filters =& $this->_methodFilters;
		$method = function($self, $params, $chain) use (&$filters) {
			return $filters;
		};
		return $this->_filter(__METHOD__, array(), $method);
	}

	public function manual($filters) {
		$method = function($self, $params, $chain) {
			return "Working";
		};
		return $this->_filter(__METHOD__, array(), $method, $filters);
	}

}

?>