text:
import { outputFile } from "fs-extra"
import { homedir } from "os"
import * as path from "path"
import { TmpDir } from "temp-file"
import { InvalidConfigurationError } from "builder-util"
import { statOrNull } from "builder-util/out/fs"
import { download } from "../binDownload"

/** @private */
export async function importCertificate(cscLink: string, tmpDir: TmpDir, currentDir: string): Promise<string> {
  cscLink = cscLink.trim()

  let file: string | null = null
  if ((cscLink.length > 3 && cscLink[1] === ":") || cscLink.startsWith("/") || cscLink.startsWith(".")) {
    file = cscLink
  } else if (cscLink.startsWith("file://")) {
    file = cscLink.substring("file://".length)
  } else if (cscLink.startsWith("~/")) {
    file = path.join(homedir(), cscLink.substring("~/".length))
  } else if (cscLink.startsWith("https://")) {
    const tempFile = await tmpDir.getTempFile({ suffix: ".p12" })
    await download(cscLink, tempFile)
    return tempFile
  } else {
    const mimeType = /data:.*;base64,/.exec(cscLink)?.[0]
    if (mimeType || cscLink.length > 2048 || cscLink.endsWith("=")) {
      const tempFile = await tmpDir.getTempFile({ suffix: ".p12" })
      await outputFile(tempFile, Buffer.from(cscLink.substring(mimeType?.length ?? 0), "base64"))
      return tempFile
    }
    file = cscLink
  }

  file = path.resolve(currentDir, file)
  const stat = await statOrNull(file)
  if (stat == null) {
    throw new InvalidConfigurationError(`${file} doesn't exist`)
  } else if (!stat.isFile()) {
    throw new InvalidConfigurationError(`${file} not a file`)
  } else {
    return file
  }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.11.29 at 12:35:53 PM GMT
//

package org.mule.modules.hybris.model;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for flexibleSearchCronJobDTO complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="flexibleSearchCronJobDTO">
 *   <complexContent>
 *     <extension base="{}mediaProcessCronJobDTO">
 *       <sequence>
 *         <element name="count" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="dontNeedTotal" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="failOnUnknown" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="query" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="rangeStart" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="searchResult" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "flexibleSearchCronJobDTO", propOrder = {
    "count",
    "dontNeedTotal",
    "failOnUnknown",
    "query",
    "rangeStart",
    "searchResult"
})
public class FlexibleSearchCronJobDTO
    extends MediaProcessCronJobDTO
{

    protected Integer count;
    protected Boolean dontNeedTotal;
    protected Boolean failOnUnknown;
    protected String query;
    protected Integer rangeStart;
    protected FlexibleSearchCronJobDTO.SearchResult searchResult;

    /**
     * Gets the value of the count property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getCount() {
        return count;
    }

    /**
     * Sets the value of the count property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setCount(Integer value) {
        this.count = value;
    }

    /**
     * Gets the value of the dontNeedTotal property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isDontNeedTotal() {
        return dontNeedTotal;
    }

    /**
     * Sets the value of the dontNeedTotal property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setDontNeedTotal(Boolean value) {
        this.dontNeedTotal = value;
    }

    /**
     * Gets the value of the failOnUnknown property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isFailOnUnknown() {
        return failOnUnknown;
    }

    /**
     * Sets the value of the failOnUnknown property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setFailOnUnknown(Boolean value) {
        this.failOnUnknown = value;
    }

    /**
     * Gets the value of the query property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getQuery() {
        return query;
    }

    /**
     * Sets the value of the query property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setQuery(String value) {
        this.query = value;
    }

    /**
     * Gets the value of the rangeStart property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getRangeStart() {
        return rangeStart;
    }

    /**
     * Sets the value of the rangeStart property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setRangeStart(Integer value) {
        this.rangeStart = value;
    }

    /**
     * Gets the value of the searchResult property.
     *
     * @return
     *     possible object is
     *     {@link FlexibleSearchCronJobDTO.SearchResult }
     *
     */
    public FlexibleSearchCronJobDTO.SearchResult getSearchResult() {
        return searchResult;
    }

    /**
     * Sets the value of the searchResult property.
     *
     * @param value
     *     allowed object is
     *     {@link FlexibleSearchCronJobDTO.SearchResult }
     *
     */
    public void setSearchResult(FlexibleSearchCronJobDTO.SearchResult value) {
        this.searchResult = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "value"
    })
    public static class SearchResult {

        protected List<String> value;

        /**
         * Gets the value of the value property.
         *
         *

         * This accessor method returns a reference to the live list,
         * not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a set method for the value property.
         *
         *

         * For example, to add a new item, do as follows:
         *

         *    getValue().add(newItem);
         *

         *
         *
         *

         * Objects of the following type(s) are allowed in the list
         * {@link String }
         *
         *
         */
        public List<String> getValue() {
            if (value == null) {
                value = new ArrayList<String>();
            }
            return this.value;
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef XENIA_KERNEL_XTIMER_H_
#define XENIA_KERNEL_XTIMER_H_

#include "xenia/base/threading.h"
#include "xenia/kernel/xobject.h"
#include "xenia/xbox.h"

namespace xe {
namespace kernel {

class XThread;

class XTimer : public XObject {
 public:
  explicit XTimer(KernelState* kernel_state);
  ~XTimer() override;

  void Initialize(uint32_t timer_type);

  X_STATUS SetTimer(int64_t due_time, uint32_t period_ms, uint32_t routine,
                    uint32_t routine_arg, bool resume);
  X_STATUS Cancel();

  xe::threading::WaitHandle* GetWaitHandle() override { return timer_.get(); }

 private:
  std::unique_ptr<xe::threading::Timer> timer_;

  XThread* callback_thread_ = nullptr;
  uint32_t callback_routine_ = 0;
  uint32_t callback_routine_arg_ = 0;
};

}  // namespace kernel
}  // namespace xe

#endif  // XENIA_KERNEL_XTIMER_H_


text:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
'use strict';

mejs.i18n.en["mejs.time-skip-back"] = ["Skip back 1 second", "Skip back %1 seconds"];

Object.assign(mejs.MepDefaults, {
	skipBackInterval: 30,

	skipBackText: null
});

Object.assign(MediaElementPlayer.prototype, {
	buildskipback: function buildskipback(player, controls, layers, media) {
		var t = this,
		    defaultTitle = mejs.i18n.t('mejs.time-skip-back', t.options.skipBackInterval),
		    skipTitle = mejs.Utils.isString(t.options.skipBackText) ? t.options.skipBackText.replace('%1', t.options.skipBackInterval) : defaultTitle,
		    button = document.createElement('div');

		button.className = t.options.classPrefix + "button " + t.options.classPrefix + "skip-back-button";
		button.innerHTML = "<button type=\"button\" aria-controls=\"" + t.id + "\" title=\"" + skipTitle + "\" aria-label=\"" + skipTitle + "\" tabindex=\"0\">" + t.options.skipBackInterval + "</button>";

		t.addControlElement(button, 'skipback');

		button.addEventListener('click', function () {
			var duration = !isNaN(media.duration) ? media.duration : t.options.skipBackInterval;
			if (duration) {
				var current = media.currentTime === Infinity ? 0 : media.currentTime;
				media.setCurrentTime(Math.max(current - t.options.skipBackInterval, 0));
				this.querySelector('button').blur();
			}
		});
	}
});

},{}]},{},[1]);


text:
var http = require('http');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({
    ws: true //Set exports to allow for websocket proxy
});
proxy.on('error', function(e) {
    console.log(e);
});
var url = require('url');
var https = require('https');

var Route = function (host, port, path) {
    path = (typeof(path) === 'undefined') ? '/' : path;
    this.host = host;
    this[path] = port;
    this.port = port;
}

exports = module.exports = {};
//Default Values
exports.httpPort = 80;
exports.httpsPort = 443;
exports.defaultPagePort = 12000;
exports.localPath = "http://localhost"
exports.httpsOptions = false;
exports._function = {};

//Variables that will be constructed.
exports.httpRoutes = {};
exports.httpsRoutes = {};

exports.newRoute = function (host, port, path, protocall){
    path = (typeof(path) === "undefined") ? "/" : path;
    if (path[0] !== "/")
        path = "/"+path;

    switch (protocall) {
        case "http":
            if (typeof(exports.httpRoutes[host]) === 'undefined')
                exports.httpRoutes[host] = {};
            exports.httpRoutes[host][path] = (new Route(host, port, path));
            break;
        case "https":
            if (typeof(exports.httpsRoutes[host]) === 'undefined')
                exports.httpsRoutes[host] = {};
            exports.httpsRoutes[host][path] =(new Route(host, port, path));
            break;
        default:
            if (typeof(exports.httpRoutes[host]) === 'undefined')
                exports.httpRoutes[host] = {};
            if (typeof(exports.httpsRoutes[host]) === 'undefined')
                exports.httpsRoutes[host] = {};
            exports.httpRoutes[host][path] =(new Route(host, port, path));
            exports.httpsRoutes[host][path] =(new Route(host, port, path));
    }
}

exports.router = function(req, res, routes, protocall){
    protocall = (typeof(protocall) === "string") ? protocall : "web";
    var hostname = req.headers.host.split(":")[0];
    var pathname = url.parse(req.url).pathname;
    var end = true;
    var port = exports.defaultPagePort;
    if (typeof(routes[hostname]) !== "undefined") {
        if (typeof(routes[hostname][pathname]) !== "undefined")
            port = routes[hostname][pathname].port;
        else if (typeof(routes[hostname]["/"]) !== "undefined")
            port = routes[hostname]["/"].port;
    }
    console.log(port);
    proxy[protocall](req, res, {target: exports.localPath + ":"+port});
}

