text:
/*
 * Created on 24 Oct 2015 ( Time 23:23:57 )
 * Generated by Telosys Tools Generator ( version 2.1.1 )
 */
package com.kumasi.journal.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

//--- Common classes
import com.kumasi.journal.web.common.AbstractController;
import com.kumasi.journal.web.common.FormMode;
import com.kumasi.journal.web.common.Message;
import com.kumasi.journal.web.common.MessageType;

//--- Entities
import com.kumasi.journal.domain.Publisher;

//--- Services
import com.kumasi.journal.business.service.PublisherService;

/**
 * Spring MVC controller for 'Publisher' management.
 */
@Controller
@RequestMapping("/publisher")
public class PublisherController extends AbstractController {

	//--- Variables names ( to be used in JSP with Expression Language )
	private static final String MAIN_ENTITY_NAME = "publisher";
	private static final String MAIN_LIST_NAME   = "list";

	//--- JSP pages names ( View name in the MVC model )
	private static final String JSP_FORM   = "publisher/form";
	private static final String JSP_LIST   = "publisher/list";

	//--- SAVE ACTION ( in the HTML form )
	private static final String SAVE_ACTION_CREATE   = "/publisher/create";
	private static final String SAVE_ACTION_UPDATE   = "/publisher/update";

	//--- Main entity service
	@Resource
    private PublisherService publisherService; // Injected by Spring
	//--- Other service(s)

	//--------------------------------------------------------------------------------------
	/**
	 * Default constructor
	 */
	public PublisherController() {
		super(PublisherController.class, MAIN_ENTITY_NAME );
		log("PublisherController created.");
	}

	//--------------------------------------------------------------------------------------
	// Spring MVC model management
	//--------------------------------------------------------------------------------------

	/**
	 * Populates the Spring MVC model with the given entity and eventually other useful data
	 * @param model
	 * @param publisher
	 */
	private void populateModel(Model model, Publisher publisher, FormMode formMode) {
		//--- Main entity
		model.addAttribute(MAIN_ENTITY_NAME, publisher);
		if ( formMode == FormMode.CREATE ) {
			model.addAttribute(MODE, MODE_CREATE); // The form is in "create" mode
			model.addAttribute(SAVE_ACTION, SAVE_ACTION_CREATE);
			//--- Other data useful in this screen in "create" mode (all fields)
		}
		else if ( formMode == FormMode.UPDATE ) {
			model.addAttribute(MODE, MODE_UPDATE); // The form is in "update" mode
			model.addAttribute(SAVE_ACTION, SAVE_ACTION_UPDATE);
			//--- Other data useful in this screen in "update" mode (only non-pk fields)
		}
	}

	//--------------------------------------------------------------------------------------
	// Request mapping
	//--------------------------------------------------------------------------------------
	/**
	 * Shows a list with all the occurrences of Publisher found in the database
	 * @param model Spring MVC model
	 * @return
	 */
	@RequestMapping()
	public String list(Model model) {
		log("Action 'list'");
		List<Publisher> list = publisherService.findAll();
		model.addAttribute(MAIN_LIST_NAME, list);
		return JSP_LIST;
	}

	/**
	 * Shows a form page in order to create a new Publisher
	 * @param model Spring MVC model
	 * @return
	 */
	@RequestMapping("/form")
	public String formForCreate(Model model) {
		log("Action 'formForCreate'");
		//--- Populates the model with a new instance
		Publisher publisher = new Publisher();
		populateModel( model, publisher, FormMode.CREATE);
		return JSP_FORM;
	}

	/**
	 * Shows a form page in order to update an existing Publisher
	 * @param model Spring MVC model
	 * @param id  primary key element
	 * @return
	 */
	@RequestMapping(value = "/form/{id}")
	public String formForUpdate(Model model, @PathVariable("id") Integer id ) {
		log("Action 'formForUpdate'");
		//--- Search the entity by its primary key and stores it in the model
		Publisher publisher = publisherService.findById(id);
		populateModel( model, publisher, FormMode.UPDATE);
		return JSP_FORM;
	}

	/**
	 * 'CREATE' action processing.

	 * This action is based on the 'Post/Redirect/Get (PRG)' pattern, so it ends by 'http redirect'

	 * @param publisher  entity to be created
	 * @param bindingResult Spring MVC binding result
	 * @param model Spring MVC model
	 * @param redirectAttributes Spring MVC redirect attributes
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(value = "/create" ) // GET or POST
	public String create(@Valid Publisher publisher, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, HttpServletRequest httpServletRequest) {
		log("Action 'create'");
		try {
			if (!bindingResult.hasErrors()) {
				Publisher publisherCreated = publisherService.create(publisher);
				model.addAttribute(MAIN_ENTITY_NAME, publisherCreated);

				//---
				messageHelper.addMessage(redirectAttributes, new Message(MessageType.SUCCESS,"save.ok"));
				return redirectToForm(httpServletRequest, publisher.getId() );
			} else {
				populateModel( model, publisher, FormMode.CREATE);
				return JSP_FORM;
			}
		} catch(Exception e) {
			log("Action 'create' : Exception - " + e.getMessage() );
			messageHelper.addException(model, "publisher.error.create", e);
			populateModel( model, publisher, FormMode.CREATE);
			return JSP_FORM;
		}
	}

	/**
	 * 'UPDATE' action processing.

	 * This action is based on the 'Post/Redirect/Get (PRG)' pattern, so it ends by 'http redirect'

	 * @param publisher  entity to be updated
	 * @param bindingResult Spring MVC binding result
	 * @param model Spring MVC model
	 * @param redirectAttributes Spring MVC redirect attributes
	 * @param httpServletRequest
	 * @return
	 */
	@RequestMapping(value = "/update" ) // GET or POST
	public String update(@Valid Publisher publisher, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes, HttpServletRequest httpServletRequest) {
		log("Action 'update'");
		try {
			if (!bindingResult.hasErrors()) {
				//--- Perform database operations
				Publisher publisherSaved = publisherService.update(publisher);
				model.addAttribute(MAIN_ENTITY_NAME, publisherSaved);
				//--- Set the result message
				messageHelper.addMessage(redirectAttributes, new Message(MessageType.SUCCESS,"save.ok"));
				log("Action 'update' : update done - redirect");
				return redirectToForm(httpServletRequest, publisher.getId());
			} else {
				log("Action 'update' : binding errors");
				populateModel( model, publisher, FormMode.UPDATE);
				return JSP_FORM;
			}
		} catch(Exception e) {
			messageHelper.addException(model, "publisher.error.update", e);
			log("Action 'update' : Exception - " + e.getMessage() );
			populateModel( model, publisher, FormMode.UPDATE);
			return JSP_FORM;
		}
	}