exports.startHttp = function (port, name, filter){
    port = (typeof(port) === 'undefined') ? exports.httsPort : port;
    name = (typeof(name) === 'undefined') ? "http_server" : name;
    if (typeof(filter) != "undefined")
        exports._function[name] = filter;

    exports[name] = http.createServer(function(req, res) {
        if (typeof(exports._function[name]) === "function")
            if(exports._function[name](req, res) === false)
                return false;
        exports.router(req, res, exports.httpRoutes)
    }).listen(port, function(){
        console.log("Http server started on port "+port);
    })
    exports[name].on("upgrade", function(req, res) {
        exports.router(req, res, exports.httpRoutes, "ws")
    })
}
exports.startHttps = function (option, port, name, filter) {
    options = (typeof(options) === 'undefined') ? exports.httpsOptions : options;
    port = (typeof(port) === 'undefined') ? exports.httpsPort : port;
    name = (typeof(name) === 'undefined') ? "https_server" : name;
    if (typeof(filter) != "undefined")
        exports._function[name] = filter;
    console.log("https started on: "+port);
    if (options === false) {
        console.log("You must declare a key & cert to start the https server");
        return false;
    }
    exports[name] = https.createServer(options, function(req, res) {
        if (typeof(exports._function[name]) === "function")
            if(exports._function[name](req, res) === false)
                return false;
        exports.router(req, res, exports.httpsRoutes);
    }).listen(port, function(){
        console.log("Https server started on port "+port);
    })
    exports[name].on('upgrade', function(req, res){
        exports.router(req, res, exports.httpsRoutes);
    })
}

exports.startDefault = function () {
    var app2 = require('express')();
    var http2 = require('http').Server(app2);
    app2.get('/', function(req, res){
      var hostname = req.headers.host.split(":")[0];
      res.send('
Hello world from '+hostname+'
');
    });
    http2.listen(exports.defaultPagePort, function(){
      console.log('Started default page at: '+exports.defaultPagePort);
    });
}
exports.start = function (){
    exports.startHttp();
    exports.startHttps();
    exports.startDefault();
}


text:
package in.techutils.tester.nlp.lang.treebank.words;

import in.techutils.tester.nlp.lang.treebank.factory.Words;
import opennlp.tools.parser.Parse;

public class RBS extends Words {
	public RBS(Parse wp) {
		super(wp);
	}
}


text:
#ifndef _NET_NETKEV_H_
#define _NET_NETKEV_H_

#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE)

/* Kernel event subclass identifiers for KEV_NETWORK_CLASS */
#define KEV_INET_SUBCLASS       1       /* inet subclass */
/* KEV_INET_SUBCLASS event codes */
#define KEV_INET_NEW_ADDR               1 /* Userland configured IP address */
#define KEV_INET_CHANGED_ADDR           2 /* Address changed event */
#define KEV_INET_ADDR_DELETED           3 /* IPv6 address was deleted */
#define KEV_INET_SIFDSTADDR             4 /* Dest. address was set */
#define KEV_INET_SIFBRDADDR             5 /* Broadcast address was set */
#define KEV_INET_SIFNETMASK             6 /* Netmask was set */
#define KEV_INET_ARPCOLLISION           7 /* ARP collision detected */
#ifdef __APPLE_API_PRIVATE
#define KEV_INET_PORTINUSE              8 /* use ken_in_portinuse */
#endif
#define KEV_INET_ARPRTRFAILURE          9 /* ARP resolution failed for router */
#define KEV_INET_ARPRTRALIVE            10 /* ARP resolution succeeded for router */

#define KEV_DL_SUBCLASS 2               /* Data Link subclass */
/*
 * Define Data-Link event subclass, and associated
 * events.
 */
#define KEV_DL_SIFFLAGS                         1
#define KEV_DL_SIFMETRICS                       2
#define KEV_DL_SIFMTU                           3
#define KEV_DL_SIFPHYS                          4
#define KEV_DL_SIFMEDIA                         5
#define KEV_DL_SIFGENERIC                       6
#define KEV_DL_ADDMULTI                         7
#define KEV_DL_DELMULTI                         8
#define KEV_DL_IF_ATTACHED                      9
#define KEV_DL_IF_DETACHING                     10
#define KEV_DL_IF_DETACHED                      11
#define KEV_DL_LINK_OFF                         12
#define KEV_DL_LINK_ON                          13
#define KEV_DL_PROTO_ATTACHED                   14
#define KEV_DL_PROTO_DETACHED                   15
#define KEV_DL_LINK_ADDRESS_CHANGED             16
#define KEV_DL_WAKEFLAGS_CHANGED                17
#define KEV_DL_IF_IDLE_ROUTE_REFCNT             18
#define KEV_DL_IFCAP_CHANGED                    19
#define KEV_DL_LINK_QUALITY_METRIC_CHANGED      20
#define KEV_DL_NODE_PRESENCE                    21
#define KEV_DL_NODE_ABSENCE                     22
#define KEV_DL_PRIMARY_ELECTED                  23
#define KEV_DL_ISSUES                           24
#define KEV_DL_IFDELEGATE_CHANGED               25
#define KEV_DL_AWDL_RESTRICTED                  26
#define KEV_DL_AWDL_UNRESTRICTED                27
#define KEV_DL_RRC_STATE_CHANGED                28
#define KEV_DL_QOS_MODE_CHANGED                 29
#define KEV_DL_LOW_POWER_MODE_CHANGED           30

#define KEV_DL_MASTER_ELECTED (_Pragma("gcc warn Use KEV_DL_PRIMARY_ELECTED instead") KEV_DL_PRIMARY_ELECTED)

#define KEV_INET6_SUBCLASS      6       /* inet6 subclass */
/* KEV_INET6_SUBCLASS event codes */
#define KEV_INET6_NEW_USER_ADDR         1 /* Userland configured IPv6 address */
#define KEV_INET6_CHANGED_ADDR          2 /* Address changed event (future) */
#define KEV_INET6_ADDR_DELETED          3 /* IPv6 address was deleted */
#define KEV_INET6_NEW_LL_ADDR           4 /* Autoconf LL address appeared */
#define KEV_INET6_NEW_RTADV_ADDR        5 /* Autoconf address has appeared */
#define KEV_INET6_DEFROUTER             6 /* Default router detected */
#define KEV_INET6_REQUEST_NAT64_PREFIX  7 /* Asking for the NAT64-prefix */

#endif /* (!_POSIX_C_SOURCE || _DARWIN_C_SOURCE) */
#endif /* _NET_NETKEV_H_ */


text:
package com.salesmanager.core.model.catalog.marketplace;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Embedded;

import com.salesmanager.core.model.catalog.catalog.Catalog;
import com.salesmanager.core.model.common.audit.AuditSection;
import com.salesmanager.core.model.common.audit.Auditable;
import com.salesmanager.core.model.generic.SalesManagerEntity;
import com.salesmanager.core.model.merchant.MerchantStore;

/**
 * A marketplace is the main grouping for the state of product presentation.
 * MarketPlace belongs to a main MerchantStore
 * A MerchantStore can have a single MarketPlace
 * A MarketPlace allows to determine the main MerchantStore allowing determination of content
 * and configurations of a given MarketPlace. A MarketPlace has a list of Catalog created by each MerchantStore
 * Each Catalog contains a list of Product. A MarketPlace has also a list of Category that merchant cannot change.
 * Only the MarketPlace can decide which category are shown and which catalog is part of product offering
 * @author c.samson
 *
 */
public class MarketPlace extends SalesManagerEntity<Long, MarketPlace> implements Auditable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private MerchantStore store;

	private Long id;

	private String code;

	private Set<Catalog> catalogs = new HashSet<Catalog>();

	@Embedded
	private AuditSection auditSection = new AuditSection();

	@Override
	public AuditSection getAuditSection() {
		return auditSection;
	}

	@Override
	public void setAuditSection(AuditSection audit) {
		this.auditSection = auditSection;
	}

	@Override
	public Long getId() {
		return id;
	}

	@Override
	public void setId(Long id) {
		this.id = id;
	}

	public MerchantStore getStore() {
		return store;
	}

	public void setStore(MerchantStore store) {
		this.store = store;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

}


text:
Super Source let's you know who's using your software projects. If you have an open source project,
and would like to understand who your users are, you should use Super Source.

## Getting Started

Getting started with Super Source takes just a few minutes. For instructions, read the
[getting started](/docs/overview/getting_started) page.

## Why Use Super Source

- Learn who's using your project.
- Develop relationships with your users.
- Send announcements over email.


text:
<!DOCTYPE html>

    <title>How Shall I Woo Thee | Miscellaneous Poems | Paul Laurence Dunbar | Lit2Go ETC</title>
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">

          Lit2Go

<form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form>

Authors

Books

Genres

Collections

Readability

      Miscellaneous Poems

      by Paul Laurence Dunbar

      How Shall I Woo Thee

        Additional Information

            Year Published:
            1913

            Language:
            English

            Country of Origin:
            United States of America

            Source:
            Dunbar, P.L. (1913). The Complete Poems of Paul Laurence Dunbar. New York: Dodd, Mead, and Company.

            Readability:

                Flesch–Kincaid Level:
                6.5

            Word Count:
            169

            Genre:
            Poetry

            Keywords:
            longing, love

            ✎ Cite This

  Share
  |

Downloads

          Audio

          Passage PDF

Student Activity

            APA

            MLA

            Chicago

            Dunbar, P. (1913). How Shall I Woo Thee. Miscellaneous Poems (Lit2Go Edition). Retrieved February 15, 2016, from http://etc.usf.edu/lit2go/186/miscellaneous-poems/3550/how-shall-i-woo-thee/

            Dunbar, Paul Laurence. "How Shall I Woo Thee." Miscellaneous Poems. Lit2Go Edition. 1913. Web. <http://etc.usf.edu/lit2go/186/miscellaneous-poems/3550/how-shall-i-woo-thee/>. February 15, 2016.

            Paul Laurence Dunbar, "How Shall I Woo Thee," Miscellaneous Poems, Lit2Go Edition, (1913), accessed February 15, 2016, http://etc.usf.edu/lit2go/186/miscellaneous-poems/3550/how-shall-i-woo-thee/.

Back

                  <audio controls style="width:99%;">
            <source src="http://etc.usf.edu/lit2go/audio/mp3/miscellaneous-poems-025-how-shall-i-woo-thee.3550.mp3" type="audio/mpeg" />
                          <source src="http://etc.usf.edu/lit2go/audio/ogg/miscellaneous-poems-025-how-shall-i-woo-thee.3550.ogg" type="audio/ogg" />
                        The embedded audio player requires a modern internet browser. You should visit Browse Happy and update your internet browser today!
          </audio>

	How shall I woo thee to win thee, mine own?

	Say in what tongue shall I tell of my love.

	I who was fearless so timid have grown,

	All that was eagle has turned into dove.

	The path from the meadow that leads to the bars

	Is more to me now than the path of the stars.

	How shall I woo thee to win thee, mine own,

	Thou who art fair and as far as the moon?

	Had I the strength of the torrent’s wild tone,

	Had I the sweetness of warblers in June;

	The strength and the sweetness might charm and persuade,

	But neither have I my petition to aid.

	How shall I woo thee to win thee, mine own?

	How shall I traverse the distance between

	My humble cot and your glorious throne?

	How shall a clown gain the ear of a queen?

	Oh teach me the tongue that shall please thee the best,

	For till I have won thee my heart may not rest.

Back

            This collection of children's literature is a part of the Educational Technology Clearinghouse and is funded by various grants.

            Copyright © 2006—2016 by the Florida Center for Instructional Technology, College of Education, University of South Florida.

License

Credits

FAQ

Giving

This document was downloaded from Lit2Go, a free online collection of stories and poems in Mp3 (audiobook) format published by the Florida Center for Instructional Technology. For more information, including classroom activities, readability data, and original sources, please visit http://etc.usf.edu/lit2go/186/miscellaneous-poems/3550/how-shall-i-woo-thee/.

Lit2Go: Miscellaneous Poems

How Shall I Woo Thee


text:
layout: post
title: "Some thoughts on anti-patterns"
description: "What's an anti-pattern? Are there rules to identify them, or is it just name-calling? Before I use the term, I try to apply some rules of thumb."
date: 2019-01-21 7:30 UTC
tags: [Design Patterns]
---
{% include JB/setup %}

		{{ page.description }}

		It takes time to write a book. Months, even years. It took me two years to write the first edition of Dependency Injection in .NET. The second edition of Dependency Injection in .NET is also the result of much work; not so much by me, but by my co-author Steven van Deursen.

		When you write a book single-handedly, you can be as opinionated as you'd like. When you have a co-author, regardless of how much you think alike, there's bound to be some disagreements. Steven and I agreed about most of the changes we'd like to make to the second edition, but each of us had to yield or compromise a few times.

		An interesting experience has been that on more than one occasion where I've reluctantly had to yield to Steven, over the time, I've come to appreciate his position. Two minds think better than one.

		Ambient Context #

		One of the changes that Steven wanted to make was that he wanted to change the status of the Ambient Context pattern to an anti-pattern. While I never use that pattern myself, I included it in the first edition in the spirit of the original Design Patterns book. The Gang of Four made it clear that the patterns they'd described weren't invented, but rather discovered:

				"We have included only designs that have been applied more than once in different systems."

			Gamma et al, Design Patterns, 1994, p. 2

		The spirit, as I understand it, is to identify solutions that already exist, and catalogue them. When I wrote the first edition of my book, I tried to do that as well.

		I'd noticed what I eventually named the Ambient Context pattern several places in the .NET Base Class Library. Some of those APIs are still around today. Thread.CurrentPrincipal, CultureInfo.CurrentCulture, thread-local storage, HttpContext.Current, and so on.

		None of these really have anything to do with Dependency Injection (DI), but people sometimes attempt to use them to solve problems similar to the problems that DI addresses. For that reason, and because the pattern was so prevalent, I included it in the book - as a pattern, not an anti-pattern.

		Steven wanted to make it an anti-pattern, and I conceded. I wasn't sure I was ready to explicitly call it out as an anti-pattern, but I agreed to the change. I'm becoming increasingly happy that Steven talked me into it.

		Pareto efficiency #

		I've heard said of me that I'm one of those people who call everything I don't like an anti-pattern. I don't think that's true.

		I think people's perception of me is skewed because even today, the most visited page (my greatest hit, if you will) is an article called Service Locator is an Anti-Pattern. (It concerns me a bit that an article from 2010 seems to be my crowning achievement. I hope I haven't peaked yet, but the numbers tell a different tale.)

		While I've used the term anti-pattern in other connections, I prefer to be conservative with my use of the word. I tend to use it only when I feel confident that something is, indeed, an anti-pattern.

		What's an anti-pattern? AntiPatterns defines it like this:

				"An AntiPattern is a literary form that describes a commonly occurring solution to a problem that generates decidedly negative consequences."

			Brown et al, AntiPatterns, 1998, p. 7

		As definitions go, it's quite amphibolous. Is it the problem that generates negative consequences? Hardly. In the context, it's clear that it's the solution that causes problems. In any case, just because it's in a book doesn't necessarily make it right, but I find it a good start.

		I think that the phrase decidedly negative consequences is key. Most solutions come with some disadvantages, but in order for a 'solution' to be an anti-pattern, the disadvantages must clearly outweigh any advantages produced.

		I usually look at it another way. If I can solve the problem in a different way that generates at least as many advantages, but fewer disadvantages, then the first 'solution' might be an anti-pattern. This way of viewing the problem may stem from my background in economics. In that perspective, an anti-pattern simply isn't Pareto optimal.

		Falsifiability #

		Another rule of thumb I employ to determine whether a solution could be an anti-pattern is Popper's concept of falsifiability. As a continuation of the Pareto efficiency perspective, an anti-pattern is a 'solution' that you can improve without any (significant) trade-offs.

		That turns claims about anti-patterns into falsifiable statements, which I consider is the most intellectually honest way to go about claiming that things are bad.

		Take, for example, the claim that Service Locator is an anti-pattern. In light of Pareto efficiency, that's a falsifiable claim. All you have to do to prove me wrong is to present a situation where Service Locator solves a problem, and I can't come up with a better solution.

		I made the claim about Service Locator in 2010, and so far, no one has been able to present such a situation, even though several have tried. I'm fairly confident making that claim.

		This way of looking at the term anti-pattern, however, makes me wary of declaiming solutions anti-patterns just because I don't like them. Could there be a counter-argument, some niche scenario, where the pattern actually couldn't be improved without trade-offs?

		I didn't take it lightly when Steven suggested making Ambient Context an anti-pattern.

		Preliminary status #

		I've had some time to think about Ambient Context since I had the (civil) discussion with Steven. The more I think about it, the more I think that he's right; that Ambient Context really is an anti-pattern.

		I never use that pattern myself, so it's clear to me that for all the situations that I typically encounter, there's always better solutions, with no significant trade-offs.

		The question is: could there be some niche scenario that I'm not aware of, where Ambient Context is a bona fide good solution?

		The more I think about this, the more I'm beginning to believe that there isn't. It remains to be seen, though. It remains to be falsified.

		Summary #

		I'm so happy that Steven van Deursen agreed to co-author the second edition of Dependency Injection in .NET with me. The few areas where we've disagreed, I've ultimately come around to agree with him. He's truly taken a good book and made it better.

		One of the changes is that Ambient Context is now classified as an anti-pattern. Originally, I wasn't sure that this was the correct thing to do, but I've since changed my mind. I do think that Ambient Context belongs in the anti-patterns chapter.

		I could be wrong, though. I was before.

    Comments