	/**
	 * 'DELETE' action processing.

	 * This action is based on the 'Post/Redirect/Get (PRG)' pattern, so it ends by 'http redirect'

	 * @param redirectAttributes
	 * @param id  primary key element
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}") // GET or POST
	public String delete(RedirectAttributes redirectAttributes, @PathVariable("id") Integer id) {
		log("Action 'delete'" );
		try {
			publisherService.delete( id );
			//--- Set the result message
			messageHelper.addMessage(redirectAttributes, new Message(MessageType.SUCCESS,"delete.ok"));
		} catch(Exception e) {
			messageHelper.addException(redirectAttributes, "publisher.error.delete", e);
		}
		return redirectToList();
	}

}


text:
<?php

namespace Album\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class TesteController extends AbstractActionController
{
	public function indexAction()
	{
	}
}

redpajama_set_name: RedPajamaGithub


text:
from test_support.smvbasetest import SmvBaseTest
from test_support.extrapath import ExtraPath

class SmvResultTest(SmvBaseTest):
    @classmethod
    def smvAppInitArgs(cls):
        return ["--smv-props", "smv.stages=stage1:stage2"]

    def test_SmvResultModule_persistence(self):
        """Test persistence of non-DataFrame results
        """
        with ExtraPath("src/test/python/smv_result"):
            res = self.smvApp.getModuleResult("stage1.modules.RM")
        self.assertEqual(res, [100, "100", 100.0])

    def test_link_to_SmvResultModule(self):
        """Test that result of link to module with non-DataFrame result same as module's result
        """
        with ExtraPath("src/test/python/smv_result"):
            RMres = self.smvApp.getModuleResult("stage2.modules.RM")
            Mdf = self.smvApp.getModuleResult("stage2.modules.M")
        self.assertEqual(str(RMres), Mdf.collect()[0][0])


text:
feature_name: PaymentRequest Shipping Options
chrome_version: 53
feature_id: 5639348045217792
---

Background

  PaymentRequest lets
  you accept payment from different payment methods.

  This sample accepts BobBucks and provides
  a couple of shipping options regardless of shipping address.

{% capture initial_output_content %}

<button id="buyButton">Buy</button>

{% endcapture %}
{% include output_helper.html initial_output_content=initial_output_content %}

{% include js_snippet.html filename='demo.js' %}


text:
"use strict";
exports.__esModule = true;
var UserRoles;
(function (UserRoles) {
    UserRoles["basic"] = "basic";
    UserRoles["premium"] = "premium";
    UserRoles["editor"] = "premium";
    UserRoles["admin"] = "admin";
})(UserRoles || (UserRoles = {}));
;
exports["default"] = UserRoles;


text:
extern "C" {
#endif

struct _cef_view_t;

///
// A Layout manager that arranges child views vertically or horizontally in a
// side-by-side fashion with spacing around and between the child views. The
// child views are always sized according to their preferred size. If the host's
// bounds provide insufficient space, child views will be clamped. Excess space
// will not be distributed. Methods must be called on the browser process UI
// thread unless otherwise indicated.
///
typedef struct _cef_box_layout_t {
  ///
  // Base structure.
  ///
  cef_layout_t base;

  ///
  // Set the flex weight for the given |view|. Using the preferred size as the
  // basis, free space along the main axis is distributed to views in the ratio
  // of their flex weights. Similarly, if the views will overflow the parent,
  // space is subtracted in these ratios. A flex of 0 means this view is not
  // resized. Flex values must not be negative.
  ///
  void (CEF_CALLBACK *set_flex_for_view)(struct _cef_box_layout_t* self,
      struct _cef_view_t* view, int flex);

  ///
  // Clears the flex for the given |view|, causing it to use the default flex
  // specified via cef_box_layout_tSettings.default_flex.
  ///
  void (CEF_CALLBACK *clear_flex_for_view)(struct _cef_box_layout_t* self,
      struct _cef_view_t* view);
} cef_box_layout_t;

#ifdef __cplusplus
}
#endif

#endif  // CEF_INCLUDE_CAPI_VIEWS_CEF_BOX_LAYOUT_CAPI_H_


text:
[![Build Status](https://travis-ci.org/nicknovitski/tabletop.svg?branch=master)](https://travis-ci.org/nicknovitski/tabletop)
[![Code Climate](https://codeclimate.com/github/nicknovitski/tabletop.png)](https://codeclimate.com/github/nicknovitski/tabletop)

Tabletop aims to provide a simple way of describing, automating and tracking the tools and tasks involved in "analog" games, determining results from the motions and properties of various dice and chips.

## Installation

    gem install tabletop

    require 'tabletop'

## Usage

For detailed information, I recommend the [full documentation](http://rubydoc.info/gems/tabletop/), but I want this file to give you a good primer, so let's get started.

### Dice

Dice are pretty straightforward.  They've got a number of sides, set on instantiation (defaulting to 6), and a current value between that number and 1 inclusive, which can be set on instantiation, or set directly. Finally, they can be rolled, which gives them a new random value.

    d6 = Die.new
    d6.sides     #=> 6
    d6.value     #=> 4
    d6.roll
    d6.value     #=> 2

    d8 = Die.new(8, 4)
    d8.sides     #=> 8
    d8.to_s      #=> "[4]/d8"

One fun special kind of die is a "Fudge Die".  They are a special kind of three-sided die that have three possible values: -1, 0, or 1.  Those are usually expressed as '-', ' ' and '+', though.

    f = FudgeDie.new
    f.sides      #=> 3
    f.value      #=> 0
    f.to_s       #=> "[ ]"

You may not believe this, but coins are also a special case of die.  Coins have two sides, and have a value of either 1 or 0, aka heads or tails, aka "+" or " ".  They can be rolled if you really want, but you'd normally call that "flipping," right?

    c = Coin.new
    c.sides      #=> 2
    c.value      #=> 1
    c.to_s       #=> "(+)"
    c.flip.to_s  #=> "( )"

### Pools

Pools are arrays of Dice objects with some extra helpful methods.

Tabletop ships with a monkeypatch to fixnum that enables an easy way to build pools with d-notation.  It's not loaded automatically, but you can easily enable it.

    require 'tabletop/d_notation'
    3.d6           #=> [[3]/d6, [3]/d6, [4]/d6]
    2.d10 + 1.d8   #=> [[2]/d10, [6]/d10, [8]/d8]

You can also create pools by passing Pool.new a literal array of dice, or (slightly more interesting) a string in die notation.

Pool's instance methods are common operations you might do on a pool of dice: summing, counting sets, dropping the lowest or highest valued dice, dropping all _but_ the lowest or highest valued dice, even dropping any dice  a specified list of values.

    d&d = 3.d6.sum    #=> 13
    ore = 10.d10.sets #=> ["3x2", "2x8", "1x7", "1x6", "1x4", "1x3", "1x1"]
    cortex = (1.d8 + 2.d6).drop([1]).highest(2).sum  #=> 9
    tsoy = (4.dF).drop_lowest.sum  #=> 2

You can also #roll an entire pool, or you can interact with individual dice in the array using array indices (`[]`).

When pools are compared to each other or to numbers with <=>, it's assumed you're actually interested in their sum.  The same thing happens if you try to add a number to them.

    4.d4 + 4         #=> 17
    1.d20 > 2.d10    #=> false

### Rolls

Rolls are very much under construction and their API is in flux, but they allow you to automate randomly determining results in a variety of ways.

Rolls have a lot of options, described in detail in the documentation.  But let's take a simple example from one of my favorite games, Apocalypse World.

>When you open your brain to the world's psychic maelstrom, roll+weird. On a hit, the MC will tell you something new and interesting about the current situation, and might ask you a question or two; answer them. On a 10+, the MC will give you good detail. On a 7–9, the MC will give you an impression.

(In the parlance of the game, a "hit" is getting a 7 or higher.  "Roll+weird" means to roll 2d6 and add the character's "weird" stat, which is an integer from -1 to 3.)

Here's how I'd write that out in Tabletop:

    weird = [-1, 0, 1, 2, 3].sample #=> get a random stat

    open_brain = Roll.new(2.d6) {
      add weird
      at_least 7, "the MC will tell you something new and interesting about the current situation..."
      equals (7..9), "...but it's just an impression"
      at_least 10, "...and it's a good detail"
    }

Simple, right?  `add` sets a value to be permanently added for the purposes of determining results.  `at_least` and `equals` take an integer (or a range, in the case of `equals`) as their first parameter, and then one or more values to return if the pool's result meets the stated condition.

Once they've been instantiated, Rolls have three important methods.

#### #roll

This method which re-rolls all the dice in the pool, and returns the Roll object.  It can take an options hash as a parameter.  Notably, one of the options is `:modifier`, which sets a temporary modifier for that roll only; it's cleared the next time `roll` is called.

    bad_luck = -1
    open_brain.roll(:modifier => bad_luck)

#### #result

This method, by default, returns the sum of the values of the Roll's dice, plus any static modifiers from `add` or per-roll modifiers from `roll(:modifier)`.

But!  When instantiating a roll, you can call `set_result` with an appropriate symbol to make `result` mean something else.

For example, in Exalted, you principally care about how many dice in your pool came up 7 or higher, counting 10s twice:

    exalted = Roll.new(8.d10) do
      set_result :count, :at_least=>7, :doubles=>10
    end

    exalted.result   #=> 2
    exalted.sum      #=> 30

#### #effects

This method returns either an array containing the results passed to any `at_least` and `equals` calls whose conditions were met, or nil if no such conditions were met.

So, possible results for our cool AW roll:

    open_brain.roll.effects #=> nil
    open_brain.roll.effects #=> ["the MC will tell you something new and interesting about the current situation", "...but it's just an impression"]
    open_brain.roll
    puts open_brain.result  #=> 10
    puts open_brain.effects #=> ["the MC will tell you something new and interesting about the current situation", "...and it's a good detail"]

### Decks

Decks are essentially weighted hashes with a random #draw method.  You can put whatever hashable object you like in a
deck (there's no Card class yet) as a key to a value that indicates the number of copies of that object in the deck.

#### #draw
This method returns another deck, and reduces the number of cards in the original deck appropriately.

      d = Deck.new
      d["card A"] = 20
      d["card B"] = 19
      d.deck_size      #=> 39
      hand = d.draw(3) #=> {"card A"=>1, "card B" =>2}
      d                #=> {"card A" => 19, "card B"=>17}
      d << hand        #=> {"card A" => 20, "card B"=>19}

### Coming Soon

That's already enough functionality to do many different kinds of rolls, but there's a lot more in store.

One bonus thing I'll briefly note is that Rolls can be nested, and `effects` returns them as such.

    rps = Roll.new(1.d3) {
      equals 1, "rock"
      equals 2, "paper"
      equals 3, "scissors"
    }
    jkp = Roll.new(1.d3) {
      equals 1, "guu"
      equals 2, "choki"
      equals 3, "paa"
    }
    fist_game = Roll.new(1.d2) {
      equals 1, "Rock Paper Scissors", rps
      equals 2, "JanKenPon", jkp
    }
    fist_game.roll.effects   #=> ["JanKenPon", ["guu"]]

This can lead to some surprisingly sophisticated constructions.  Remember that "tables" are really just a special case of a roll!

## How to contribute

*First and most importantly*, if you're reading this and you make games, please tell me about them!  Second, any complaints or suggestions are always welcome, _regardless of coding knowledge_.  Feel free to communicate your opinions by [creating an issue on github](https://github.com/njay/tabletop/issues), or just dropping me a line at <nick.novitski@gmail.com>.

If you have clear ideas about what more the project should do, and you think you can do something about it, then make it so!  Don't even bother asking me about it, you know the drill:

* Fork the project.
* Create a topic branch.
* Make tests that describe your feature addition or bug fix.
* Write code that passes those tests.
* Send me a pull request.

## Copyright

Copyright (c) 2011 Nick Novitski. See LICENSE for details.


text:
BR.RoutingOptions = BR.Control.extend({
    options: {
        heading: 'Options',
        divId: 'route_options'
    },

    onAdd: function (map) {
        var select = L.DomUtil.get('profile'),
            i,
            option;

        select.onchange = this._getChangeHandler();
        L.DomUtil.get('alternative').onchange = this._getChangeHandler();

        // build option list from config
        var profiles = BR.conf.profiles;
        for (i = 0; i < profiles.length; i++) {
            option = document.createElement("option");
            option.value = profiles[i];
            option.text = profiles[i];
            select.add(option, null);
        }
        // <custom> option disabled, select next
        select.options[1].selected = true;

        return BR.Control.prototype.onAdd.call(this, map);
    },

    getOptions: function() {
        return {
            profile: L.DomUtil.get('profile').value,
            alternative: L.DomUtil.get('alternative').value
        };
    },

    setOptions: function(options) {
        var select,
            profile = options.profile;

        if (profile) {
            select = L.DomUtil.get('profile');
            select.value = profile;

            // profile got not selected = not in option values -> custom profile passed with permalink
            if (select.value != profile) {
                this.setCustomProfile(profile, true);
            }

        }
        if (options.alternative) {
            L.DomUtil.get('alternative').value = options.alternative;
        }
    },

    setCustomProfile: function(profile, noUpdate) {
        var select,
            option;

        select = L.DomUtil.get('profile');
        option = select.options[0]
        option.value = profile;
        option.disabled = !profile;
        option.selected = !!profile;

        if (!noUpdate) {
            this.fire('update', {options: this.getOptions()});
        }
    },

    getCustomProfile: function() {
        var select = L.DomUtil.get('profile'),
            option = select.options[0],
            profile = null;

        if (!option.disabled) {
            profile = option.value;
        }
        return profile;
    },

    _getChangeHandler: function() {
        return L.bind(function(evt) {
            this.fire('update', {options: this.getOptions()});
        }, this);
    }
});

BR.RoutingOptions.include(L.Mixin.Events);


text:
#pragma once

namespace Sharp {
	class Application {
	private:
		Application(); // 매개 변수 없이 생성 금지
		static Application *Instance;
		HINSTANCE hInstance;
		HWND hWnd;
		HDC hDC;
		HGLRC hRC;
		WNDCLASSEX WndClassEx;
		LPCTSTR Title;
		int ScreenWidth, ScreenHeight;

		LRESULT CALLBACK RealWndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
		void DoDisplay();

	public:
		Application(HINSTANCE hInstance, int screenWidth, int screenHeight, LPCTSTR title);
		~Application();
		static LRESULT CALLBACK WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
		WPARAM Start();
	};
}


text:
package de.fhg.fokus.ims.core.sdp;

import java.net.Inet6Address;
import java.net.InetAddress;

import de.fhg.fokus.ims.core.utils.Parser;

/**
 * SDP connection field.
 *

 *

 *
 *

 *    connection-field = "c=" nettype SP addrtype SP connection-address CRLF
 *                       ;a connection field must be present
 *                       ;in every media description or at the
 *                       ;session-level
 *

 *
 *

 */
public class ConnectionField extends SdpField
{
	public ConnectionField(String connectionField)
	{
		super('c', connectionField);
	}

	public ConnectionField(InetAddress address, int ttl, int num)
	{
		super('c', null);
		String address_type = address instanceof Inet6Address ? "IP6" : "IP4";

		value = "IN " + address_type + " " + address.getHostAddress();
		if (ttl > 0)
			value += "/" + ttl;
		if (num > 0)
			value += "/" + num;
	}

	public ConnectionField(InetAddress address)
	{
		super('c',null);
		String address_type = null;
		if(address instanceof Inet6Address)  {
			address_type = "IP6";
			value =  "IN "+address_type+" ["+address.getHostAddress()+"]";
		} else {
			address_type = "IP4";
			value = "IN "+address_type+" "+address.getHostAddress();
		}
	}

	public ConnectionField(SdpField sf)
	{
		super(sf);
	}

	public String getAddressType()
	{
		String type = (new Parser(value)).skipString().getString();
		return type;
	}

	public String getAddress()
	{
		String address = (new Parser(value)).skipString().skipString().getString();
		int i = address.indexOf('/');
		if (i < 0)
			return address;
		else
			return address.substring(0, i);
	}

	public int getTTL()
	{
		String address = (new Parser(value)).skipString().skipString().getString();
		int i = address.indexOf('/');
		if (i < 0)
			return 0;
		int j = address.indexOf('/', i);
		if (j < 0)
			return Integer.parseInt(address.substring(i));
		else
			return Integer.parseInt(address.substring(i, j));
	}

	public int getNum()
	{
		String address = (new Parser(value)).skipString().skipString().getString();
		int i = address.indexOf('/');
		if (i < 0)
			return 0;
		int j = address.indexOf('/', i);
		if (j < 0)
			return 0;
		return Integer.parseInt(address.substring(j));
	}

	public Object clone()
	{
		return new ConnectionField(this);
	}
}


text:
const env = process.env.NODE_ENV

const config = require('./.webpack/config')
const entrys = require('./.webpack/entrys')
const output = require('./.webpack/output')
const modules = require('./.webpack/modules')
const plugins = require('./.webpack/plugins')
const server = require('./.webpack/server')

module.exports = () => ({
  target: config.target,
  cache: config.cache,
  devtool: config.devtool,
  context: config.context,
  resolve: config.resolve,
  entry: entrys,
  output: output,
  module: modules,
  plugins: plugins,
  performance: env === 'development' ? { hints: false } : {},
  devServer: env === 'development' ? server : {}
})


text:
namespace task_manager {

// Defines a concrete UserData type for WebContents owned by DevToolsWindow.
class DevToolsTag : public WebContentsTag {
 public:
  DevToolsTag(const DevToolsTag&) = delete;
  DevToolsTag& operator=(const DevToolsTag&) = delete;
  ~DevToolsTag() override;

  // task_manager::WebContentsTag:
  std::unique_ptr<RendererTask> CreateTask(
      WebContentsTaskProvider*) const override;

 private:
  friend class WebContentsTags;

  explicit DevToolsTag(content::WebContents* web_contents);
};

}  // namespace task_manager

#endif  // CHROME_BROWSER_TASK_MANAGER_PROVIDERS_WEB_CONTENTS_DEVTOOLS_TAG_H_


text:
using System;

namespace Deinterleave
{
    internal class Program
    {
        private static int Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.Error.WriteLine("Syntax: Deinterleave input.xps output.xps\n");
                return 1;
            }

            OPCCopier.CopyPackage(args[0], args[1]);

            return 0;
        }
    }
}


text:
package cn.felord.wepay.ali.sdk.api.domain;

import java.util.List;

import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiListField;

/**
 * 凤蝶创建H5应用的初始化数据
 *
 * @author auto create
 * @version $Id: $Id
 */
public class FengdieActivityCreateData extends AlipayObject {

	private static final long serialVersionUID = 8747161544896375117L;

	/**
	 * H5应用的名称,用户自定义,最终用于生成URL。生成URL的规则"域名/p/f/${name}/页面名称.html"
	 */
	@ApiField("name")
	private String name;

	/**
	 * 用户自定义,到了该时间后,用户将访问不到该应用
	 */
	@ApiField("offline_time")
	private String offlineTime;

	/**
	 * H5应用的页面在编辑器中默认展示的数据
	 */
	@ApiListField("page")
	@ApiField("fengdie_activity_create_page_data")
	private List<FengdieActivityCreatePageData> page;

	/**
	 * H5应用标题,用户自定义
	 */
	@ApiField("title")
	private String title;

	/**
	 *
Getter for the field name.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getName() {
		return this.name;
	}
	/**
	 *
Setter for the field name.

	 *
	 * @param name a {@link java.lang.String} object.
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 *
Getter for the field offlineTime.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getOfflineTime() {
		return this.offlineTime;
	}
	/**
	 *
Setter for the field offlineTime.

	 *
	 * @param offlineTime a {@link java.lang.String} object.
	 */
	public void setOfflineTime(String offlineTime) {
		this.offlineTime = offlineTime;
	}

	/**
	 *
Getter for the field page.

	 *
	 * @return a {@link java.util.List} object.
	 */
	public List<FengdieActivityCreatePageData> getPage() {
		return this.page;
	}
	/**
	 *
Setter for the field page.

	 *
	 * @param page a {@link java.util.List} object.
	 */
	public void setPage(List<FengdieActivityCreatePageData> page) {
		this.page = page;
	}

	/**
	 *
Getter for the field title.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getTitle() {
		return this.title;
	}
	/**
	 *
Setter for the field title.

	 *
	 * @param title a {@link java.lang.String} object.
	 */
	public void setTitle(String title) {
		this.title = title;
	}

}


text:
<!DOCTYPE html>

		<title>three.js webgl - read float pixels</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

three.js read float pixels webgl example