Mogens Heller Grabe

      	Thanks for great input for discussion :P

      	Like with all other patterns and anti-patterns, I think there's a time and a place.

      	Simply looking at it in a one-dimensional manner, i.e. asking "does there exist a solution to this problem with the same advantages but less downsides?" must be qualified with "IN THIS TIME AND PLACE", in my opinion.

      	This way, the patterns/anti-patterns distinction does not make that much sense in a global perspective, because all patterns can be an anti-patterns in some situations, and vice versa.

  		For example, I like what Ambient Context does in Rebus: It provides a mechanism that enables user code to transparently enlist its bus operations in a
  		unit of work, without requiring user code to pass that unit of work to each operation.

  		This is very handy, e.g. in OWIN-based applications, where the unit of work can be managed by an OWIN middleware that uses a
  		RebusTransactionScope,
  		this way enlisting all send/publish operations on the bus in that unit of work.

      	Had it not been possible to automatically pick up an ongoing ambient Rebus transaction context, one would probably need to pollute the interfaces of one's application with an ITransactionContext argument,
      	thus not handling the cross-cutting concern of managing the unit of work in a cross-cutting manner.

2019-01-21 12:37 UTC

Mark Seemann

				Mogens, thank you for writing. The reason I explicitly framed my treatment in a discourse related to Pareto efficiency is exactly because this view on optima is multi-dimensional. When considering whether a 'solution coordinate' is Pareto-optimal or not, the question is exactly whether or not it's possible to improve at least one dimension without exacerbating any other dimension. If you can make one dimension better without trade-offs, then you can make a Pareto improvement. If you can only make one dimension better at the cost of one or more other dimensions, then you already have a Pareto-optimal solution.

				The theory of Pareto efficiency doesn't say anything about the number of dimensions. Usually, as in the linked Wikipedia article, the concept is illustrated in the plane, but conceptually, it applies to an arbitrary number of dimensions.

				In the context of anti-patterns, those dimensions include time and place, as you say.

				I consider something to be an anti-pattern if I can make a change that constitutes an improvement in at least one dimension, without trading off of any other dimensions. In other words, in this article, I'm very deliberately not looking at it in a one-dimensional manner.

				As I wrote, I'm still not sure that Ambient Context is an anti-pattern (although I increasingly believe it to be). How can we even test that hypothesis when we can't really quantify software design?

				On the other hand, if we leave the question about Ambient Context for a moment, I feel confident that Service Locator is an anti-pattern, even in what you call a global perspective. The reason I believe that is that I made that falsifiable claim in 2010, and here, almost nine years later, no-one has successfully produced a valid counter-example.

				I don't have the same long history with the claim about Ambient Context, so I could be wrong. Perhaps you are, right now, proving me wrong. I can't tell, though, because I don't (yet) know enough about Rebus to be able to tell whether what you describe is Pareto-optimal.

				The question isn't whether the current design is 'handy'. The question is whether it's possible to come up with a design that's 'globally' better; i.e. either has all the advantages of the current design, but fewer disadvantages; or has more advantages, and only the same disadvantages.

				I may be able to suggest such an improvement if provided with some code examples, but in the end we may never agree whether one design is better than another. After all, since we can't quantify software design, a subjective judgement will always remain.