text:
""" Collection of tf.train.SessionRunHooks
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import abc
import os

import numpy as np
import six
import yaml

import tensorflow as tf
from tensorflow.python.training.basic_session_run_hooks import SecondOrStepTimer  # pylint: disable=E0611
from tensorflow.python.training import session_manager # pylint: disable=E0611
from tensorflow.python.client import timeline  # pylint: disable=E0611
from tensorflow import gfile

from seq2seq.configurable import Configurable, abstractstaticmethod
from seq2seq import graph_utils, global_vars

FLAGS = tf.flags.FLAGS

@six.add_metaclass(abc.ABCMeta)
class TrainingHook(tf.train.SessionRunHook, Configurable):
  """Abstract base class for training hooks.
  """

  def __init__(self, params, model_dir, run_config):
    tf.train.SessionRunHook.__init__(self)
    Configurable.__init__(self, params, tf.contrib.learn.ModeKeys.TRAIN)
    self._model_dir = model_dir
    self._run_config = run_config

  @property
  def model_dir(self):
    """Returns the directory model checkpoints are written to.
    """
    return os.path.abspath(self._model_dir)

  @property
  def is_chief(self):
    """Returns true if and only if the current process is the chief.
    This is used for distributed training.
    """
    return self._run_config.is_chief

  @abstractstaticmethod
  def default_params():
    raise NotImplementedError()

class MetadataCaptureHook(TrainingHook):
  """A hook to capture metadata for a single step.
  Useful for performance debugging. It performs a full trace and saves
  run_metadata and Chrome timeline information to a file.

  Args:
    step: The step number to trace. The hook is only enable for this step.
  """

  def __init__(self, params, model_dir, run_config):
    super(MetadataCaptureHook, self).__init__(params, model_dir, run_config)
    self._active = False
    self._done = False
    self._global_step = None
    self._output_dir = os.path.abspath(self.model_dir)

  @staticmethod
  def default_params():
    return {"step": 10}

  def begin(self):
    self._global_step = tf.train.get_global_step()

  def before_run(self, _run_context):
    if not self.is_chief or self._done:
      return
    if not self._active:
      return tf.train.SessionRunArgs(self._global_step)
    else:
      tf.logging.info("Performing full trace on next step.")
      run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) #pylint: disable=E1101
      return tf.train.SessionRunArgs(self._global_step, options=run_options)

  def after_run(self, _run_context, run_values):
    if not self.is_chief or self._done:
      return

    step_done = run_values.results
    if self._active:
      tf.logging.info("Captured full trace at step %s", step_done)
      # Create output directory
      gfile.MakeDirs(self._output_dir)

      # Save run metadata
      trace_path = os.path.join(self._output_dir, "run_meta")
      with gfile.GFile(trace_path, "wb") as trace_file:
        trace_file.write(run_values.run_metadata.SerializeToString())
        tf.logging.info("Saved run_metadata to %s", trace_path)

      # Save timeline
      timeline_path = os.path.join(self._output_dir, "timeline.json")
      with gfile.GFile(timeline_path, "w") as timeline_file:
        tl_info = timeline.Timeline(run_values.run_metadata.step_stats)
        tl_chrome = tl_info.generate_chrome_trace_format(show_memory=True)
        timeline_file.write(tl_chrome)
        tf.logging.info("Saved timeline to %s", timeline_path)

      # Save tfprof op log
      tf.contrib.tfprof.tfprof_logger.write_op_log(
          graph=tf.get_default_graph(),
          log_dir=self._output_dir,
          run_meta=run_values.run_metadata)
      tf.logging.info("Saved op log to %s", self._output_dir)
      self._active = False
      self._done = True

    self._active = (step_done >= self.params["step"])

class TrainSampleHook(TrainingHook):
  """Occasionally samples predictions from the training run and prints them.

  Params:
    every_n_secs: Sample predictions every N seconds.
      If set, `every_n_steps` must be None.
    every_n_steps: Sample predictions every N steps.
      If set, `every_n_secs` must be None.
    sample_dir: Optional, a directory to write samples to.
    delimiter: Join tokens on this delimiter. Defaults to space.
  """

  #pylint: disable=missing-docstring

  def __init__(self, params, model_dir, run_config):
    super(TrainSampleHook, self).__init__(params, model_dir, run_config)
    self._sample_dir = os.path.join(self.model_dir, "samples")
    self._timer = SecondOrStepTimer(
        every_secs=self.params["every_n_secs"],
        every_steps=self.params["every_n_steps"])
    self._pred_dict = {}
    self._should_trigger = False
    self._iter_count = 0
    self._global_step = None
    self._source_delimiter = self.params["source_delimiter"]
    self._target_delimiter = self.params["target_delimiter"]

  @staticmethod
  def default_params():
    return {
        "every_n_secs": None,
        "every_n_steps": 1000,
        "source_delimiter": " ",
        "target_delimiter": " "
    }

  def begin(self):
    self._iter_count = 0
    self._global_step = tf.train.get_global_step()
    self._pred_dict = graph_utils.get_dict_from_collection("predictions")
    # Create the sample directory
    if self._sample_dir is not None:
      gfile.MakeDirs(self._sample_dir)

  def before_run(self, _run_context):
    self._should_trigger = self._timer.should_trigger_for_step(self._iter_count)
    if self._should_trigger:
      fetches = {
          "predicted_tokens": self._pred_dict["predicted_tokens"],
          "target_words": self._pred_dict["labels.target_tokens"],
          "target_len": self._pred_dict["labels.target_len"]
      }
      return tf.train.SessionRunArgs([fetches, self._global_step])
    return tf.train.SessionRunArgs([{}, self._global_step])

  def after_run(self, _run_context, run_values):
    result_dict, step = run_values.results
    self._iter_count = step

    if not self._should_trigger:
      return None

    # Convert dict of lists to list of dicts
    result_dicts = [
        dict(zip(result_dict, t)) for t in zip(*result_dict.values())
    ]

    # Print results
    result_str = ""
    result_str += "Prediction followed by Target @ Step {}\n".format(step)
    result_str += ("=" * 100) + "\n"
    for result in result_dicts:
      target_len = result["target_len"]
      predicted_slice = result["predicted_tokens"][:target_len - 1]
      target_slice = result["target_words"][1:target_len]
      result_str += self._target_delimiter.encode("utf-8").join(
          predicted_slice).decode("utf-8") + "\n"
      result_str += self._target_delimiter.encode("utf-8").join(
          target_slice).decode("utf-8") + "\n\n"
    result_str += ("=" * 100) + "\n\n"
    tf.logging.info(result_str)
    if self._sample_dir:
      filepath = os.path.join(self._sample_dir,
                              "samples_{:06d}.txt".format(step))
      with gfile.GFile(filepath, "w") as file:
        file.write(result_str)
    self._timer.update_last_triggered_step(self._iter_count - 1)

class PrintModelAnalysisHook(TrainingHook):
  """Writes the parameters of the model to a file and stdout.
  """

  #pylint: disable=missing-docstring
  def __init__(self, params, model_dir, run_config):
    super(PrintModelAnalysisHook, self).__init__(params, model_dir, run_config)
    self._filename = os.path.join(self.model_dir, "model_analysis.txt")

  @staticmethod
  def default_params():
    return {}

  def begin(self):
    # Dump to file on the chief worker
    if self.is_chief:
      opts = tf.contrib.tfprof.model_analyzer.TRAINABLE_VARS_PARAMS_STAT_OPTIONS
      opts['dump_to_file'] = os.path.abspath(self._filename)
      tf.contrib.tfprof.model_analyzer.print_model_analysis(
          tf.get_default_graph(), tfprof_options=opts)

    # Print the model analysis
    with gfile.GFile(self._filename) as file:
      tf.logging.info(file.read())

class VariableRestoreHook(TrainingHook):
  """A hooks that restored variables from a given checkpoints.

  Params:
    prefix: Variables matching this prefix are restored.
    checkpoint_path: Path to the checkpoint to restore variables from.
  """

  def __init__(self, params, model_dir, run_config):
    super(VariableRestoreHook, self).__init__(params, model_dir, run_config)
    self._saver = None

  @staticmethod
  def default_params():
    return {"prefix": "", "checkpoint_path": ""}

  def begin(self):
    variables = tf.contrib.framework.get_variables(scope=self.params["prefix"])

    def varname_in_checkpoint(name):
      """Removes the prefix from the variable name.
      """
      prefix_parts = self.params["prefix"].split("/")
      checkpoint_prefix = "/".join(prefix_parts[:-1])
      return name.replace(checkpoint_prefix + "/", "")

    target_names = [varname_in_checkpoint(_.op.name) for _ in variables]
    restore_map = {k: v for k, v in zip(target_names, variables)}

    tf.logging.info("Restoring variables: \n%s",
                    yaml.dump({k: v.op.name
                               for k, v in restore_map.items()}))

    self._saver = tf.train.Saver(restore_map)

  def after_create_session(self, session, coord):
    self._saver.restore(session, self.params["checkpoint_path"])
    tf.logging.info("Successfully restored all variables")

class DelayStartHook(TrainingHook, tf.train.GlobalStepWaiterHook):
  """Delays the start of the current worker process until global step
  K * task_id is reached. K is a parameter.
  """
  def __init__(self, params, model_dir, run_config):
    TrainingHook.__init__(self, params, model_dir, run_config)
    self._task_id = self._run_config.task_id
    self._delay_k = self.params["delay_k"]
    self._wait_until_step = int(self._delay_k * self._task_id)
    tf.train.GlobalStepWaiterHook.__init__(self, self._wait_until_step)

  @staticmethod
  def default_params():
    return {"delay_k": 500}

class SyncReplicasOptimizerHook(TrainingHook):
  """A SessionRunHook handles ops related to SyncReplicasOptimizer."""

  def __init__(self, params, model_dir, run_config):
    super(SyncReplicasOptimizerHook, self).__init__(
        params, model_dir, run_config)
    self._sync_optimizer = None
    self._num_tokens = -1

    self._local_init_op = None
    self._ready_for_local_init_op = None
    self._q_runner = None
    self._init_tokens_op = None

  @staticmethod
  def default_params():
    return {}

  def begin(self):
    if global_vars.SYNC_REPLICAS_OPTIMIZER is not None:
      self._sync_optimizer = global_vars.SYNC_REPLICAS_OPTIMIZER
    else:
      return

    if self._sync_optimizer._gradients_applied is False:  # pylint: disable=protected-access
      raise ValueError(
          "SyncReplicasOptimizer.apply_gradient should be called before using "
          "the hook.")
    if self.is_chief:
      self._local_init_op = self._sync_optimizer.chief_init_op
      self._ready_for_local_init_op = (
          self._sync_optimizer.ready_for_local_init_op)
      self._q_runner = self._sync_optimizer.get_chief_queue_runner()
      self._init_tokens_op = self._sync_optimizer.get_init_tokens_op(
          self._num_tokens)
    else:
      self._local_init_op = self._sync_optimizer.local_step_init_op
      self._ready_for_local_init_op = (
          self._sync_optimizer.ready_for_local_init_op)
      self._q_runner = None
      self._init_tokens_op = None

  def after_create_session(self, session, coord):
    """Runs SyncReplicasOptimizer initialization ops."""

    if not self._sync_optimizer:
      return

    tf.logging.info("Found SyncReplicasOptimizer. Initializing.")

    local_init_success, msg = session_manager._ready(  # pylint: disable=protected-access
        self._ready_for_local_init_op, session,
        "Model is not ready for SyncReplicasOptimizer local init.")
    if not local_init_success:
      raise RuntimeError(
          "Init operations did not make model ready for SyncReplicasOptimizer "
          "local_init. Init op: %s, error: %s" %
          (self._local_init_op.name, msg))
    session.run(self._local_init_op)
    if self._init_tokens_op is not None:
      session.run(self._init_tokens_op)
    if self._q_runner is not None:
      self._q_runner.create_threads(
          session, coord=coord, daemon=True, start=True)


text:
<?php

namespace Test\Files;

use OC\Files\Filesystem;
use OC\Files\Mount\MountPoint;
use OC\Files\Storage\Temporary;
use OC\Files\View;
use OC\User\NoUserException;
use OCP\Files\Config\IMountProvider;
use OCP\Files\Storage\IStorageFactory;
use OCP\IUser;
use Test\TestCase;
use Test\Traits\UserTrait;

class DummyMountProvider implements IMountProvider {
	private $mounts = [];

	/**
	 * @param array $mounts
	 */
	public function __construct(array $mounts) {
		$this->mounts = $mounts;
	}

	/**
	 * Get the pre-registered mount points
	 *
	 * @param IUser $user
	 * @param IStorageFactory $loader
	 * @return \OCP\Files\Mount\IMountPoint[]
	 */
	public function getMountsForUser(IUser $user, IStorageFactory $loader) {
		return isset($this->mounts[$user->getUID()]) ? $this->mounts[$user->getUID()] : [];
	}
}

/**
 * Class FilesystemTest
 *
 * @group DB
 *
 * @package Test\Files
 */
class FilesystemTest extends TestCase {
	use UserTrait;

	const TEST_FILESYSTEM_USER1 = "test-filesystem-user1";
	const TEST_FILESYSTEM_USER2 = "test-filesystem-user1";

	/**
	 * @var array tmpDirs
	 */
	private $tmpDirs = [];

	/**
	 * @return array
	 */
	private function getStorageData() {
		$dir = \OC::$server->getTempManager()->getTemporaryFolder();
		$this->tmpDirs[] = $dir;
		return ['datadir' => $dir];
	}

	protected function setUp(): void {
		parent::setUp();
		$this->createUser(self::TEST_FILESYSTEM_USER1, self::TEST_FILESYSTEM_USER1);
		$this->createUser(self::TEST_FILESYSTEM_USER2, self::TEST_FILESYSTEM_USER2);
		$this->loginAsUser();
	}

	protected function tearDown(): void {
		foreach ($this->tmpDirs as $dir) {
			\OC_Helper::rmdirr($dir);
		}

		$this->logout();
		$this->invokePrivate('\OC\Files\Filesystem', 'normalizedPathCache', [null]);
		\OC_User::clearBackends();
		parent::tearDown();
	}

	public function testMount() {
		Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/');
		$this->assertEquals('/', Filesystem::getMountPoint('/'));
		$this->assertEquals('/', Filesystem::getMountPoint('/some/folder'));
		list(, $internalPath) = Filesystem::resolvePath('/');
		$this->assertEquals('', $internalPath);
		list(, $internalPath) = Filesystem::resolvePath('/some/folder');
		$this->assertEquals('some/folder', $internalPath);

		Filesystem::mount('\OC\Files\Storage\Local', self::getStorageData(), '/some');
		$this->assertEquals('/', Filesystem::getMountPoint('/'));
		$this->assertEquals('/some/', Filesystem::getMountPoint('/some/folder'));
		$this->assertEquals('/some/', Filesystem::getMountPoint('/some/'));
		$this->assertEquals('/some/', Filesystem::getMountPoint('/some'));
		list(, $internalPath) = Filesystem::resolvePath('/some/folder');
		$this->assertEquals('folder', $internalPath);
	}

	public function normalizePathData() {
		return [
			['/', ''],
			['/', '/'],
			['/', '//'],
			['/', '/', false],
			['/', '//', false],

			['/path', '/path/'],
			['/path/', '/path/', false],
			['/path', 'path'],

			['/foo/bar', '/foo//bar/'],
			['/foo/bar/', '/foo//bar/', false],
			['/foo/bar', '/foo////bar'],
			['/foo/bar', '/foo/////bar'],
			['/foo/bar', '/foo/bar/.'],
			['/foo/bar', '/foo/bar/./'],
			['/foo/bar/', '/foo/bar/./', false],
			['/foo/bar', '/foo/bar/./.'],
			['/foo/bar', '/foo/bar/././'],
			['/foo/bar/', '/foo/bar/././', false],
			['/foo/bar', '/foo/./bar/'],
			['/foo/bar/', '/foo/./bar/', false],
			['/foo/.bar', '/foo/.bar/'],
			['/foo/.bar/', '/foo/.bar/', false],
			['/foo/.bar/tee', '/foo/.bar/tee'],

			// Windows paths
			['/', ''],
			['/', '\\'],
			['/', '\\', false],
			['/', '\\\\'],
			['/', '\\\\', false],

			['/path', '\\path'],
			['/path', '\\path', false],
			['/path', '\\path\\'],
			['/path/', '\\path\\', false],

			['/foo/bar', '\\foo\\\\bar\\'],
			['/foo/bar/', '\\foo\\\\bar\\', false],
			['/foo/bar', '\\foo\\\\\\\\bar'],
			['/foo/bar', '\\foo\\\\\\\\\\bar'],
			['/foo/bar', '\\foo\\bar\\.'],
			['/foo/bar', '\\foo\\bar\\.\\'],
			['/foo/bar/', '\\foo\\bar\\.\\', false],
			['/foo/bar', '\\foo\\bar\\.\\.'],
			['/foo/bar', '\\foo\\bar\\.\\.\\'],
			['/foo/bar/', '\\foo\\bar\\.\\.\\', false],
			['/foo/bar', '\\foo\\.\\bar\\'],
			['/foo/bar/', '\\foo\\.\\bar\\', false],
			['/foo/.bar', '\\foo\\.bar\\'],
			['/foo/.bar/', '\\foo\\.bar\\', false],
			['/foo/.bar/tee', '\\foo\\.bar\\tee'],

			// Absolute windows paths NOT marked as absolute
			['/C:', 'C:\\'],
			['/C:/', 'C:\\', false],
			['/C:/tests', 'C:\\tests'],
			['/C:/tests', 'C:\\tests', false],
			['/C:/tests', 'C:\\tests\\'],
			['/C:/tests/', 'C:\\tests\\', false],

			// normalize does not resolve '..' (by design)
			['/foo/..', '/foo/../'],
			['/foo/..', '\\foo\\..\\'],
		];
	}

	/**
	 * @dataProvider normalizePathData
	 */
	public function testNormalizePath($expected, $path, $stripTrailingSlash = true) {
		$this->assertEquals($expected, Filesystem::normalizePath($path, $stripTrailingSlash));
	}

	public function normalizePathKeepUnicodeData() {
		$nfdName = 'ümlaut';
		$nfcName = 'ümlaut';
		return [
			['/' . $nfcName, $nfcName, true],
			['/' . $nfcName, $nfcName, false],
			['/' . $nfdName, $nfdName, true],
			['/' . $nfcName, $nfdName, false],
		];
	}

	/**
	 * @dataProvider normalizePathKeepUnicodeData
	 */
	public function testNormalizePathKeepUnicode($expected, $path, $keepUnicode = false) {
		$this->assertEquals($expected, Filesystem::normalizePath($path, true, false, $keepUnicode));
	}

	public function testNormalizePathKeepUnicodeCache() {
		$nfdName = 'ümlaut';
		$nfcName = 'ümlaut';
		// call in succession due to cache
		$this->assertEquals('/' . $nfcName, Filesystem::normalizePath($nfdName, true, false, false));
		$this->assertEquals('/' . $nfdName, Filesystem::normalizePath($nfdName, true, false, true));
	}

	public function isValidPathData() {
		return [
			['/', true],
			['/path', true],
			['/foo/bar', true],
			['/foo//bar/', true],
			['/foo////bar', true],
			['/foo//\///bar', true],
			['/foo/bar/.', true],
			['/foo/bar/./', true],
			['/foo/bar/./.', true],
			['/foo/bar/././', true],
			['/foo/bar/././..bar', true],
			['/foo/bar/././..bar/a', true],
			['/foo/bar/././..', false],
			['/foo/bar/././../', false],
			['/foo/bar/.././', false],
			['/foo/bar/../../', false],
			['/foo/bar/../..\\', false],
			['..', false],
			['../', false],
			['../foo/bar', false],
			['..\foo/bar', false],
		];
	}

	/**
	 * @dataProvider isValidPathData
	 */
	public function testIsValidPath($path, $expected) {
		$this->assertSame($expected, Filesystem::isValidPath($path));
	}

	public function isFileBlacklistedData() {
		return [
			['/etc/foo/bar/foo.txt', false],
			['\etc\foo/bar\foo.txt', false],
			['.htaccess', true],
			['.htaccess/', true],
			['.htaccess\\', true],
			['/etc/foo\bar/.htaccess\\', true],
			['/etc/foo\bar/.htaccess/', true],
			['/etc/foo\bar/.htaccess/foo', true],
			['//foo//bar/\.htaccess/', true],
			['\foo\bar\.HTAccess', true],
		];
	}

	/**
	 * @dataProvider isFileBlacklistedData
	 */
	public function testIsFileBlacklisted($path, $expected) {
		$this->assertSame($expected, Filesystem::isForbiddenFileOrDir($path, ['.htaccess']));
	}

	public function isFileBlacklistedRegexData() {
		return [
			['/etc/foo/outlook.ptt',      [ '.*\.pst$', '.*dummy.*', '^sample.*', ], false],
			['/etc/foo/outlook.pst',      [ '.*\.pst$', '.*dummy.*', '^sample.*', ], true],
			['/etc/foo/outlook.PST',      [ '.*\.pst$', '.*dummy.*', '^sample.*', ], true],
			['/toto.txt',                 [ '.*\.pst$', '.*dummy.*', '^sample.*', ], false],
			['/etc/toto.txt',             [ '.*\.pst$', '.*dummy.*', '^sample.*', ], false],
			['/etc/foo/machin.txt',       [ '.*\.pst$', '.*dummy.*', '^sample.*', ], false],
			['/etc/dummy/machin.chose',   [ '.*\.pst$', '.*dummy.*', '^sample.*', ], true],
			['/etc/foo/dummy_machin.txt', [ '.*\.pst$', '.*dummy.*', '^sample.*', ], true],
			['/etc/foo/dUMMy_machin.txt', [ '.*\.pst$', '.*dummy.*', '^sample.*', ], true],
			['/etc/foo/sample.txt',       [ '.*\.pst$', '.*dummy.*', '^sample.*', ], true],
			['/sample.pst',               [ '.*\.pst$', '.*dummy.*', '^sample.*', ], true],
		];
	}

	/**
	 * @dataProvider isFileBlacklistedRegexData
	 */
	public function testIsFileBlacklistedRegex($path, $regex, $expected) {
		$this->assertSame($expected, Filesystem::isForbiddenFileOrDir($path, $regex));
	}

	public function isExcludedData() {
		return [
			['.snapshot', true],
			['.snapshot/', true],
			['.snapshot\\', true],
			['/etc/foo/bar/foo.txt', false],
			['/.snapshot/etc/foo/bar/foo.txt', true],
			['/.snapShot/etc/foo/bar/foo.txt', true],
			['\.snapshot\etc\foo/bar\foo.txt', true],
			['/etc/foo/.snapshot', true],
			['/etc/foo/.snapshot/bar', true],
		];
	}

	/**
	 * The parameter array can be redesigned if filesystem.php will get a constructor where it is possible to
	 * define the excluded directories for unit tests
	 * @dataProvider isExcludedData
	 */
	public function testIsExcluded($path, $expected) {
		$this->assertSame($expected, Filesystem::isForbiddenFileOrDir($path, ['.snapshot']));
	}

	public function isExcludedDataRegex() {
		return [
			['/backup',               [ '.*backup.*', 'Thomas.*', ], true],
			['/_backup',              [ '.*backup.*', 'Thomas.*', ], true],
			['/backup_',              [ '.*backup.*', 'Thomas.*', ], true],
			['/foo/backup/bar',       [ '.*backup.*', 'Thomas.*', ], true],
			['/foo/baCKup/bar',       [ '.*backup.*', 'Thomas.*', ], true],
			['/foo/bac.kup/bar',      [ '.*backup.*', 'Thomas.*', ], false],
			['/ThomasFolder',         [ '.*backup.*', 'Thomas.*', ], true],
			['/thomasFolder',         [ '.*backup.*', 'Thomas.*', ], true],
			['/foo/_Thomas/Files',    [ '.*backup.*', 'Thomas.*', ], true],
			['/foo/ThomasFoo/Files',  [ '.*backup.*', 'Thomas.*', ], true],
			['/foo/_ThomasFoo/Files', [ '.*backup.*', 'Thomas.*', ], true],
		];
	}

	/**
	 * The parameter array can be redesigned if filesystem.php will get a constructor where it is possible to
	 * define the excluded directories for unit tests
	 * @dataProvider isExcludedDataRegex
	 */
	public function testIsExcludedRegex($path, $regex, $expected) {
		$this->assertSame($expected, Filesystem::isForbiddenFileOrDir($path, $regex));
	}

	public function testNormalizePathUTF8() {
		if (!\class_exists('Patchwork\PHP\Shim\Normalizer')) {
			$this->markTestSkipped('UTF8 normalizer Patchwork was not found');
		}

		$this->assertEquals("/foo/bar\xC3\xBC", Filesystem::normalizePath("/foo/baru\xCC\x88"));
		$this->assertEquals("/foo/bar\xC3\xBC", Filesystem::normalizePath("\\foo\\baru\xCC\x88"));
	}

	public function testHooks() {
		if (Filesystem::getView()) {
			$user = \OC_User::getUser();
		} else {
			$user = self::TEST_FILESYSTEM_USER1;
			$this->createUser($user, $user);
			$userObj = \OC::$server->getUserManager()->get($user);
			\OC::$server->getUserSession()->setUser($userObj);
			Filesystem::init($user, '/' . $user . '/files');
		}
		\OC_Hook::clear('OC_Filesystem');
		\OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook');

		Filesystem::mount('OC\Files\Storage\Temporary', [], '/');

		$rootView = new View('');
		$rootView->mkdir('/' . $user);
		$rootView->mkdir('/' . $user . '/files');

//		\OC\Files\Filesystem::file_put_contents('/foo', 'foo');
		Filesystem::mkdir('/bar');
//		\OC\Files\Filesystem::file_put_contents('/bar//foo', 'foo');

		$tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
		\file_put_contents($tmpFile, 'foo');
		$fh = \fopen($tmpFile, 'r');
//		\OC\Files\Filesystem::file_put_contents('/bar//foo', $fh);
	}

	/**
	 * Tests that an exception is thrown when passed user does not exist.
	 *
	 */
	public function testLocalMountWhenUserDoesNotExist() {
		$this->expectException(\OC\User\NoUserException::class);

		$userId = $this->getUniqueID('user_');

		Filesystem::initMountPoints($userId);
	}

	/**
	 */
	public function testNullUserThrows() {
		$this->expectException(\OC\User\NoUserException::class);

		Filesystem::initMountPoints(null);
	}

	public function testNullUserThrowsTwice() {
		$thrown = 0;
		try {
			Filesystem::initMountPoints(null);
		} catch (NoUserException $e) {
			$thrown++;
		}
		try {
			Filesystem::initMountPoints(null);
		} catch (NoUserException $e) {
			$thrown++;
		}
		$this->assertEquals(2, $thrown);
	}

	/**
	 * Tests that an exception is thrown when passed user does not exist.
	 */
	public function testLocalMountWhenUserDoesNotExistTwice() {
		$thrown = 0;
		$userId = $this->getUniqueID('user_');

		try {
			Filesystem::initMountPoints($userId);
		} catch (NoUserException $e) {
			$thrown++;
		}

		try {
			Filesystem::initMountPoints($userId);
		} catch (NoUserException $e) {
			$thrown++;
		}

		$this->assertEquals(2, $thrown);
	}

	public function testUserNameCasing() {
		$this->logout();
		$userId = $this->getUniqueID('user_');
		$this->createUser($userId);

		$view = new View();
		$this->assertFalse($view->file_exists('/' . $userId));

		Filesystem::initMountPoints(\strtoupper($userId));

		list($storage1, $path1) = $view->resolvePath('/' . $userId);
		list($storage2, $path2) = $view->resolvePath('/' . \strtoupper($userId));

		$this->assertTrue($storage1->instanceOfStorage('\OCP\Files\IHomeStorage'));
		$this->assertEquals('', $path1);

		// not mounted, still on the local root storage
		$this->assertEquals(\strtoupper($userId), $path2);
	}

	/**
	 * Tests that the home storage is used for the user's mount point
	 */
	public function testHomeMount() {
		$userId = $this->getUniqueID('user_');

		\OC::$server->getUserManager()->createUser($userId, $userId);

		Filesystem::initMountPoints($userId);

		$homeMount = Filesystem::getStorage('/' . $userId . '/');

		$this->assertTrue($homeMount->instanceOfStorage('\OCP\Files\IHomeStorage'));
		if ($this->runsWithPrimaryObjectstorage()) {
			$this->assertTrue($homeMount->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage'));
			$this->assertEquals('object::user:' . $userId, $homeMount->getId());
		} else {
			$this->assertTrue($homeMount->instanceOfStorage('\OC\Files\Storage\Home'));
			$this->assertEquals('home::' . $userId, $homeMount->getId());
		}

		$user = \OC::$server->getUserManager()->get($userId);
		if ($user !== null) {
			$user->delete();
		}
	}

	public function dummyHook($arguments) {
		$path = $arguments['path'];
		$this->assertEquals($path, Filesystem::normalizePath($path)); //the path passed to the hook should already be normalized
	}

	/**
	 * Test that the default cache dir is part of the user's home
	 */
	public function testMountDefaultCacheDir() {
		$userId = $this->getUniqueID('user_');
		$config = \OC::$server->getConfig();
		$oldCachePath = $config->getSystemValue('cache_path', '');
		// no cache path configured
		$config->setSystemValue('cache_path', '');

		\OC::$server->getUserManager()->createUser($userId, $userId);
		Filesystem::initMountPoints($userId);

		$this->assertEquals(
			'/' . $userId . '/',
			Filesystem::getMountPoint('/' . $userId . '/cache')
		);
		list($storage, $internalPath) = Filesystem::resolvePath('/' . $userId . '/cache');
		$this->assertTrue($storage->instanceOfStorage('\OCP\Files\IHomeStorage'));
		$this->assertEquals('cache', $internalPath);
		$user = \OC::$server->getUserManager()->get($userId);
		if ($user !== null) {
			$user->delete();
		}

		$config->setSystemValue('cache_path', $oldCachePath);
	}

	/**
	 * Test that an external cache is mounted into
	 * the user's home
	 */
	public function testMountExternalCacheDir() {
		$userId = $this->getUniqueID('user_');

		$config = \OC::$server->getConfig();
		$oldCachePath = $config->getSystemValue('cache_path', '');
		// set cache path to temp dir
		$cachePath = \OC::$server->getTempManager()->getTemporaryFolder() . '/extcache';
		$config->setSystemValue('cache_path', $cachePath);

		\OC::$server->getUserManager()->createUser($userId, $userId);
		Filesystem::initMountPoints($userId);

		$this->assertEquals(
			'/' . $userId . '/cache/',
			Filesystem::getMountPoint('/' . $userId . '/cache')
		);
		list($storage, $internalPath) = Filesystem::resolvePath('/' . $userId . '/cache');
		$this->assertTrue($storage->instanceOfStorage('\OC\Files\Storage\Local'));
		$this->assertEquals('', $internalPath);
		$user = \OC::$server->getUserManager()->get($userId);
		if ($user !== null) {
			$user->delete();
		}

		$config->setSystemValue('cache_path', $oldCachePath);
	}

	public function testRegisterMountProviderAfterSetup() {
		Filesystem::initMountPoints(self::TEST_FILESYSTEM_USER2);
		$this->assertEquals('/', Filesystem::getMountPoint('/foo/bar'));
		$mount = new MountPoint(new Temporary([]), '/foo/bar');
		$mountProvider = new DummyMountProvider([self::TEST_FILESYSTEM_USER2 => [$mount]]);
		$um = \OC::$server->getUserManager();
		\OC::$server->getMountProviderCollection()->registerProvider($mountProvider);
		$this->assertEquals('/foo/bar/', Filesystem::getMountPoint('/foo/bar'));
	}
}


text:
package csicommon

import (
	"context"

	"github.com/ceph/ceph-csi/internal/util/log"

	"github.com/container-storage-interface/spec/lib/go/csi"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	mount "k8s.io/mount-utils"
)

// DefaultNodeServer stores driver object.
type DefaultNodeServer struct {
	csi.UnimplementedNodeServer
	Driver  *CSIDriver
	Type    string
	Mounter mount.Interface
}

// NodeExpandVolume returns unimplemented response.
func (ns *DefaultNodeServer) NodeExpandVolume(
	ctx context.Context,
	req *csi.NodeExpandVolumeRequest,
) (*csi.NodeExpandVolumeResponse, error) {
	return nil, status.Error(codes.Unimplemented, "")
}

// NodeGetInfo returns node ID.
func (ns *DefaultNodeServer) NodeGetInfo(
	ctx context.Context,
	req *csi.NodeGetInfoRequest,
) (*csi.NodeGetInfoResponse, error) {
	log.TraceLog(ctx, "Using default NodeGetInfo")

	csiTopology := &csi.Topology{
		Segments: ns.Driver.topology,
	}

	return &csi.NodeGetInfoResponse{
		NodeId:             ns.Driver.nodeID,
		AccessibleTopology: csiTopology,
	}, nil
}

// NodeGetCapabilities returns RPC unknown capability.
func (ns *DefaultNodeServer) NodeGetCapabilities(
	ctx context.Context,
	req *csi.NodeGetCapabilitiesRequest,
) (*csi.NodeGetCapabilitiesResponse, error) {
	log.TraceLog(ctx, "Using default NodeGetCapabilities")

	return &csi.NodeGetCapabilitiesResponse{
		Capabilities: []*csi.NodeServiceCapability{
			{
				Type: &csi.NodeServiceCapability_Rpc{
					Rpc: &csi.NodeServiceCapability_RPC{
						Type: csi.NodeServiceCapability_RPC_UNKNOWN,
					},
				},
			},
		},
	}, nil
}

// ConstructMountOptions returns only unique mount options in slice.
func ConstructMountOptions(mountOptions []string, volCap *csi.VolumeCapability) []string {
	if m := volCap.GetMount(); m != nil {
		hasOption := func(options []string, opt string) bool {
			for _, o := range options {
				if o == opt {
					return true
				}
			}

			return false
		}
		for _, f := range m.MountFlags {
			if !hasOption(mountOptions, f) {
				mountOptions = append(mountOptions, f)
			}
		}
	}

	return mountOptions
}

// MountOptionContains checks the opt is present in mountOptions.
func MountOptionContains(mountOptions []string, opt string) bool {
	for _, mnt := range mountOptions {
		if mnt == opt {
			return true
		}
	}

	return false
}


text:
package scala
package util
package control

import scala.annotation.tailrec
import scala.reflect.{ClassTag, classTag}
import scala.language.implicitConversions

/** Classes representing the components of exception handling.
 *
 *  Each class is independently composable.
 *
 *  This class differs from [[scala.util.Try]] in that it focuses on composing exception handlers rather than
 *  composing behavior.  All behavior should be composed first and fed to a [[Catch]] object using one of the
 *  `opt`, `either` or `withTry` methods. Taken together the classes provide a DSL for composing catch and finally
 *  behaviors.
 *
 *  === Examples ===
 *
 *  Create a `Catch` which handles specified exceptions.
 *  {{{
 *  import scala.util.control.Exception._
 *  import java.net._
 *
 *  val s = "http://www.scala-lang.org/"
 *
 *  // Some(http://www.scala-lang.org/)
 *  val x1: Option[URL] = catching(classOf[MalformedURLException]) opt new URL(s)
 *
 *  // Right(http://www.scala-lang.org/)
 *  val x2: Either[Throwable,URL] =
 *    catching(classOf[MalformedURLException], classOf[NullPointerException]) either new URL(s)
 *
 *  // Success(http://www.scala-lang.org/)
 *  val x3: Try[URL] = catching(classOf[MalformedURLException], classOf[NullPointerException]) withTry new URL(s)
 *
 *  val defaultUrl = new URL("http://example.com")
 *  //  URL(http://example.com) because htt/xx throws MalformedURLException
 *  val x4: URL = failAsValue(classOf[MalformedURLException])(defaultUrl)(new URL("htt/xx"))
 *  }}}
 *
 *  Create a `Catch` which logs exceptions using `handling` and `by`.
 *  {{{
 *  def log(t: Throwable): Unit = t.printStackTrace
 *
 *  val withThrowableLogging: Catch[Unit] = handling(classOf[MalformedURLException]) by (log)
 *
 *  def printUrl(url: String) : Unit = {
 *    val con = new URL(url) openConnection()
 *    val source = scala.io.Source.fromInputStream(con.getInputStream())
 *    source.getLines.foreach(println)
 *  }
 *
 *  val badUrl = "htt/xx"
 *  // Prints stacktrace,
 *  //   java.net.MalformedURLException: no protocol: htt/xx
 *  //     at java.net.URL.<init>(URL.java:586)
 *  withThrowableLogging { printUrl(badUrl) }
 *
 *  val goodUrl = "http://www.scala-lang.org/"
 *  // Prints page content,
 *  //   <!DOCTYPE html>
 *  //   <html>
 *  withThrowableLogging { printUrl(goodUrl) }
 *  }}}
 *
 *  Use `unwrapping` to create a `Catch` that unwraps exceptions before rethrowing.
 *  {{{
 *  class AppException(cause: Throwable) extends RuntimeException(cause)
 *
 *  val unwrappingCatch: Catch[Nothing] = unwrapping(classOf[AppException])
 *
 *  def calcResult: Int = throw new AppException(new NullPointerException)
 *
 *  // Throws NPE not AppException,
 *  //   java.lang.NullPointerException
 *  //     at .calcResult(<console>:17)
 *  val result = unwrappingCatch(calcResult)
 *  }}}
 *
 *  Use `failAsValue` to provide a default when a specified exception is caught.
 *
 *  {{{
 *  val inputDefaulting: Catch[Int] = failAsValue(classOf[NumberFormatException])(0)
 *  val candidatePick = "seven" // scala.io.StdIn.readLine()
 *
 *  // Int = 0
 *  val pick = inputDefaulting(candidatePick.toInt)
 *  }}}
 *
 *  Compose multiple `Catch`s with `or` to build a `Catch` that provides default values varied by exception.
 *  {{{
 *  val formatDefaulting: Catch[Int] = failAsValue(classOf[NumberFormatException])(0)
 *  val nullDefaulting: Catch[Int] = failAsValue(classOf[NullPointerException])(-1)
 *  val otherDefaulting: Catch[Int] = nonFatalCatch withApply(_ => -100)
 *
 *  val combinedDefaulting: Catch[Int] = formatDefaulting or nullDefaulting or otherDefaulting
 *
 *  def p(s: String): Int = s.length * s.toInt
 *
 *  // Int = 0
 *  combinedDefaulting(p("tenty-nine"))
 *
 *  // Int = -1
 *  combinedDefaulting(p(null: String))
 *
 *  // Int = -100
 *  combinedDefaulting(throw new IllegalStateException)
 *
 *  // Int = 22
 *  combinedDefaulting(p("11"))
 *  }}}
 *
 *  @groupname composition-catch Catch behavior composition
 *  @groupprio composition-catch 10
 *  @groupdesc composition-catch Build Catch objects from exception lists and catch logic
 *
 *  @groupname composition-finally Finally behavior composition
 *  @groupprio composition-finally 20
 *  @groupdesc composition-finally Build Catch objects from finally logic
 *
 *  @groupname canned-behavior General purpose catch objects
 *  @groupprio canned-behavior 30
 *  @groupdesc canned-behavior Catch objects with predefined behavior. Use combinator methods to compose additional behavior.
 *
 *  @groupname dsl DSL behavior composition
 *  @groupprio dsl 40
 *  @groupdesc dsl Expressive Catch behavior composition
 *
 *  @groupname composition-catch-promiscuously Promiscuous Catch behaviors
 *  @groupprio composition-catch-promiscuously 50
 *  @groupdesc composition-catch-promiscuously Useful if catching `ControlThrowable` or `InterruptedException` is required.
 *
 *  @groupname logic-container Logic Containers
 *  @groupprio logic-container 60
 *  @groupdesc logic-container Containers for catch and finally behavior.
 *
 *  @define protectedExceptions `ControlThrowable` or `InterruptedException`
 */

object Exception {
  type Catcher[+T] = PartialFunction[Throwable, T]

  def mkCatcher[Ex <: Throwable: ClassTag, T](isDef: Ex => Boolean, f: Ex => T): PartialFunction[Throwable, T] = new Catcher[T] {
    private def downcast(x: Throwable): Option[Ex] =
      if (classTag[Ex].runtimeClass.isAssignableFrom(x.getClass)) Some(x.asInstanceOf[Ex])
      else None

    def isDefinedAt(x: Throwable): Boolean = downcast(x) exists isDef
    def apply(x: Throwable): T = f(downcast(x).get)
  }

  def mkThrowableCatcher[T](isDef: Throwable => Boolean, f: Throwable => T): PartialFunction[Throwable, T] = mkCatcher[Throwable, T](isDef, f)

  implicit def throwableSubtypeToCatcher[Ex <: Throwable: ClassTag, T](pf: PartialFunction[Ex, T]): Catcher[T] =
    mkCatcher(pf.isDefinedAt, pf.apply)

  /** !!! Not at all sure of every factor which goes into this,
   *  and/or whether we need multiple standard variations.
   *  @return true if `x` is $protectedExceptions otherwise false.
   */
  def shouldRethrow(x: Throwable): Boolean = x match {
    case _: ControlThrowable      => true
    case _: InterruptedException  => true
    // case _: java.lang.Error       => true ?
    case _                        => false
  }

  trait Described {
    protected val name: String
    private[this] var _desc: String = ""
    def desc: String = _desc
    def withDesc(s: String): this.type = {
      _desc = s
      this
    }
    override def toString(): String = name + "(" + desc + ")"
  }

  /** A container class for finally code.
   *  @group logic-container
   */
  class Finally private[Exception](body: => Unit) extends Described {
    protected val name = "Finally"

    def and(other: => Unit): Finally = new Finally({ body ; other })
    def invoke(): Unit = { body }
  }

  /** A container class for catch/finally logic.
   *
   *  Pass a different value for rethrow if you want to probably
   *  unwisely allow catching control exceptions and other throwables
   *  which the rest of the world may expect to get through.
   *  @tparam T result type of bodies used in try and catch blocks
   *  @param pf Partial function used when applying catch logic to determine result value
   *  @param fin Finally logic which if defined will be invoked after catch logic
   *  @param rethrow Predicate on throwables determining when to rethrow a caught [[Throwable]]
   *  @group logic-container
   */
  class Catch[+T](
    val pf: Catcher[T],
    val fin: Option[Finally] = None,
    val rethrow: Throwable => Boolean = shouldRethrow)
  extends Described {

    protected val name = "Catch"

    /** Create a new Catch with additional exception handling logic. */
    def or[U >: T](pf2: Catcher[U]): Catch[U] = new Catch(pf orElse pf2, fin, rethrow)
    def or[U >: T](other: Catch[U]): Catch[U] = or(other.pf)

    /** Apply this catch logic to the supplied body. */
    def apply[U >: T](body: => U): U =
      try body
      catch {
        case x if rethrow(x)        => throw x
        case x if pf isDefinedAt x  => pf(x)
      }
      finally fin foreach (_.invoke())

    /** Create a new Catch container from this object and the supplied finally body.
     *  @param body The additional logic to apply after all existing finally bodies
     */
    def andFinally(body: => Unit): Catch[T] = {
      val appendedFin = fin map(_ and body) getOrElse new Finally(body)
      new Catch(pf, Some(appendedFin), rethrow)
    }

    /** Apply this catch logic to the supplied body, mapping the result
     *  into `Option[T]` - `None` if any exception was caught, `Some(T)` otherwise.
     */
    def opt[U >: T](body: => U): Option[U] = toOption(Some(body))

    /** Apply this catch logic to the supplied body, mapping the result
     *  into `Either[Throwable, T]` - `Left(exception)` if an exception was caught,
     *  `Right(T)` otherwise.
     */
    def either[U >: T](body: => U): Either[Throwable, U] = toEither(Right(body))

    /** Apply this catch logic to the supplied body, mapping the result
     * into `Try[T]` - `Failure` if an exception was caught, `Success(T)` otherwise.
     */
    def withTry[U >: T](body: => U): scala.util.Try[U] = toTry(Success(body))

    /** Create a `Catch` object with the same `isDefinedAt` logic as this one,
      * but with the supplied `apply` method replacing the current one. */
    def withApply[U](f: Throwable => U): Catch[U] = {
      val pf2 = new Catcher[U] {
        def isDefinedAt(x: Throwable): Boolean = pf isDefinedAt x
        def apply(x: Throwable): U = f(x)
      }
      new Catch(pf2, fin, rethrow)
    }

    /** Convenience methods. */
    def toOption: Catch[Option[T]] = withApply(_ => None)
    def toEither: Catch[Either[Throwable, T]] = withApply(Left(_))
    def toTry: Catch[scala.util.Try[T]] = withApply(x => Failure(x))
  }

  final val nothingCatcher: Catcher[Nothing]  = mkThrowableCatcher(_ => false, throw _)
  final def nonFatalCatcher[T]: Catcher[T]    = mkThrowableCatcher({ case NonFatal(_) => true; case _ => false }, throw _)
  final def allCatcher[T]: Catcher[T]         = mkThrowableCatcher(_ => true, throw _)

  /** The empty `Catch` object.
   *  @group canned-behavior
   **/
  final val noCatch: Catch[Nothing] = new Catch(nothingCatcher) withDesc "<nothing>"

  /** A `Catch` object which catches everything.
   *  @group canned-behavior
   **/
  final def allCatch[T]: Catch[T] = new Catch(allCatcher[T]) withDesc "<everything>"

  /** A `Catch` object which catches non-fatal exceptions.
   *  @group canned-behavior
   **/
  final def nonFatalCatch[T]: Catch[T] = new Catch(nonFatalCatcher[T]) withDesc "<non-fatal>"

  /** Creates a `Catch` object which will catch any of the supplied exceptions.
   *  Since the returned `Catch` object has no specific logic defined and will simply
   *  rethrow the exceptions it catches, you will typically want to call `opt`,
   *  `either` or `withTry` on the return value, or assign custom logic by calling "withApply".
   *
   *  Note that `Catch` objects automatically rethrow `ControlExceptions` and others
   *  which should only be caught in exceptional circumstances.  If you really want
   *  to catch exactly what you specify, use `catchingPromiscuously` instead.
   *  @group composition-catch
   */
  def catching[T](exceptions: Class[_]*): Catch[T] =
    new Catch(pfFromExceptions(exceptions : _*)) withDesc (exceptions map (_.getName) mkString ", ")

  def catching[T](c: Catcher[T]): Catch[T] = new Catch(c)

  /** Creates a `Catch` object which will catch any of the supplied exceptions.
   *  Unlike "catching" which filters out those in shouldRethrow, this one will
   *  catch whatever you ask of it including $protectedExceptions.
   *  @group composition-catch-promiscuously
   */
  def catchingPromiscuously[T](exceptions: Class[_]*): Catch[T] = catchingPromiscuously(pfFromExceptions(exceptions : _*))
  def catchingPromiscuously[T](c: Catcher[T]): Catch[T]         = new Catch(c, None, _ => false)

  /** Creates a `Catch` object which catches and ignores any of the supplied exceptions.
   *  @group composition-catch
   */
  def ignoring(exceptions: Class[_]*): Catch[Unit] =
    catching(exceptions: _*) withApply (_ => ())

  /** Creates a `Catch` object which maps all the supplied exceptions to `None`.
   *  @group composition-catch
   */
  def failing[T](exceptions: Class[_]*): Catch[Option[T]] =
    catching(exceptions: _*) withApply (_ => None)

  /** Creates a `Catch` object which maps all the supplied exceptions to the given value.
   *  @group composition-catch
   */
  def failAsValue[T](exceptions: Class[_]*)(value: => T): Catch[T] =
    catching(exceptions: _*) withApply (_ => value)

  class By[T,R](f: T => R) {
    def by(x: T): R = f(x)
  }

  /** Returns a partially constructed `Catch` object, which you must give
    * an exception handler function as an argument to `by`.
    * @example
    * {{{
    *   handling(classOf[MalformedURLException], classOf[NullPointerException]) by (_.printStackTrace)
    * }}}
    *  @group dsl
    */
  def handling[T](exceptions: Class[_]*): By[Throwable => T, Catch[T]] = {
    def fun(f: Throwable => T): Catch[T] = catching(exceptions: _*) withApply f
    new By[Throwable => T, Catch[T]](fun)
  }

  /** Returns a `Catch` object with no catch logic and the argument as the finally logic.
   *  @group composition-finally
   */
  def ultimately[T](body: => Unit): Catch[T] = noCatch andFinally body

  /** Creates a `Catch` object which unwraps any of the supplied exceptions.
   *  @group composition-catch
   */
  def unwrapping[T](exceptions: Class[_]*): Catch[T] = {
    @tailrec
    def unwrap(x: Throwable): Throwable =
      if (wouldMatch(x, exceptions) && x.getCause != null) unwrap(x.getCause)
      else x

    catching(exceptions: _*) withApply (x => throw unwrap(x))
  }

  /** Private **/
  private def wouldMatch(x: Throwable, classes: scala.collection.Seq[Class[_]]): Boolean =
    classes exists (_ isAssignableFrom x.getClass)

  private def pfFromExceptions(exceptions: Class[_]*): PartialFunction[Throwable, Nothing] =
    { case x if wouldMatch(x, exceptions) => throw x }
}