2019-01-24 8:00 UTC

Drew Douglas

				Mark,
Thanks for this thoughtful meta-analysis of what it means to be an anti-pattern and how we think about them. What are some considerations when designing a replacement for ambient context objects? What patterns have you found succesful in object-oriented code? I'm sure you'd mention Constructor Injection and CQRS with decorators.

How might one refactor ambient context out of a solution? Some say passing around an object, maybe some sort of continuation?

2019-04-12 6:09 UTC

Mark Seemann

				Drew, thank you for writing. Indeed, in object-oriented code, I'd typically replace Ambient Contexts with either injected dependencies or Decorators. I'm not sure I see how CQRS fits into this picture.

				When refactoring away an Ambient Context, it's typically, before the refactoring, used like Context.DoSomething(). The first step is often to inject a dependency and make it available to the class as a property called Context. IIRC, the C# overload resolution system should then pick the instance property over the static class, so that Context.DoSomething() calls DoSomething on the injected Context property.

				There may be some static member that also use the Ambient Context. If that's the case, you'll first have to make those static members instance members.

				Once you've made those replacements everywhere, you should be able to delete the Ambient Context.

2019-04-13 16:43 UTC


text:
NSString *const downloadedEpisodesCacheIdentifier = @"downloaded_episodes";

@interface ESESLEpisodeManager ()

@property (nonatomic, strong) SFFileCacheManager *cacheManager;

@end

@implementation ESESLEpisodeManager

+ (instancetype)sharedManager
{
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self class] new];
    });
    return instance;
}

- (id)init
{
    self = [super init];

    _cacheManager = [SFFileCacheManager fileCacheManagerWithFolderPath:[self _cachePath]];

    return self;
}

- (NSString *)_cachePath
{
    NSString *path = [NSString stringWithFormat:@"%@/Documents/", NSHomeDirectory()];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path] == NO) {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return path;
}

- (void)_saveDownloadedEpisodes:(NSArray *)downloadedEpisodes
{
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:downloadedEpisodes];
    [self.cacheManager storeCacheWithIdentifier:downloadedEpisodesCacheIdentifier data:data];
}

- (NSMutableArray *)_downloadedEpisodes
{
    NSData *dataOfDownloadedEpisodes = [self.cacheManager cachedDataWithIdentifier:downloadedEpisodesCacheIdentifier
                                                                            filter:[SFBuildInCacheFilters foreverCacheFilter]];
    NSMutableArray *downloadedEpisodes = nil;
    if (dataOfDownloadedEpisodes.length != 0) {
        downloadedEpisodes = [NSKeyedUnarchiver unarchiveObjectWithData:dataOfDownloadedEpisodes];
    } else {
        downloadedEpisodes = [NSMutableArray array];
    }
    return downloadedEpisodes;
}

- (void)addDownloadedEpisode:(ESEpisode *)episode
{
    [self removeDownloadedEpisode:episode];
    NSMutableArray *downloadedEpisodes = [self _downloadedEpisodes];

    BOOL exists = NO;
    for (NSDictionary *dict in downloadedEpisodes) {
        NSString *uid = [dict objectForKey:@"uid"];
        if ([uid isEqualToString:episode.uid]) {
            exists = YES;
            break;
        }
    }
    if (exists == NO) {
        NSDictionary *dict = [[SFObject2Dict object2Dict] dictionaryWithObject:episode];
        [downloadedEpisodes addObject:dict];
        [self _saveDownloadedEpisodes:downloadedEpisodes];
    }
}

- (void)removeDownloadedEpisode:(ESEpisode *)episode
{
    NSMutableArray *downloadedEpisodes = [self _downloadedEpisodes];

    NSInteger index = -1;
    for (NSInteger i = 0; i < downloadedEpisodes.count; ++i) {
        NSDictionary *dict = [downloadedEpisodes objectAtIndex:i];
        NSString *uid = [dict objectForKey:@"uid"];
        if ([uid isEqualToString:episode.uid]) {
            index = i;
            break;
        }
    }
    if (index != -1) {
        [downloadedEpisodes removeObjectAtIndex:index];
        [self _saveDownloadedEpisodes:downloadedEpisodes];
    }
}

- (void)exchangePositionWithSourceEpisode:(ESEpisode *)sourceEpisode destinationEpisode:(ESEpisode *)destinationEpisode
{

}

- (NSArray *)downloadedEpisodes
{
    NSArray *downloadedEpisides = [self _downloadedEpisodes];
    NSArray *episides = [[SFDict2Object dict2ObjectWithObjectMapping:
                          [SFObjectMapping objectMappingWithClass:[ESEpisode class]]] objectsFromDictionaries:downloadedEpisides];

    return episides;
}

- (BOOL)isEpisodeDownloaded:(ESEpisode *)episode
{
    BOOL downloaded = NO;
    downloaded = [self.cacheManager isCacheExistsWithIdentifier:[episode.soundURLString sf_stringByEncryptingUsingMD5]];
    return downloaded;
}

- (id<ESService>)soundPathWithEpisode:(ESEpisode *)episode
{
    return [self downloadSoundWithEpisode:episode progressTracker:nil sync:YES forceDownload:NO];
}

- (id<ESService>)downloadSoundWithEpisode:(ESEpisode *)episode progressTracker:(id<ESProgressTracker>)progressTracker sync:(BOOL)sync forceDownload:(BOOL)forceDownload
{
    NSString *URLString = episode.soundURLString;
    id<SFRequestProxy> requestProxy = nil;

    ESHTTPRequest *request = [ESHTTPRequest requestWithURLString:URLString];
    [request setResponseDataWrapper:^id(NSData * data) {
        NSString *identifier = [URLString sf_stringByEncryptingUsingMD5];
        [self.cacheManager storeCacheWithIdentifier:identifier data:data];
        NSString *cachedDataFilePath = [self.cacheManager cachedDataFilePathWithIdentifier:identifier];
        return cachedDataFilePath;
    }];
    __weak typeof(progressTracker) weakProgressTracker = progressTracker;
    [request setRequestProgressDidChange:^(float percent) {
        [weakProgressTracker progressUpdatingWithPercent:percent];
    }];
    requestProxy = request;
    if (forceDownload == NO) {
        ESRequestProxyWrapper *wrappedRequest = [ESRequestProxyWrapper wrapperWithRequestProxy:requestProxy resultGetter:^id(NSDictionary *parameters) {
            id result = nil;
            NSString *identifier = [URLString sf_stringByEncryptingUsingMD5];
            NSData *data = [self.cacheManager cachedDataWithIdentifier:identifier filter:[SFBuildInCacheFilters foreverCacheFilter]];
            if (data != nil) {
                NSString *cachedDataFilePath = [self.cacheManager cachedDataFilePathWithIdentifier:identifier];
                result = cachedDataFilePath;
            }
            return result;
        }];
        wrappedRequest.runSynchronously = sync;
        requestProxy = wrappedRequest;
    }

    ESServiceSession *session = [ESServiceSession sessionWithRequestProxy:requestProxy];
    __weak typeof(self) weakSelf = self;
    [session setSessionDidFinishHandler:^(id resultObject, NSError *error) {
        if (error == nil) {
            [weakSelf addDownloadedEpisode:episode];
        }
    }];

    return session;
}

- (id<ESService>)episodes
{
    return [ESEpisodeService new];
}

- (id<ESService>)newestEpisodes
{
    ESEpisodeService *service = [ESEpisodeService new];
    service.useCache = NO;
    return service;
}

- (id<ESService>)soundPathWithEpisode:(ESEpisode *)episode progressTracker:(id<ESProgressTracker>)progressTracker
{
    return [self downloadSoundWithEpisode:episode progressTracker:progressTracker sync:NO forceDownload:YES];
}

@end


text:
import csv
import io
from os.path import dirname
from os.path import join

import pytest

from werkzeug import formparser
from werkzeug.datastructures import MultiDict
from werkzeug.exceptions import RequestEntityTooLarge
from werkzeug.formparser import FormDataParser
from werkzeug.formparser import parse_form_data
from werkzeug.test import Client
from werkzeug.test import create_environ
from werkzeug.wrappers import Request
from werkzeug.wrappers import Response

@Request.application
def form_data_consumer(request):
    result_object = request.args["object"]
    if result_object == "text":
        return Response(repr(request.form["text"]))
    f = request.files[result_object]
    return Response(
        b"\n".join(
            (
                repr(f.filename).encode("ascii"),
                repr(f.name).encode("ascii"),
                repr(f.content_type).encode("ascii"),
                f.stream.read(),
            )
        )
    )

def get_contents(filename):
    with open(filename, "rb") as f:
        return f.read()

class TestFormParser:
    def test_limiting(self):
        data = b"foo=Hello+World&bar=baz"
        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="application/x-www-form-urlencoded",
            method="POST",
        )
        req.max_content_length = 400
        assert req.form["foo"] == "Hello World"

        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="application/x-www-form-urlencoded",
            method="POST",
        )
        req.max_form_memory_size = 7
        pytest.raises(RequestEntityTooLarge, lambda: req.form["foo"])

        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="application/x-www-form-urlencoded",
            method="POST",
        )
        req.max_form_memory_size = 400
        assert req.form["foo"] == "Hello World"

        data = (
            b"--foo\r\nContent-Disposition: form-field; name=foo\r\n\r\n"
            b"Hello World\r\n"
            b"--foo\r\nContent-Disposition: form-field; name=bar\r\n\r\n"
            b"bar=baz\r\n--foo--"
        )
        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        req.max_content_length = 4
        pytest.raises(RequestEntityTooLarge, lambda: req.form["foo"])

        # when the request entity is too large, the input stream should be
        # drained so that firefox (and others) do not report connection reset
        # when run through gunicorn
        # a sufficiently large stream is necessary for block-based reads
        input_stream = io.BytesIO(b"foo=" + b"x" * 128 * 1024)
        req = Request.from_values(
            input_stream=input_stream,
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        req.max_content_length = 4
        pytest.raises(RequestEntityTooLarge, lambda: req.form["foo"])
        # ensure that the stream is exhausted
        assert input_stream.read() == b""

        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        req.max_content_length = 400
        assert req.form["foo"] == "Hello World"

        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        req.max_form_memory_size = 7
        pytest.raises(RequestEntityTooLarge, lambda: req.form["foo"])

        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        req.max_form_memory_size = 400
        assert req.form["foo"] == "Hello World"

    def test_missing_multipart_boundary(self):
        data = (
            b"--foo\r\nContent-Disposition: form-field; name=foo\r\n\r\n"
            b"Hello World\r\n"
            b"--foo\r\nContent-Disposition: form-field; name=bar\r\n\r\n"
            b"bar=baz\r\n--foo--"
        )
        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data",
            method="POST",
        )
        assert req.form == {}

    def test_parse_form_data_put_without_content(self):
        # A PUT without a Content-Type header returns empty data

        # Both rfc1945 and rfc2616 (1.0 and 1.1) say "Any HTTP/[1.0/1.1] message
        # containing an entity-body SHOULD include a Content-Type header field
        # defining the media type of that body."  In the case where either
        # headers are omitted, parse_form_data should still work.
        env = create_environ("/foo", "http://example.org/", method="PUT")

        stream, form, files = formparser.parse_form_data(env)
        assert stream.read() == b""
        assert len(form) == 0
        assert len(files) == 0

    def test_parse_form_data_get_without_content(self):
        env = create_environ("/foo", "http://example.org/", method="GET")

        stream, form, files = formparser.parse_form_data(env)
        assert stream.read() == b""
        assert len(form) == 0
        assert len(files) == 0

    @pytest.mark.parametrize(
        ("no_spooled", "size"), ((False, 100), (False, 3000), (True, 100), (True, 3000))
    )
    def test_default_stream_factory(self, no_spooled, size, monkeypatch):
        if no_spooled:
            monkeypatch.setattr("werkzeug.formparser.SpooledTemporaryFile", None)

        data = b"a,b,c\n" * size
        req = Request.from_values(
            data={"foo": (io.BytesIO(data), "test.txt")}, method="POST"
        )
        file_storage = req.files["foo"]

        try:
            reader = csv.reader(io.TextIOWrapper(file_storage))
            # This fails if file_storage doesn't implement IOBase.
            # https://github.com/pallets/werkzeug/issues/1344
            # https://github.com/python/cpython/pull/3249
            assert sum(1 for _ in reader) == size
        finally:
            file_storage.close()

    def test_parse_bad_content_type(self):
        parser = FormDataParser()
        assert parser.parse("", "bad-mime-type", 0) == (
            "",
            MultiDict([]),
            MultiDict([]),
        )

    def test_parse_from_environ(self):
        parser = FormDataParser()
        stream, _, _ = parser.parse_from_environ({"wsgi.input": ""})
        assert stream is not None

@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")
class TestMultiPart:
    def test_basic(self):
        resources = join(dirname(__file__), "multipart")
        client = Client(form_data_consumer)

        repository = [
            (
                "firefox3-2png1txt",
                "---------------------------186454651713519341951581030105",
                [
                    ("anchor.png", "file1", "image/png", "file1.png"),
                    ("application_edit.png", "file2", "image/png", "file2.png"),
                ],
                "example text",
            ),
            (
                "firefox3-2pnglongtext",
                "---------------------------14904044739787191031754711748",
                [
                    ("accept.png", "file1", "image/png", "file1.png"),
                    ("add.png", "file2", "image/png", "file2.png"),
                ],
                "--long text\r\n--with boundary\r\n--lookalikes--",
            ),
            (
                "opera8-2png1txt",
                "----------zEO9jQKmLc2Cq88c23Dx19",
                [
                    ("arrow_branch.png", "file1", "image/png", "file1.png"),
                    ("award_star_bronze_1.png", "file2", "image/png", "file2.png"),
                ],
                "blafasel öäü",
            ),
            (
                "webkit3-2png1txt",
                "----WebKitFormBoundaryjdSFhcARk8fyGNy6",
                [
                    ("gtk-apply.png", "file1", "image/png", "file1.png"),
                    ("gtk-no.png", "file2", "image/png", "file2.png"),
                ],
                "this is another text with ümläüts",
            ),
            (
                "ie6-2png1txt",
                "---------------------------7d91b03a20128",
                [
                    ("file1.png", "file1", "image/x-png", "file1.png"),
                    ("file2.png", "file2", "image/x-png", "file2.png"),
                ],
                "ie6 sucks :-/",
            ),
        ]

        for name, boundary, files, text in repository:
            folder = join(resources, name)
            data = get_contents(join(folder, "request.http"))
            for filename, field, content_type, fsname in files:
                response = client.post(
                    f"/?object={field}",
                    data=data,
                    content_type=f'multipart/form-data; boundary="{boundary}"',
                    content_length=len(data),
                )
                lines = response.get_data().split(b"\n", 3)
                assert lines[0] == repr(filename).encode("ascii")
                assert lines[1] == repr(field).encode("ascii")
                assert lines[2] == repr(content_type).encode("ascii")
                assert lines[3] == get_contents(join(folder, fsname))
            response = client.post(
                "/?object=text",
                data=data,
                content_type=f'multipart/form-data; boundary="{boundary}"',
                content_length=len(data),
            )
            assert response.get_data() == repr(text).encode("utf-8")

    @pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning")
    def test_ie7_unc_path(self):
        client = Client(form_data_consumer)
        data_file = join(dirname(__file__), "multipart", "ie7_full_path_request.http")
        data = get_contents(data_file)
        boundary = "---------------------------7da36d1b4a0164"
        response = client.post(
            "/?object=cb_file_upload_multiple",
            data=data,
            content_type=f'multipart/form-data; boundary="{boundary}"',
            content_length=len(data),
        )
        lines = response.get_data().split(b"\n", 3)
        assert lines[0] == b"'Sellersburg Town Council Meeting 02-22-2010doc.doc'"

    def test_end_of_file(self):
        # This test looks innocent but it was actually timeing out in
        # the Werkzeug 0.5 release version (#394)
        data = (
            b"--foo\r\n"
            b'Content-Disposition: form-data; name="test"; filename="test.txt"\r\n'
            b"Content-Type: text/plain\r\n\r\n"
            b"file contents and no end"
        )
        data = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        assert not data.files
        assert not data.form

    def test_file_no_content_type(self):
        data = (
            b"--foo\r\n"
            b'Content-Disposition: form-data; name="test"; filename="test.txt"\r\n\r\n'
            b"file contents\r\n--foo--"
        )
        data = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        assert data.files["test"].filename == "test.txt"
        assert data.files["test"].read() == b"file contents"

    def test_extra_newline(self):
        # this test looks innocent but it was actually timeing out in
        # the Werkzeug 0.5 release version (#394)
        data = (
            b"\r\n\r\n--foo\r\n"
            b'Content-Disposition: form-data; name="foo"\r\n\r\n'
            b"a string\r\n"
            b"--foo--"
        )
        data = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        assert not data.files
        assert data.form["foo"] == "a string"

    def test_headers(self):
        data = (
            b"--foo\r\n"
            b'Content-Disposition: form-data; name="foo"; filename="foo.txt"\r\n'
            b"X-Custom-Header: blah\r\n"
            b"Content-Type: text/plain; charset=utf-8\r\n\r\n"
            b"file contents, just the contents\r\n"
            b"--foo--"
        )
        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        foo = req.files["foo"]
        assert foo.mimetype == "text/plain"
        assert foo.mimetype_params == {"charset": "utf-8"}
        assert foo.headers["content-type"] == foo.content_type
        assert foo.content_type == "text/plain; charset=utf-8"
        assert foo.headers["x-custom-header"] == "blah"

    @pytest.mark.parametrize("ending", [b"\n", b"\r", b"\r\n"])
    def test_nonstandard_line_endings(self, ending: bytes):
        data = ending.join(
            (
                b"--foo",
                b"Content-Disposition: form-data; name=foo",
                b"",
                b"this is just bar",
                b"--foo",
                b"Content-Disposition: form-data; name=bar",
                b"",
                b"blafasel",
                b"--foo--",
            )
        )
        req = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        assert req.form["foo"] == "this is just bar"
        assert req.form["bar"] == "blafasel"

    def test_failures(self):
        def parse_multipart(stream, boundary, content_length):
            parser = formparser.MultiPartParser(content_length)
            return parser.parse(stream, boundary, content_length)

        data = b"--foo\r\n\r\nHello World\r\n--foo--"
        pytest.raises(ValueError, parse_multipart, io.BytesIO(data), b"foo", len(data))

        data = (
            b"--foo\r\nContent-Disposition: form-field; name=foo\r\n\r\nHello World\r\n"
        )
        pytest.raises(ValueError, parse_multipart, io.BytesIO(data), b"foo", len(data))

    def test_empty_multipart(self):
        environ = {}
        data = b"--boundary--"
        environ["REQUEST_METHOD"] = "POST"
        environ["CONTENT_TYPE"] = "multipart/form-data; boundary=boundary"
        environ["CONTENT_LENGTH"] = str(len(data))
        environ["wsgi.input"] = io.BytesIO(data)
        stream, form, files = parse_form_data(environ, silent=False)
        rv = stream.read()
        assert rv == b""
        assert form == MultiDict()
        assert files == MultiDict()

class TestMultiPartParser:
    def test_constructor_not_pass_stream_factory_and_cls(self):
        parser = formparser.MultiPartParser()

        assert parser.stream_factory is formparser.default_stream_factory
        assert parser.cls is MultiDict

    def test_constructor_pass_stream_factory_and_cls(self):
        def stream_factory():
            pass

        parser = formparser.MultiPartParser(stream_factory=stream_factory, cls=dict)

        assert parser.stream_factory is stream_factory
        assert parser.cls is dict

    def test_file_rfc2231_filename_continuations(self):
        data = (
            b"--foo\r\n"
            b"Content-Type: text/plain; charset=utf-8\r\n"
            b"Content-Disposition: form-data; name=rfc2231;\r\n"
            b"	filename*0*=ascii''a%20b%20;\r\n"
            b"	filename*1*=c%20d%20;\r\n"
            b'	filename*2="e f.txt"\r\n\r\n'
            b"file contents\r\n--foo--"
        )
        request = Request.from_values(
            input_stream=io.BytesIO(data),
            content_length=len(data),
            content_type="multipart/form-data; boundary=foo",
            method="POST",
        )
        assert request.files["rfc2231"].filename == "a b c d e f.txt"
        assert request.files["rfc2231"].read() == b"file contents"


text:
Test session_set_save_handler() function: create_sid
--INI--
session.save_handler=files
session.name=PHPSESSID
--SKIPIF--
<?php include('skipif.inc'); ?>
--FILE--
<?php

ob_start();

echo "*** Testing session_set_save_handler() function: create_sid ***\n";

class MySession2 {
	public $path;

	public function open($path, $name) {
		if (!$path) {
			$path = sys_get_temp_dir();
		}
		$this->path = $path . '/u_sess_' . $name;
		return true;
	}

	public function close() {
		return true;
	}

	public function read($id) {
		return @file_get_contents($this->path . $id);
	}

	public function write($id, $data) {
		return file_put_contents($this->path . $id, $data);
	}

	public function destroy($id) {
		@unlink($this->path . $id);
	}

	public function gc($maxlifetime) {
		foreach (glob($this->path . '*') as $filename) {
			if (filemtime($filename) + $maxlifetime < time()) {
				@unlink($filename);
			}
		}
		return true;
	}

	public function create_sid() {
		return 'my_sid';
	}
}

$handler = new MySession2;
session_set_save_handler(array($handler, 'open'), array($handler, 'close'),
	array($handler, 'read'), array($handler, 'write'), array($handler, 'destroy'), array($handler, 'gc'), array($handler, 'create_sid'));
session_start();

$_SESSION['foo'] = "hello";

var_dump(session_id(), ini_get('session.save_handler'), $_SESSION);

session_write_close();
session_unset();

session_start();
var_dump($_SESSION);

session_write_close();
session_unset();

--EXPECTF--
*** Testing session_set_save_handler() function: create_sid ***
string(%d) "my_sid"
string(4) "user"
array(1) {
  ["foo"]=>
  string(5) "hello"
}
array(1) {
  ["foo"]=>
  string(5) "hello"
}


text:
//
//  ZZFlexibleLayoutViewModel.h
//  ZZFlexibleLayoutFrameworkDemo
//
//  Created by lbk on 2016/12/27.
//  Copyright © 2016年 lbk. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 * 仅框架内部使用
 *
 * 是对dataModel的一层封装
 * 实际给cell\view传递的仍然是dataModel
 */
@interface ZZFlexibleLayoutViewModel : NSObject

/// view/cell类名
@property (nonatomic, strong, readonly) NSString *className;
/// view/cell类
@property (nonatomic, assign) Class viewClass;

/// view/cell的数据Model
@property (nonatomic, strong) id dataModel;

/// view/cell的大小
@property (nonatomic, assign) CGSize viewSize;

@property (nonatomic, assign) NSInteger viewTag;

/// view/cell中的事件
@property (nonatomic, copy) id (^eventAction)(NSInteger actionType, id data);

/// 业务方指定的代理,默认nil
@property (nonatomic, copy) id delegate;

/// cell选中事件
@property (nonatomic, copy) void (^selectedAction)(id data);

/// cell配置事件
@property (nonatomic, copy) void (^configAction)(__kindof UIView *itemView, id dataModel);

/**
*  根据类名初始化viewModel
*/
- (instancetype)initWithViewClass:(Class)viewClass;

/**
 *  根据类名和数据源初始化viewModel
 */
- (instancetype)initWithViewClass:(Class)viewClass andDataModel:(id)dataModel;
- (instancetype)initWithViewClass:(Class)viewClass andDataModel:(id)dataModel viewTag:(NSInteger)viewTag;
- (instancetype)initWithViewClass:(Class)viewClass andDataModel:(id)dataModel viewSize:(CGSize)viewSize viewTag:(NSInteger)viewTag;

/**
 *  重新计算视图大小
 */
- (void)updateViewSize;

@end


text:
import atexit
import inspect

from lwr.core import LwrApp
from lwr.web.framework import RoutingApp

import lwr.web.routes

def app_factory(global_conf, **local_conf):
    """
    Returns the LWR WSGI application.
    """
    lwr_app = LwrApp(global_conf=global_conf, **local_conf)
    webapp = LwrWebApp(lwr_app=lwr_app)
    atexit.register(webapp.shutdown)
    return webapp

class LwrWebApp(RoutingApp):
    """
    Web application for LWR web server.
    """

    def __init__(self, lwr_app):
        super(LwrWebApp, self).__init__()
        self.lwr_app = lwr_app
        self.__setup_routes()

    def __setup_routes(self):
        for func_name, func in inspect.getmembers(lwr.web.routes, lambda x: getattr(x, '__controller__', False)):
            self.__add_route_for_function(func)

    def __add_route_for_function(self, function):
        route_suffix = '/%s' % function.__name__
        # Default or old-style route without explicit manager specified,
        # will be routed to manager '_default_'.
        default_manager_route = route_suffix
        self.add_route(default_manager_route, function)
        # Add route for named manager as well.
        named_manager_route = '/managers/{manager_name}%s' % route_suffix
        self.add_route(named_manager_route, function)

    def __getattr__(self, name):
        return getattr(self.lwr_app, name)


text:
package org.jetbrains.plugins.scala
package annotator

import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.lang.annotation.{Annotation, AnnotationHolder}
import com.intellij.psi.{PsiElement, PsiMethod, PsiNamedElement, PsiParameter}
import org.jetbrains.plugins.scala.annotator.createFromUsage._
import org.jetbrains.plugins.scala.annotator.importsTracker.ImportTracker
import org.jetbrains.plugins.scala.annotator.quickfix.ReportHighlightingErrorQuickFix
import org.jetbrains.plugins.scala.codeInspection.varCouldBeValInspection.ValToVarQuickFix
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil
import org.jetbrains.plugins.scala.lang.psi.api.base.patterns.{ScConstructorPattern, ScInfixPattern, ScPattern}
import org.jetbrains.plugins.scala.lang.psi.api.base.types.ScSimpleTypeElement
import org.jetbrains.plugins.scala.lang.psi.api.base.{ScReferenceElement, ScStableCodeReferenceElement}
import org.jetbrains.plugins.scala.lang.psi.api.expr._
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.{ScParameter, ScParameters}
import org.jetbrains.plugins.scala.lang.psi.api.statements.{ScFunction, ScValue}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScTypeDefinition
import org.jetbrains.plugins.scala.lang.psi.impl.expr.ScInterpolatedPrefixReference
import org.jetbrains.plugins.scala.lang.psi.impl.toplevel.synthetic.ScSyntheticFunction
import org.jetbrains.plugins.scala.lang.psi.types._
import org.jetbrains.plugins.scala.lang.psi.types.api.ScTypePresentation
import org.jetbrains.plugins.scala.lang.psi.types.nonvalue.Parameter
import org.jetbrains.plugins.scala.lang.psi.types.result.TypingContext
import org.jetbrains.plugins.scala.lang.resolve.ScalaResolveResult
import org.jetbrains.plugins.scala.project.ProjectContext

/**
 * Pavel.Fatin, 31.05.2010
 */
trait ApplicationAnnotator {
  def annotateReference(reference: ScReferenceElement, holder: AnnotationHolder) {
    for {result <- reference.multiResolve(false)
         r = result.asInstanceOf[ScalaResolveResult]} {

      ImportTracker.registerUsedImports(reference, r)

      if (r.isAssignment) {
        annotateAssignmentReference(reference, holder)
      }
      if (!r.isApplicable()) {
        r.element match {
          case f@(_: ScFunction | _: PsiMethod | _: ScSyntheticFunction) =>
            reference.getContext match {
              case genCall: ScGenericCall =>
                val missing = for (MissedTypeParameter(p) <- r.problems) yield p.name
                missing match {
                  case Seq() =>
                  case as =>
                    holder.createErrorAnnotation(genCall.typeArgs.getOrElse(genCall),
                      "Unspecified type parameters: " + as.mkString(", "))
                }
                r.problems.foreach {
                  case MissedTypeParameter(_) =>
                    // handled in bulk above
                  case DoesNotTakeTypeParameters =>
                    holder.createErrorAnnotation(genCall.typeArgs.getOrElse(genCall), f.name + " does not take type parameters")
                  case ExcessTypeArgument(arg) if inSameFile(arg, holder) =>
                    holder.createErrorAnnotation(arg, "Too many type arguments for " + f.name)
                  case DefaultTypeParameterMismatch(expected, actual) => genCall.typeArgs match {
                    case Some(typeArgs) =>
                      val message: String = ScalaBundle.message("type.mismatch.default.args.expected.actual", expected, actual)
                      holder.createErrorAnnotation(typeArgs, message)
                    case _ =>
                  }
                  case _ =>
                    //holder.createErrorAnnotation(call.argsElement, "Not applicable to " + signatureOf(f))
                }
              case call: MethodInvocation =>
                val missed =
                  for (MissedValueParameter(p) <- r.problems) yield p.name + ": " + p.paramType.presentableText

                if (missed.nonEmpty) {
                  holder.createErrorAnnotation(call.argsElement,
                    "Unspecified value parameters: " + missed.mkString(", "))
                  addCreateFromUsagesQuickFixes(reference, holder)
                }
                val (problems, fun) = call.applyOrUpdateElement match {
                  case Some(rr) =>
                    (rr.problems, rr.element)
                  case _ => (r.problems, f)
                }

                problems.foreach {
                  case DoesNotTakeParameters() =>
                    holder.createErrorAnnotation(call.argsElement, fun.name + " does not take parameters")
                    addCreateFromUsagesQuickFixes(reference, holder)
                  case ExcessArgument(argument) if inSameFile(argument, holder) =>
                    holder.createErrorAnnotation(argument, "Too many arguments for method " + nameOf(fun))
                    addCreateFromUsagesQuickFixes(reference, holder)
                  case TypeMismatch(expression, expectedType) if inSameFile(expression, holder) =>
                    for (t <- expression.getType(TypingContext.empty)) {
                      //TODO show parameter name
                      val (expectedText, actualText) = ScTypePresentation.different(expectedType, t)
                      val message = ScalaBundle.message("type.mismatch.expected.actual", expectedText, actualText)
                      val annotation = holder.createErrorAnnotation(expression, message)
                      annotation.registerFix(ReportHighlightingErrorQuickFix)
                      addCreateFromUsagesQuickFixes(reference, holder)
                    }
                  case MissedValueParameter(_) => // simultaneously handled above
                  case UnresolvedParameter(_) => // don't show function inapplicability, unresolved
                  case MalformedDefinition() =>
                    holder.createErrorAnnotation(call.getInvokedExpr, f.name + " has malformed definition")
                  case ExpansionForNonRepeatedParameter(expression) if inSameFile(expression, holder) =>
                    holder.createErrorAnnotation(expression, "Expansion for non-repeated parameter")
                  case PositionalAfterNamedArgument(argument) if inSameFile(argument, holder) =>
                    holder.createErrorAnnotation(argument, "Positional after named argument")
                  case ParameterSpecifiedMultipleTimes(assignment) if inSameFile(assignment, holder) =>
                    holder.createErrorAnnotation(assignment.getLExpression, "Parameter specified multiple times")
                  case WrongTypeParameterInferred => //todo: ?
                  case ExpectedTypeMismatch => //will be reported later
                  case ElementApplicabilityProblem(element, actual, expected) if inSameFile(element, holder) =>
                    val (actualType, expectedType) = ScTypePresentation.different(actual, expected)
                    holder.createErrorAnnotation(element, ScalaBundle.message("type.mismatch.found.required",
                      actualType, expectedType))
                  case _ =>
                    holder.createErrorAnnotation(call.argsElement, "Not applicable to " + signatureOf(f))
                }
              case _ =>
                r.problems.foreach {
                  case MissedParametersClause(_) if !reference.isInstanceOf[ScInterpolatedPrefixReference] =>
                    holder.createErrorAnnotation(reference, "Missing arguments for method " + nameOf(f))
                    addCreateFromUsagesQuickFixes(reference, holder)
                  case _ =>
                }
            }
          case _ =>
        }
      }
    }
  }

  /**
   * Annotates: val a = 1; a += 1;
   */
  private def annotateAssignmentReference(reference: ScReferenceElement, holder: AnnotationHolder) {
    val qualifier = reference.getContext match {
      case x: ScMethodCall => x.getEffectiveInvokedExpr match {
        case x: ScReferenceExpression => x.qualifier
        case _ => None
      }
      case x: ScInfixExpr => Some(x.lOp)
      case _ => None
    }
    val refElementOpt = qualifier.flatMap(_.asOptionOf[ScReferenceElement])
    val ref: Option[PsiElement] = refElementOpt.flatMap(_.resolve().toOption)
    val reassignment = ref.exists(ScalaPsiUtil.isReadonly)
    if (reassignment) {
      val annotation = holder.createErrorAnnotation(reference, "Reassignment to val")
      ref.get match {
        case named: PsiNamedElement if ScalaPsiUtil.nameContext(named).isInstanceOf[ScValue] =>
          annotation.registerFix(new ValToVarQuickFix(ScalaPsiUtil.nameContext(named).asInstanceOf[ScValue]))
        case _ =>
      }
    }
  }

  def annotateMethodInvocation(call: MethodInvocation, holder: AnnotationHolder) {
    implicit val ctx: ProjectContext = call

    //do we need to check it:
    call.getEffectiveInvokedExpr match {
      case ref: ScReferenceElement =>
        ref.bind() match {
          case Some(r) if r.notCheckedResolveResult || r.isDynamic => //it's unhandled case
          case _ =>
            call.applyOrUpdateElement match {
              case Some(r) if r.isDynamic => //it's still unhandled
              case _ => return //it's definetely handled case
            }
        }
      case _ => //unhandled case (only ref expressions was checked)
    }

    val problems = call.applyOrUpdateElement.map(_.problems).getOrElse(call.applicationProblems)
    val missed = for (MissedValueParameter(p) <- problems) yield p.name + ": " + p.paramType.presentableText

    if(missed.nonEmpty)
      holder.createErrorAnnotation(call.argsElement, "Unspecified value parameters: " + missed.mkString(", "))

    //todo: better error explanation?
    //todo: duplicate
    problems.foreach {
      case DoesNotTakeParameters() =>
        val annotation = holder.createErrorAnnotation(call.argsElement, "Application does not take parameters")
        (call, call.getInvokedExpr) match {
          case (c: ScMethodCall, InstanceOfClass(td: ScTypeDefinition)) =>
            annotation.registerFix(new CreateApplyQuickFix(td, c))
          case _ =>
        }
      case ExcessArgument(argument) =>
        holder.createErrorAnnotation(argument, "Too many arguments")
      case TypeMismatch(expression, expectedType) =>
        for(t <- expression.getType(TypingContext.empty)) {
          //TODO show parameter name
          val (expectedText, actualText) = ScTypePresentation.different(expectedType, t)
          val message = ScalaBundle.message("type.mismatch.expected.actual", expectedText, actualText)
          val annotation = holder.createErrorAnnotation(expression, message)
          annotation.registerFix(ReportHighlightingErrorQuickFix)
        }
      case MissedValueParameter(_) => // simultaneously handled above
      case UnresolvedParameter(_) => // don't show function inapplicability, unresolved
      case MalformedDefinition() =>
        holder.createErrorAnnotation(call.getInvokedExpr, "Application has malformed definition")
      case ExpansionForNonRepeatedParameter(expression) =>
        holder.createErrorAnnotation(expression, "Expansion for non-repeated parameter")
      case PositionalAfterNamedArgument(argument) =>
        holder.createErrorAnnotation(argument, "Positional after named argument")
      case ParameterSpecifiedMultipleTimes(assignment) =>
        holder.createErrorAnnotation(assignment.getLExpression, "Parameter specified multiple times")
      case ExpectedTypeMismatch => // it will be reported later
      case DefaultTypeParameterMismatch(_, _) => //it will be reported later
      case _ => holder.createErrorAnnotation(call.argsElement, "Not applicable")
    }
  }

  protected def registerCreateFromUsageFixesFor(ref: ScReferenceElement, annotation: Annotation) {
    ref match {
      case (exp: ScReferenceExpression) childOf (_: ScMethodCall) =>
        annotation.registerFix(new CreateMethodQuickFix(exp))
        if (ref.refName.headOption.exists(_.isUpper))
          annotation.registerFix(new CreateCaseClassQuickFix(exp))
      case (exp: ScReferenceExpression) childOf (infix: ScInfixExpr) if infix.operation == exp =>
        annotation.registerFix(new CreateMethodQuickFix(exp))
      case (exp: ScReferenceExpression) childOf ((_: ScGenericCall) childOf (_: ScMethodCall)) =>
        annotation.registerFix(new CreateMethodQuickFix(exp))
      case (exp: ScReferenceExpression) childOf (_: ScGenericCall) =>
        annotation.registerFix(new CreateParameterlessMethodQuickFix(exp))
      case exp: ScReferenceExpression =>
        annotation.registerFix(new CreateParameterlessMethodQuickFix(exp))
        annotation.registerFix(new CreateValueQuickFix(exp))
        annotation.registerFix(new CreateVariableQuickFix(exp))
        annotation.registerFix(new CreateObjectQuickFix(exp))
      case (_: ScStableCodeReferenceElement) childOf (st: ScSimpleTypeElement) if st.singleton =>
      case (stRef: ScStableCodeReferenceElement) childOf (Both(p: ScPattern, (_: ScConstructorPattern | _: ScInfixPattern))) =>
        annotation.registerFix(new CreateCaseClassQuickFix(stRef))
        annotation.registerFix(new CreateExtractorObjectQuickFix(stRef, p))
      case stRef: ScStableCodeReferenceElement =>
        annotation.registerFix(new CreateTraitQuickFix(stRef))
        annotation.registerFix(new CreateClassQuickFix(stRef))
        annotation.registerFix(new CreateCaseClassQuickFix(stRef))
      case _ =>
    }
  }

  private def nameOf(f: PsiNamedElement) = f.name + signatureOf(f)

  private def signatureOf(f: PsiNamedElement): String = f match {
    case f: ScFunction =>
      if (f.parameters.isEmpty) "" else formatParamClauses(f.paramClauses)
    case m: PsiMethod =>
      val params = m.parameters
      if (params.isEmpty) "" else formatJavaParams(params)
    case syn: ScSyntheticFunction =>
      if (syn.paramClauses.isEmpty) "" else syn.paramClauses.map(formatSyntheticParams).mkString
  }

  private def formatParamClauses(paramClauses: ScParameters) = {
    def formatParams(parameters: Seq[ScParameter], types: Seq[ScType]) = {
      val parts = parameters.zip(types).map {
        case (p, t) => t.presentableText + (if(p.isRepeatedParameter) "*" else "")
      }
      parenthesise(parts)
    }
    paramClauses.clauses.map(clause => formatParams(clause.parameters, clause.paramTypes)).mkString
  }

  private def formatJavaParams(parameters: Seq[PsiParameter]): String = {
    val types = ScalaPsiUtil.mapToLazyTypesSeq(parameters)
    val parts = parameters.zip(types).map {
      case (p, t) => t().presentableText + (if(p.isVarArgs) "*" else "")
    }
    parenthesise(parts)
  }

  private def formatSyntheticParams(parameters: Seq[Parameter]) = {
    val parts = parameters.map {
      p => p.paramType.presentableText + (if (p.isRepeated) "*" else "")
    }
    parenthesise(parts)
  }

  private def parenthesise(items: Seq[_]) = items.mkString("(", ", ", ")")

  private def addCreateFromUsagesQuickFixes(ref: ScReferenceElement, holder: AnnotationHolder) = {
    val annotation = holder.createErrorAnnotation(ref, ScalaBundle.message("cannot.resolve.such.signature", ref.refName))
    annotation.setHighlightType(ProblemHighlightType.INFORMATION)
    registerCreateFromUsageFixesFor(ref, annotation)
  }

  private def inSameFile(elem: PsiElement, holder: AnnotationHolder): Boolean = {
    elem != null && elem.getContainingFile == holder.getCurrentAnnotationSession.getFile
  }
}


text:
@import url(http://extjs.cachefly.net/ext-3.3.1/resources/css/ext-all.css);

@import url(sphinxdoc.css);

/* override some of ext-all.css */
ul, ol {
    margin: 14px 0;
    padding-left: 40px;
}
ul {
    list-style: disc;
}
ol {
    list-style-type:decimal;
}
strong {
    font-weight: bolder;
}

/* override some of sphinxdoc.css */
html {
    margin: 0;
    padding: 0;
}
body {
    border: none;
    background-color: white;
    margin: 0;
    padding: 0;
    min-width: 900px;
}
h1, h2, h3, h4, h5, h6 {
    color: #385F95;
}
table td, table th {
    padding: 0;
}
div.related {
    margin: 0 80px;
    width: auto;
}
div.related ul {
    border: 1px solid #EEEEEE;
}
div.bodywrapper {
    border-right: 0;
}
a.reference em {
    font-style: normal;
}
div.sphinxsidebar {
    padding-right: 95px;
}
div.sphinxsidebar h3, div.sphinxsidebar h4 {
    background: inherit;
    border: none;
    color: #385F95;
    padding: 0;
}
div.sphinxsidebar h3 a {
    color: inherit;
}
div.document {
    margin: 0 80px;
}
div.documentwrapper {
    width: auto;
    border-left: 1px solid #EEEEEE;
    border-right: 1px solid #EEEEEE;
}
div.footer {
    background: #4E7AB2 url(img/footer-bg.png) repeat-x;
    color: #d9d9d9;
    padding: 60px 0 35px;
    text-align: center;
}

/* custom header */
div.header {
    position: relative;
    overflow: hidden;
    height: 120px;
    background: #97b7e1 url(img/header-bg.png) 0 0 repeat-x;
}
div.header div.wrap {
    margin: 0 80px;
}
#logo {
    padding: 0;
}
#logo a {
    float: left;
    width: 300px;
    height: 120px;
    overflow: hidden;
    text-indent: -9999em;
    background: url(img/geoext-logo.png) no-repeat;
}
#top-nav {
    position: absolute;
    bottom: 22px;
    right: 90px;
    list-style: none;
    margin: 0;
}

#top-nav li {
    display: inline;
    margin: 0;
    padding: 0 8px;
    border-left: 1px solid #fff;
}

#top-nav li:first-child, #top-nav li.first {
    border-left: 0;
}

#top-nav li a {
    color: #fff;
    font-weight: bold;
    text-decoration: none;
    font-family: "Lucida Sans", "Lucida Sans Unicode", "Lucida Grande", Verdana, Arial, Helvetica, sans-serif;
}

#top-nav li a:hover {
    color: #e0e0e0;
}

/* search box style */
#searchbox {
    position: absolute;
    bottom: 70px;
    right: 95px;
    background: transparent url(img/search-box.png) top left no-repeat;
    height: 28px;
    width: 190px;
}
#searchbox-query {
    color: #72a629;
    font-size: 0.92em;
    border: 0;
    background: transparent;
    width: 175px;
    margin: 5px 0 0 8px;
}
#searchbox-submit {
    position: absolute;
    top: 6px;
    right: 5px;
}
a.headerlink {
    display: none;
}

/* meta-info about a class/module get pulled out */
.meta {
    float: right;
    padding: 0 2em;
    background-color: white;
}
.meta ul {
    list-style-type: none;
    padding: 0;
}

/* overriding clear: both on dl */
dl.class {
    clear: left;
}

/* don't display class names for attributes or methods*/
.attribute .descclassname {
    display: none;
}
.method .descclassname {
    display: none;
}
.classmethod .descclassname, .classmethod .property {
    display: none;
}

/* headers with bottom border get some padding */
h2, h3, h4 {
    padding-bottom: 4px;
}

/* making code samples less gigantic */
pre {
    font-size: 0.8em;
}

/* blog entry style */
ul.rss_items li.rss_item {
    padding-bottom: 0.5em;
}

/* execute button style */
.x-btn.execute {
    margin: 1em;
}

.exampleblock {
    width: 225px;
    margin: 5px;
    height: 110px;
    overflow: auto;
}
.exampleblock h2 {
    margin-top: 0;
    font-size: 1em;
}
a.examplelink {
    margin: 5px;
    text-decoration: none !important;
    float: left;
    display: block;
    border: 1px solid #FFFFFF;
}
a.examplelink:hover {
    border: 1px solid #E5EDD3;
    background-color: #F5FDE3
}

/* builder page style */
div.builder-form {
    margin-top: 1em;
}
.module-desc {
    padding: 0 0 5px;
    font-size: 12px;
}
.component label {
    font-family: "Lucida Console", "Courier New", Courier, monospace;
    font-size: 11px;
}

div.download-button {
    margin: 0 1em 2em;
}
div.download-button>table {
    float: right;
}

.x-btn .download {
    background-image: url(img/disk.png);
}

p.credit {
    font-size: smaller;
    color: #666666;
}


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

package org.chromium.content_public.browser.test;

import android.os.Handler;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.test.util.LooperUtils;

import java.lang.reflect.InvocationTargetException;

/**
 * Handles processing messages in nested run loops.
 *
 * Android does not support nested run loops by default. While running
 * in nested mode, we use reflection to retreive messages from the MessageQueue
 * and dispatch them.
 */
@JNINamespace("content")
public class NestedSystemMessageHandler {
    private static final int QUIT_MESSAGE = 10;
    private static final Handler sHandler = new Handler();

    private NestedSystemMessageHandler() {}

    /**
     * Dispatches the first message from the current MessageQueue, blocking
     * until a task becomes available if the queue is empty. Callbacks for
     * other event handlers registered to the thread's looper (e.g.,
     * MessagePumpAndroid) may also be processed as a side-effect.
     *
     * Returns true if task dispatching succeeded, or false if an exception was
     * thrown.
     */
    @SuppressWarnings("unused")
    @CalledByNative
    private static boolean dispatchOneMessage() {
        try {
            LooperUtils.runSingleNestedLooperTask();
        } catch (IllegalArgumentException | IllegalAccessException | SecurityException
                | InvocationTargetException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /*
     * Causes a previous call to dispatchOneMessage() to stop blocking and
     * return.
     */
    @SuppressWarnings("unused")
    @CalledByNative
    private static void postQuitMessage() {
        // Causes MessageQueue.next() to return in case it was blocking waiting
        // for more messages.
        sHandler.sendMessage(sHandler.obtainMessage(QUIT_MESSAGE));
    }
}


text:
package com.hits.modules.sys.bean;

import java.util.List;

import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Many;
import org.nutz.dao.entity.annotation.Name;
import org.nutz.dao.entity.annotation.Table;

/**
 * @author Wizzer.cn
 * @time   2012-9-13 上午10:54:04
 *
 */
@Table("sys_unit")
public class Sys_unit
{
	@Column
	@Name
	private String id;
	@Column
	private String unittype;
	@Column
	private String name;
	@Column
	private String namespell;
	@Column
	private String unitcode;
	@Column
	private String descript;
	@Column
	private String address;
	@Column
	private String telephone;
	@Column
	private String email;
	@Column
	private String website;
	@Column
	private String handler;
	@Column
	private String handlerphone;
	@Column
	private String leader;
	@Column
	private String leadphone;
	@Column
	private int location;
	@Column
	private String xy_type;
	@Column
	private String sjdw;
	@Column
	private String xzqh;
	@Many(target = Sys_user.class, field = "unitid")//一个单位下有N个用户
	private List<Sys_user> users;

	public String getId()
	{
		return id;
	}
	public void setId(String id)
	{
		this.id=id;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name=name;
	}
	public String getUnitcode()
	{
		return unitcode;
	}
	public void setUnitcode(String unitcode)
	{
		this.unitcode=unitcode;
	}
	public String getDescript()
	{
		return descript;
	}
	public void setDescript(String descript)
	{
		this.descript=descript;
	}
	public String getAddress()
	{
		return address;
	}
	public void setAddress(String address)
	{
		this.address=address;
	}
	public String getTelephone()
	{
		return telephone;
	}
	public void setTelephone(String telephone)
	{
		this.telephone=telephone;
	}
	public String getEmail()
	{
		return email;
	}
	public void setEmail(String email)
	{
		this.email=email;
	}
	public String getWebsite()
	{
		return website;
	}
	public void setWebsite(String website)
	{
		this.website=website;
	}
	public int getLocation()
	{
		return location;
	}
	public void setLocation(int location)
	{
		this.location=location;
	}
	public String getUnittype() {
		return unittype;
	}
	public void setUnittype(String unittype) {
		this.unittype = unittype;
	}
	public String getNamespell() {
		return namespell;
	}
	public void setNamespell(String namespell) {
		this.namespell = namespell;
	}
	public String getHandler() {
		return handler;
	}
	public void setHandler(String handler) {
		this.handler = handler;
	}
	public String getHandlerphone() {
		return handlerphone;
	}
	public void setHandlerphone(String handlerphone) {
		this.handlerphone = handlerphone;
	}
	public String getLeader() {
		return leader;
	}
	public void setLeader(String leader) {
		this.leader = leader;
	}
	public String getLeadphone() {
		return leadphone;
	}
	public void setLeadphone(String leadphone) {
		this.leadphone = leadphone;
	}
	public List<Sys_user> getUsers() {
		return users;
	}
	public void setUsers(List<Sys_user> users) {
		this.users = users;
	}

	public String getXy_type() {
		return xy_type;
	}

	public void setXy_type(String xy_type) {
		this.xy_type = xy_type;
	}

	public String getSjdw() {
		return sjdw;
	}

	public void setSjdw(String sjdw) {
		this.sjdw = sjdw;
	}
	public String getXzqh() {
		return xzqh;
	}
	public void setXzqh(String xzqh) {
		this.xzqh = xzqh;
	}
}