text:
#include "SkOperand2.h"
#include "SkStream.h"
#include "SkTDArray.h"
#include "SkTDArray_Experimental.h"
#include "SkTDict.h"
#include "SkTDStack.h"

typedef SkLongArray(SkString*) SkTDStringArray;

class SkAnimateMaker;
class SkScriptCallBack;

class SkScriptEngine2 {
public:
	enum Error {
		kNoError,
		kArrayIndexOutOfBounds,
		kCouldNotFindReferencedID,
		kFunctionCallFailed,
		kMemberOpFailed,
		kPropertyOpFailed
	};

	enum Attrs {
		kConstant,
		kVariable
	};

	SkScriptEngine2(SkOperand2::OpType returnType);
	~SkScriptEngine2();
	bool convertTo(SkOperand2::OpType , SkScriptValue2* );
	bool evaluateScript(const char** script, SkScriptValue2* value);
	void forget(SkOpArray* array);
	Error getError() { return fError; }
	SkOperand2::OpType getReturnType() { return fReturnType; }
	void track(SkOpArray* array) {
		SkASSERT(fTrackArray.find(array) < 0);
		*fTrackArray.append() = array; }
	void track(SkString* string) {
		SkASSERT(fTrackString.find(string) < 0);
		*fTrackString.append() = string;
	}
	static bool ConvertTo(SkScriptEngine2* , SkOperand2::OpType toType, SkScriptValue2* value);
	static SkScalar IntToScalar(int32_t );
	static bool ValueToString(const SkScriptValue2& value, SkString* string);

	enum Op {		// used by tokenizer attribute table
		kUnassigned,
		kAdd,
		kBitAnd,
		kBitNot,
		kBitOr,
		kDivide,
		kEqual,
		kFlipOps,
		kGreaterEqual,
		kLogicalAnd,
		kLogicalNot,
		kLogicalOr,
		kMinus,
		kModulo,
		kMultiply,
		kShiftLeft,
		kShiftRight,	// signed
		kSubtract,
		kXor,
// following not in attribute table
		kArrayOp,
		kElse,
		kIf,
		kParen,
		kLastLogicalOp,
		kArtificialOp = 0x20
	};

	enum TypeOp {	// generated by tokenizer
		kNop, // should never get generated
		kAccumulatorPop,
		kAccumulatorPush,
		kAddInt,
		kAddScalar,
		kAddString,	// string concat
		kArrayIndex,
		kArrayParam,
		kArrayToken,
		kBitAndInt,
		kBitNotInt,
		kBitOrInt,
		kBoxToken,
		kCallback,
		kDivideInt,
		kDivideScalar,
		kDotOperator,
		kElseOp,
		kEnd,
		kEqualInt,
		kEqualScalar,
		kEqualString,
		kFunctionCall,
		kFlipOpsOp,
		kFunctionToken,
		kGreaterEqualInt,
		kGreaterEqualScalar,
		kGreaterEqualString,
		kIfOp,
		kIntToScalar,
		kIntToScalar2,
		kIntToString,
		kIntToString2,
		kIntegerAccumulator,
		kIntegerOperand,
		kLogicalAndInt,
		kLogicalNotInt,
		kLogicalOrInt,
		kMemberOp,
		kMinusInt,
		kMinusScalar,
		kModuloInt,
		kModuloScalar,
		kMultiplyInt,
		kMultiplyScalar,
		kPropertyOp,
		kScalarAccumulator,
		kScalarOperand,
		kScalarToInt,
		kScalarToInt2,
		kScalarToString,
		kScalarToString2,
		kShiftLeftInt,
		kShiftRightInt,	// signed
		kStringAccumulator,
		kStringOperand,
		kStringToInt,
		kStringToScalar,
		kStringToScalar2,
		kStringTrack,
		kSubtractInt,
		kSubtractScalar,
		kToBool,
		kUnboxToken,
		kUnboxToken2,
		kXorInt,
		kLastTypeOp
	};

	enum OpBias {
		kNoBias,
		kTowardsNumber = 0,
		kTowardsString
	};

protected:

	enum BraceStyle {
	//	kStructBrace,
		kArrayBrace,
		kFunctionBrace
	};

	enum AddTokenRegister {
		kAccumulator,
		kOperand
	};

	enum ResultIsBoolean {
		kResultIsNotBoolean,
		kResultIsBoolean
	};

	struct OperatorAttributes {
		unsigned int fLeftType : 3;	// SkOpType union, but only lower values
		unsigned int fRightType : 3;	 // SkOpType union, but only lower values
		OpBias fBias : 1;
		ResultIsBoolean fResultIsBoolean : 1;
	};

	struct Branch {
		Branch() {
		}

		Branch(Op op, int depth, unsigned offset) : fOffset(offset), fOpStackDepth(depth), fOperator(op),
			fPrimed(kIsNotPrimed), fDone(kIsNotDone) {
		}

		enum Primed {
			kIsNotPrimed,
			kIsPrimed
		};

		enum Done {
			kIsNotDone,
			kIsDone,
		};

		unsigned fOffset : 16; // offset in generated stream where branch needs to go
		int fOpStackDepth : 7; // depth when operator was found
		Op fOperator : 6; // operand which generated branch
		mutable Primed fPrimed : 1;	// mark when next instruction generates branch
		Done fDone : 1;	// mark when branch is complete
		void prime() { fPrimed = kIsPrimed; }
		void resolve(SkDynamicMemoryWStream* , size_t offset);
	};

	static const OperatorAttributes gOpAttributes[];
	static const signed char gPrecedence[];
	static const TypeOp gTokens[];
	void addToken(TypeOp );
	void addTokenConst(SkScriptValue2* , AddTokenRegister , SkOperand2::OpType , TypeOp );
	void addTokenInt(int );
	void addTokenScalar(SkScalar );
	void addTokenString(const SkString& );
	void addTokenValue(const SkScriptValue2& , AddTokenRegister );
	int arithmeticOp(char ch, char nextChar, bool lastPush);
	bool convertParams(SkTDArray<SkScriptValue2>* ,
		const SkOperand2::OpType* paramTypes, int paramTypeCount);
	void convertToString(SkOperand2* operand, SkOperand2::OpType type) {
		SkScriptValue2 scriptValue;
		scriptValue.fOperand = *operand;
		scriptValue.fType = type;
		convertTo(SkOperand2::kString, &scriptValue);
		*operand = scriptValue.fOperand;
	}
	bool evaluateDot(const char*& script);
	bool evaluateDotParam(const char*& script, const char* field, size_t fieldLength);
	bool functionParams(const char** scriptPtr, SkTDArray<SkScriptValue2>* params);
	size_t getTokenOffset();
	SkOperand2::OpType getUnboxType(SkOperand2 scriptValue);
	bool handleArrayIndexer(const char** scriptPtr);
	bool handleFunction(const char** scriptPtr);
	bool handleMember(const char* field, size_t len, void* object);
	bool handleMemberFunction(const char* field, size_t len, void* object,
		SkTDArray<SkScriptValue2>* params);
	bool handleProperty();
	bool handleUnbox(SkScriptValue2* scriptValue);
	bool innerScript(const char** scriptPtr, SkScriptValue2* value);
	int logicalOp(char ch, char nextChar);
	void processLogicalOp(Op op);
	bool processOp();
	void resolveBranch(Branch& );
//	void setAnimateMaker(SkAnimateMaker* maker) { fMaker = maker; }
	SkDynamicMemoryWStream fStream;
	SkDynamicMemoryWStream* fActiveStream;
	SkTDStack<BraceStyle> fBraceStack;		// curly, square, function paren
	SkTDStack<Branch> fBranchStack;  // logical operators, slot to store forward branch
	SkLongArray(SkScriptCallBack*) fCallBackArray;
	SkTDStack<Op> fOpStack;
	SkTDStack<SkScriptValue2> fValueStack;
//	SkAnimateMaker* fMaker;
	SkLongArray(SkOpArray*) fTrackArray;
	SkTDStringArray fTrackString;
	const char* fToken; // one-deep stack
	size_t fTokenLength;
	SkOperand2::OpType fReturnType;
	Error fError;
	SkOperand2::OpType fAccumulatorType;	// tracking for code generation
	SkBool fBranchPopAllowed;
	SkBool fConstExpression;
	SkBool fOperandInUse;
private:
#ifdef SK_DEBUG
public:
	void decompile(const unsigned char* , size_t );
	static void UnitTest();
	static void ValidateDecompileTable();
#endif
};

#ifdef SK_DEBUG

struct SkScriptNAnswer2 {
	const char* fScript;
	SkOperand2::OpType fType;
	int32_t fIntAnswer;
	SkScalar fScalarAnswer;
	const char* fStringAnswer;
};

#endif

#endif // SkScript2_DEFINED


text:
MuSprint-client module hosts the frontend server components using React.js. The response from these modules can be consumed by a web client.

# Deployment Instructions
You can deploy the frontend server independently using docker container.

## 1 Docker Deployment

**Note:** Make sure you have [docker](https://docs.docker.com/get-docker/) installed.
~~~~
$ docker -v
Docker version 19.03.13, build 4484c46d9d
~~~~

### 1.1 Build Client docker image
  Change directory to `client` and build image:
  ~~~~
  $ cd <>/json-in-db/MuSprint/client
  $ docker build -t musprint-client:1.0.0 .
  ~~~~

### 1.2 Run Client app
  ~~~~
  $ docker run -it \
               -p 3000:3000 \
               musprint-client:1.0.0
  ~~~~
  This will start a listener on port 3000.
  Note:
  * If you wish to deploy the backend server (Step 3.1) on a machinie that you would like to access using its IP address, set the environment variable **`REACT_APP_MUSTORIES_SERVICE_URL`** while running the client app. For example:
  ~~~~
  $ docker run -it \
               -p 3000:3000 \
               --env REACT_APP_MUSTORIES_SERVICE_URL=http://<your_ip_address>:5000/stories/ \
               musprint-client:1.0.0
  ~~~~

The application is ready to view on a browser:  http://localhost:3000/

redpajama_set_name: RedPajamaGithub


text:
`warded [command] [options]`

### Options

- `--ward {wardName}`
	- Select a ward to operate on
	- Defaults to `default` if not supplied

### Commands

- `edit <passName>`
	- Edit/create a passphrase using `$EDITOR`

- `generate <passLength> [<passName>]`
	- Generates a new passphrase
	- If `passName` already exists, only the first line will be replaced
	- If `passName` isn't provided, then a passphrase will be generated and printed to stdout

- `ls`, `list`
	- List passphrases in a ward

- `rekey`
	- Replaces the existing master key and a new master key
	- This operation will create a new temporary ward to ensure that the existing ward is not left in an inconsistent state in the case of failure/interruption

- `show <passName>`
	- Prints the given passphrase


text:
'use strict';

var Parser = /** @type Parser */ require('./parser/parser');

var parser = new Parser();

/**
 * @class Tools
 * @extends Parser
 * @param {String} ruleString
 * */
function Tools(ruleString) {

    /**
     * @protected
     * @memberOf {Tools}
     * @property
     * @type {String}
     * */
    this._ruleString = ruleString;

    /**
     * @protected
     * @memberOf {Tools}
     * @property
     * @type {RulePath}
     * */
    this._pathRule = this._compilePathRule();
}

Tools.prototype.constructor = Tools;

/**
 * @public
 * @memberOf {Tools}
 * @method
 *
 * @param {Function} func
 *
 * @returns {Tools}
 * */
Tools.prototype.inspect = function (func) {
    Tools.inspectRule(this._pathRule, func, this);
    return this;
};

/**
 * @public
 * @memberOf {Tools}
 * @method
 *
 * @param {Function} func
 * @param {*} accum
 *
 * @returns {String}
 * */
Tools.prototype.reduce = function (func, accum) {
    this.inspect(function (rule, stackPop, depth) {
        accum = func.call(this, accum, rule, stackPop, depth);
    });

    return accum;
};

/**
 * @public
 * @memberOf {Tools}
 * @method
 *
 * @returns {String}
 * */
Tools.prototype.toString = function () {
    return this._ruleString;
};

/**
 * @protected
 * @memberOf {Tools}
 * @method
 *
 * @returns {RulePath}
 * */
Tools.prototype._compilePathRule = function () {
    return parser.parse(this._ruleString);
};

/**
 * @public
 * @static
 * @memberOf {Tools}
 * @method
 *
 * @param {Object} rule
 * @param {Function} func
 * @param {*} [thisp]
 * */
Tools.inspectRule = function (rule, func, thisp) {
    var index = 0;
    var parts = [rule];
    var stack = [];
    var depth = stack.length;
    var count = parts.length;
    var state;

    do {
        if (count === index) {
            // do not check if depth === 0, coz 0 depth always have child nodes
            state = stack.pop();
            depth = stack.length;
            parts = state.parts;
            index = state.index;
            count = parts.length;
            func.call(thisp, parts[index], true, depth);
            index += 1;

            continue;
        }

        rule = parts[index];

        func.call(thisp, rule, false, depth);

        if (rule.parts) {
            depth = stack.push(new State(parts, index));
            parts = rule.parts;
            index = 0;
            count = parts.length;

            continue;
        }

        index += 1;
    } while (depth > 0);
};

function State(parts, index) {
    this.parts = parts;
    this.index = index;
}

module.exports = Tools;


text:
package eu.jpereira.trainings.designpatterns.creational.singleton.crwaling;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * This class is used only to simulate a long call without using thread.sleep.
 * It will open a connection to a set of sites and dump the contents
 *
 * @author Joao Pereira
 *
 */
public class DummySiteCrawler implements SiteCrawler{

	private Map<String, StringBuffer> urlContents;

	public DummySiteCrawler() {
		this.urlContents = createNewSiteContens();
	}

	public DummySiteCrawler withURL(String url) {
		this.urlContents.put(url, new StringBuffer());
		return this;
	}

	private void crawl(String urlString, StringBuffer targetBuffer) throws CannotCrawlException{
		try {
			URL url = new URL(urlString);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				targetBuffer.append(line);
			}
			reader.close();

		} catch (Exception e) {
			throw new CannotCrawlException(e);

		}

	}

	public SiteCrawler crawl() throws CannotCrawlException {
		for (String url : this.urlContents.keySet()) {
			crawl(url, this.urlContents.get(url));
		}
		return this;
	}

	/* (non-Javadoc)
	 * @see eu.jpereira.trainings.designpatterns.creational.singleton.SiteCrawler#getSiteContents()
	 */
	@Override
	public Map<String, StringBuffer> packSiteContens() {
		//return the reference and reuit for other instance
		Map<String, StringBuffer> retunrContents = this.urlContents;
		this.urlContents = createNewSiteContens();
		return retunrContents;
	}

	/**
	 * can override
	 * @return
	 */
	protected Map<String, StringBuffer> createNewSiteContens() {

		return new HashMap<String, StringBuffer>();
	}
}


text:
King Arthur and his knights are having a New Years party. Last year Lancelot was jealous of Arthur, because Arthur had a date and Lancelot did not, and they started a duel.

To prevent this from happening again, Arthur wants to make sure that there are at least as many women as men at this year's party. He gave you a list of integers of all the party goers.

Arthur needs you to return true if he needs to invite more women or false if he is all set.
## Input/Output

* [input] integer array L ($a in PHP)

An array (guaranteed non-associative in PHP) representing the genders of the attendees, where -1 represents women and 1 represents men.

2 <= L.length <= 50

* [output] a boolean value

true if Arthur need to invite more women, false otherwise.
```python
def invite_more_women(arr):
    return False if sum(arr) <= 0 else True
```
```python
def invite_more_women(arr):
    return sum(arr) > 0
```


text:
'use strict';

import { expect } from 'chai';
import * as inputchecker from '../../../../../src/lib/device/validation/inputMacroChecker';

describe('./lib/device/validation/inputMacroChecker.ts', () => {
  it('should throw error when parameter is not of type Array', () => {
    // @ts-ignore
    expect(() => inputchecker.hasNoInputButtonsDefined('foo')).to.throw(/NOT_ARRAY_PARAMETER/);
  });

  it('empty array returns missing input buttons', () => {
    const result = inputchecker.hasNoInputButtonsDefined([]);
    expect(result).to.equal(true);
  });

  it('random strings returns missing input buttons', () => {
    const result = inputchecker.hasNoInputButtonsDefined([
      { param: { name: 'FOO' } },
      { param: { name: 'INTHEBAR' } },
    ]);
    expect(result).to.equal(true);
  });

  it('should find input command', () => {
    const result = inputchecker.hasNoInputButtonsDefined([
      { param: { name: 'FOO' } },
      { param: { name: 'INPUT HDMI 1' } },
    ]);
    expect(result).to.equal(false);
  });

  it('should not ignore empty parameter', () => {
    // @ts-ignore
    const result = inputchecker.hasNoInputButtonsDefined([
      { param: {} },
      { foo: { bar: 'INPUT HDMI 1' } },
    ]);
    expect(result).to.equal(true);
  });
});


text:
package com.ketayao.fensy.mvc;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ketayao.fensy.exception.ActionException;
import com.ketayao.fensy.util.CryptUtils;
import com.ketayao.fensy.util.ResourceUtils;
import com.ketayao.fensy.webutil.Multimedia;
import com.ketayao.fensy.webutil.RequestUtils;

/**
 * 请求上下文
 *
 * @date 2010-1-13 下午04:18:00
 */
public class WebContext {
	private final static Logger log = LoggerFactory.getLogger(WebContext.class);

	private final static String UTF_8 = "UTF-8";

	private static int maxSize = 10 * 1024 * 1024;
	private final static String TEMP_UPLOAD_FILE = "$TEMP_UPLOAD_FILE$";

	private final static ThreadLocal<WebContext> CONTEXTS = new ThreadLocal<WebContext>();

	private ServletContext context;
	private HttpSession session;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private Locale locale;
	private Map<String, Cookie> cookies;

	public final static byte[] E_KEY = new byte[] { '1', '2', '3', '4', '5', '6', '7', '8' };

	public final static String LOCALE = "___locale";
	public final static int MAX_AGE = 86400 * 365; // 默认一年时间

	public final static String COOKIE_LOGIN = "___login";

	public final static String REQUEST_LOCALE_PARAM = "request_locale";

	static {
		// BeanUtils对时间转换的初始化设置
		ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class);
		ConvertUtils.register(new Converter() {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
			SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-M-d H:m");

			@SuppressWarnings("rawtypes")
			public Object convert(Class type, Object value) {
				if (value == null)
					return null;
				if (value instanceof Date)
					return (value);
				try {
					return sdfTime.parse(value.toString());
				} catch (ParseException e) {
					try {
						return sdf.parse(value.toString());
					} catch (ParseException e1) {
						return null;
					}
				}
			}
		}, java.util.Date.class);
	}

	/**
	 * 初始化请求上下文,默认转码为UTF8
	 *
	 * @param ctx
	 * @param req
	 * @param res
	 */
	public static WebContext begin(ServletContext servletContext,
			HttpServletRequest request, HttpServletResponse response) {
		WebContext wc = new WebContext();

		wc.context = servletContext;
		wc.request = autoUploadRequest(encodeRequest(request));// 是否是上传请求
		wc.response = response;

		// 保存request_locale参数设置
		wc.saveLocale();

		wc.response.setCharacterEncoding(UTF_8);
		wc.session = request.getSession(false); //默认不创建session
		//wc.session = req.getSession();

		wc.cookies = new HashMap<String, Cookie>();// 获取cookie
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie ck : cookies) {
				wc.cookies.put(ck.getName(), ck);
			}
		}

		CONTEXTS.set(wc);
		return wc;
	}

	/**
	 * 删除上传临时文件,清除context上下文。
	 */
	public void end() {
		String tmpPath = (String) request.getAttribute(TEMP_UPLOAD_FILE);
		if (tmpPath != null) {
			try {
				FileUtils.deleteDirectory(new File(tmpPath));
			} catch (IOException e) {
				log.error("Failed to cleanup upload directory: " + tmpPath, e);
			}
		}
		this.context = null;
		this.request = null;
		this.response = null;
		this.session = null;
		this.cookies = null;
		this.locale = null;

		CONTEXTS.remove();
	}

	/**
	 * 自动文件上传请求的封装
	 *
	 * @param req
	 * @return
	 */
	private static HttpServletRequest autoUploadRequest(HttpServletRequest request) {
		if (isMultipart(request)) {
			String path = System.getProperty("java.io.tmpdir") + RandomStringUtils.randomAlphanumeric(10);
			File dir = new File(path);
			if (!dir.exists() && !dir.isDirectory())
				dir.mkdirs();
			try {
				request.setAttribute(TEMP_UPLOAD_FILE, dir.getCanonicalPath());
				return new MultipartRequest(request, dir.getCanonicalPath(), maxSize, UTF_8);
			} catch (NullPointerException e) {
			} catch (IOException e) {
				log.error("Failed to save upload files into temp directory: " + path, e);
			}
		}

		return request;
	}

	/**
	 * 自动编码处理
	 *
	 * @param req
	 * @return
	 */
	private static HttpServletRequest encodeRequest(HttpServletRequest req) {
		if (req instanceof RequestProxy)
			return req;
		HttpServletRequest autoEncodingReq = req;
		if ("POST".equalsIgnoreCase(req.getMethod())) {
			try {
				autoEncodingReq.setCharacterEncoding(UTF_8);
			} catch (UnsupportedEncodingException e) {
			}
		}

		return autoEncodingReq;
	}

	/**
	 * @return the maxSize
	 */
	public static int getMaxSize() {
		return maxSize;
	}

	/**
	 * @param maxSize the maxSize to set
	 */
	public static void setMaxSize(int maxSize) {
		WebContext.maxSize = maxSize;
	}

	/**
	 * 获取当前请求的上下文
	 *
	 * @return
	 */
	public static WebContext get() {
		return CONTEXTS.get();
	}

	public ServletContext getContext() {
		return context;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public HttpSession getSession() {
		return session;
	}

	public HttpSession getSession(boolean create) {
		return (session == null && create) ? (session = request.getSession()) : session;
	}

	public String getQueryString() {
		return request.getQueryString();
	}

	@SuppressWarnings("unchecked")
	public Enumeration<String> getParams() {
		return request.getParameterNames();
	}

	public String getParam(String name) {
		return request.getParameter(name);
	}

	public String getParam(String name, String... defValue) {
		String v = request.getParameter(name);
		return (v != null) ? v : ((defValue.length > 0) ? defValue[0] : null);
	}

	public long getParam(String name, long defValue) {
		return NumberUtils.toLong(getParam(name), defValue);
	}

	public int getParam(String name, int defValue) {
		return NumberUtils.toInt(getParam(name), defValue);
	}

	public byte getParam(String name, byte defValue) {
		return NumberUtils.toByte(getParam(name), defValue);
	}

	public String[] getParams(String name) {
		return request.getParameterValues(name);
	}

	public Object getRequestAttr(String name) {
		HttpServletRequest request = getRequest();
		return (request != null) ? request.getAttribute(name) : null;
	}

	public void setRequestAttr(String key, Object value) {
		request.setAttribute(key, value);
	}

	public Object getSessionAttr(String name) {
		HttpSession ssn = getSession();
		return (ssn != null) ? ssn.getAttribute(name) : null;
	}

	public void setSessionAttr(String key, Object value) {
		HttpSession ssn = getSession(true);
		ssn.setAttribute(key, value);
	}

	public Cookie getCookie(String name) {
		return cookies.get(name);
	}

	public void setCookie(String name, String value, int maxAge, boolean allSubDomain) {
		RequestUtils.setCookie(request, response, name, value, maxAge, allSubDomain);
	}

	public void deleteCookie(String name, boolean all_domain) {
		RequestUtils.deleteCookie(request, response, name, all_domain);
	}

	public String getHeader(String name) {
		return request.getHeader(name);
	}

	public void setHeader(String name, String value) {
		response.setHeader(name, value);
	}

	public void setHeader(String name, int value) {
		response.setIntHeader(name, value);
	}

	public void setHeader(String name, long value) {
		response.setDateHeader(name, value);
	}

	public void forward(String uri) throws ServletException, IOException {
		RequestDispatcher rd = context.getRequestDispatcher(uri);
		rd.forward(request, response);
	}

	public void redirect(String uri) throws IOException {
		response.sendRedirect(uri);
	}

	public void include(String uri) throws ServletException, IOException {
		RequestDispatcher rd = context.getRequestDispatcher(uri);
		rd.include(request, response);
	}

	public static boolean isMultipart(HttpServletRequest request) {
		return ((request.getContentType() != null) &&
				(request.getContentType().toLowerCase().startsWith("multipart")));
	}

	public boolean isUpload() {
		return (request instanceof MultipartRequest);
	}

	public boolean isRobot() {
		return RequestUtils.isRobot(request);
	}

	public long getId() {
		return getParam("id", 0L);
	}

	public String getIp() {
		return RequestUtils.getRemoteAddr(request);
	}

	public File getFile(String fieldName) {
		if (request instanceof MultipartRequest)
			return ((MultipartRequest) request).getFile(fieldName);
		return null;
	}

	public File getImage(String fieldname) {
		File imgFile = getFile(fieldname);
		return (imgFile != null && Multimedia.isImageFile(imgFile.getName())) ? imgFile : null;
	}

	public String getServletPath() {
		return request.getServletPath();
	}

	public String getURI() {
		return request.getRequestURI();
	}

	public String getContextPath() {
		return request.getContextPath();
	}

	public static String getWebrootPath() {
		String root = WebContext.class.getResource("/").getFile();
		try {
			root = new File(root).getParentFile().getParentFile().getCanonicalPath();
			root += File.separator;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return root;
	}

	/**
	 * 从cookie中获取locale信息
	 * @return
	 */
	public Locale getLocale() {
		if (locale != null) {
			return locale;
		}

		Cookie cookie = getCookie(LOCALE);
		if (cookie != null) {
			return LocaleUtils.toLocale(cookie.getValue());
		}

		return request.getLocale();
	}

	public void saveLocale(String localeValue) {
		saveLocale(localeValue, MAX_AGE);
	}

	/**
	 * 将local信息存入cookie
	 * @param localeValue
	 */
	public void saveLocale(String localeValue, int maxAge) {
		if (localeValue != null) {
			try {
				locale = LocaleUtils.toLocale(localeValue);
				response.setLocale(locale);// 放入请求
				setCookie(LOCALE, locale.getLanguage() + "_" + locale.getCountry(), maxAge, true);
			} catch (Exception e) {
				log.warn("setLocale is error, localeValue=" + localeValue + "is not used.");
			}
		}
	}

	/**
	 * 从url参数中获取locale并存入cookie
	 */
	public void saveLocale() {
		String requestLocale = getParam(REQUEST_LOCALE_PARAM);
		saveLocale(requestLocale);
	}

	/**
	 * 输出信息到浏览器
	 *
	 * @param msg
	 * @throws IOException
	 */
	public void print(Object msg) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		if (!UTF_8.equalsIgnoreCase(response.getCharacterEncoding()))
			response.setCharacterEncoding(UTF_8);
		response.getWriter().print(msg);
	}

	public void printJson(String[] key, Object[] value) throws IOException {
		StringBuilder json = new StringBuilder("{");
		for (int i = 0; i < key.length; i++) {
			if (i > 0)
				json.append(',');
			boolean isNum = value[i] instanceof Number;
			json.append("\"");
			json.append(key[i]);
			json.append("\":");
			if (!isNum)
				json.append("\"");
			json.append(value[i]);
			if (!isNum)
				json.append("\"");
		}
		json.append("}");
		print(json.toString());
	}

	public void printJson(String key, Object value) throws IOException {
		printJson(new String[] { key }, new Object[] { value });
	}

	public void notFound() throws IOException {
		error(HttpServletResponse.SC_NOT_FOUND);
	}

	public void error(int code, String... msg) throws IOException {
		if (msg.length > 0)
			response.sendError(code, msg[0]);
		else
			response.sendError(code);
	}

	public void forbidden() throws IOException {
		error(HttpServletResponse.SC_FORBIDDEN);
	}

	public void closeCache() {
		setHeader("Pragma", "No-cache");
		setHeader("Cache-Control", "no-cache");
		setHeader("Expires", 0L);
	}

	public ActionException fromResource(String bundle, String key, Object... args) {
		String res = ResourceUtils.getStringForLocale(request.getLocale(), bundle, key, args);
		return new ActionException(res);
	}

	/**
	 * 将HTTP请求参数映射到bean对象中
	 *
	 * @param req
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public <T> T convertBean(Class<T> beanClass) {
		try {
			T bean = beanClass.newInstance();
			BeanUtils.populate(bean, request.getParameterMap());
			return bean;
		} catch (Exception e) {
			throw new ActionException(e.getMessage());
		}
	}

	public void populate(Object bean) throws IllegalAccessException, InvocationTargetException {
		BeanUtils.populate(bean, request.getParameterMap());
	}

	/**
	 * 去除contextPath的URI
	 * @param rc
	 * @return
	 */
	public String getURIAndExcludeContextPath() {
		if (getContextPath().equals("")) {
			return getURI();
		} else {
			String t = StringUtils.substringAfter(getURI(), getContextPath());
			if (!t.startsWith("/")) {
				t = "/" + t;
			}
			return t;
		}
	}

	/**
	 * 从cookie中读取保存的用户信息
	 *
	 * @param req
	 * @return
	 */
	public IUser getUserFromCookie() {
		try {
			Cookie cookie = getCookie(COOKIE_LOGIN);
			if (cookie != null && StringUtils.isNotBlank(cookie.getValue())) {
				return getUserByUUID(cookie.getValue());
			}
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 保存登录信息
	 *
	 * @param req
	 * @param res
	 * @param user
	 * @param save
	 */
	public void saveUserInCookie(IUser user, boolean save) {
		String newValue = genLoginKey(user, getIp(), getHeader("user-agent"));
		int maxAge = save ? MAX_AGE : -1;
		deleteCookie(COOKIE_LOGIN, true);
		setCookie(COOKIE_LOGIN, newValue, maxAge, true);
	}

	/**
	 * 删除登录信息
	 */
	public void deleteUserFromCookie() {
		deleteCookie(COOKIE_LOGIN, true);
	}

	/**
	 * 从cookie中读取保存的用户信息
	 *
	 * @param req
	 * @return
	 */
	public IUser getUserByUUID(String uuid) {
		if (StringUtils.isBlank(uuid))
			return null;
		String ck = decrypt(uuid);
		final String[] items = StringUtils.split(ck, '|');
		if (items.length == 5) {
			String ua = getHeader("user-agent");
			int uaCode = (ua == null) ? 0 : ua.hashCode();
			int oldUaCode = Integer.parseInt(items[3]);
			if (uaCode == oldUaCode) {
				return new IUser() {
					public boolean isBlocked() {
						return false;
					}

					public long getId() {
						return NumberUtils.toLong(items[0], -1L);
					}

					public String getPassword() {
						return items[1];
					}

					public byte getRole() {
						return IUser.ROLE_GENERAL;
					}
				};
			}
		}
		return null;
	}

	/**
	 * 生成用户登录标识字符串
	 *
	 * @param user
	 * @param ip
	 * @param userAgent
	 * @return
	 */
	public static String genLoginKey(IUser user, String ip, String userAgent) {
		StringBuilder sb = new StringBuilder();
		sb.append(user.getId());
		sb.append('|');
		sb.append(user.getPassword());
		sb.append('|');
		sb.append(ip);
		sb.append('|');
		sb.append((userAgent == null) ? 0 : userAgent.hashCode());
		sb.append('|');
		sb.append(System.currentTimeMillis());
		return encrypt(sb.toString());
	}

	/**
	 * 加密
	 *
	 * @param value
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String value) {
		byte[] data = CryptUtils.encrypt(value.getBytes(), E_KEY);
		try {
			return URLEncoder.encode(new String(Base64.encodeBase64(data)), UTF_8);
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	/**
	 * 解密
	 *
	 * @param value
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String value) {
		try {
			value = URLDecoder.decode(value, UTF_8);
			if (StringUtils.isBlank(value))
				return null;
			byte[] data = Base64.decodeBase64(value.getBytes());
			return new String(CryptUtils.decrypt(data, E_KEY));
		} catch (UnsupportedEncodingException excp) {
			return null;
		}
	}

	/**
	 * 自动解码
	 *
	 */
	private static class RequestProxy extends HttpServletRequestWrapper {
		private String uriEncoding;

		RequestProxy(HttpServletRequest request, String encoding) {
			super(request);
			this.uriEncoding = encoding;
		}

		/**
		 * 重载getParameter
		 */
		public String getParameter(String paramName) {
			String value = super.getParameter(paramName);
			return decodeParamValue(value);
		}

		/**
		 * 重载getParameterMap
		 */
		@SuppressWarnings({ "unchecked", "rawtypes" })
		public Map<String, Object> getParameterMap() {
			Map params = super.getParameterMap();
			HashMap<String, Object> newParams = new HashMap<String, Object>();
			Iterator<String> iter = params.keySet().iterator();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				Object oValue = params.get(key);
				if (oValue.getClass().isArray()) {
					String[] values = (String[]) params.get(key);
					String[] new_values = new String[values.length];
					for (int i = 0; i < values.length; i++)
						new_values[i] = decodeParamValue(values[i]);

					newParams.put(key, new_values);
				} else {
					String value = (String) params.get(key);
					String newValue = decodeParamValue(value);
					if (newValue != null)
						newParams.put(key, newValue);
				}
			}
			return newParams;
		}

		/**
		 * 重载getParameterValues
		 */
		public String[] getParameterValues(String arg) {
			String[] values = super.getParameterValues(arg);
			for (int i = 0; values != null && i < values.length; i++)
				values[i] = decodeParamValue(values[i]);
			return values;
		}

		/**
		 * 参数转码
		 *
		 * @param value
		 * @return
		 */
		private String decodeParamValue(String value) {
			if (StringUtils.isBlank(value) || StringUtils.isBlank(uriEncoding)
					|| StringUtils.isNumeric(value))
				return value;
			try {
				return new String(value.getBytes("8859_1"), uriEncoding);
			} catch (Exception e) {
			}
			return value;
		}
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <properties>
        <phpmavenTagName>${project.version}</phpmavenTagName>
    </properties>

    <parent>
        <groupId>org.phpmaven.build</groupId>
        <artifactId>generic-java-parent</artifactId>
        <version>2.0.3-SNAPSHOT</version>
        <relativePath>../java-parent/pom.xml</relativePath>
    </parent>

    <groupId>org.phpmaven</groupId>
    <artifactId>maven-httpd-control-api</artifactId>
    <packaging>jar</packaging>

    <name>maven-httpd-control-api:${project.version}</name>

    <description>
        A Maven plugin for dependency management and quality assurance in PHP projects. Uses
        the default Maven lifecycle to provide multiple php features.

        httpd webserver plugin.
    </description>

    <url>${phpmavenRootUrl}/${phpmavenTagType}/${phpmavenTagName}/maven-httpd-control-api/</url>

    <distributionManagement>
        <site>
            <id>upload-${phpmavenSitesId}</id>
            <name>${phpmavenSitesName}</name>
            <url>${phpmavenSitesUploadUrl}/${phpmavenTagType}/${phpmavenTagName}/maven-httpd-control-api/</url>
        </site>
    </distributionManagement>

    <dependencies>
    	<!-- maven -->
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>3.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>3.0.4</version>
        </dependency>
        <dependency>
        	<groupId>org.phpmaven</groupId>
        	<artifactId>maven-php-core</artifactId>
        	<version>${project.version}</version>
        </dependency>
    </dependencies>

  <build>
      <plugins>
      	  <plugin>
      	      <groupId>org.apache.maven.plugins</groupId>
      	      <artifactId>maven-site-plugin</artifactId>
      	      <configuration>
      	      	<reportPlugins>
      	      		<reportPlugin>
      	      			<groupId>org.apache.maven.plugins</groupId>
      	      			<artifactId>maven-plugin-plugin</artifactId>
      	      			<version>2.9</version>
      	      		</reportPlugin>
      	      	</reportPlugins>
      	      </configuration>
      	  </plugin>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-source-plugin</artifactId>
          </plugin>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-javadoc-plugin</artifactId>
          </plugin>
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-remote-resources-plugin</artifactId>
          </plugin>
            <plugin>
                <groupId>org.phpmaven.sites</groupId>
                <artifactId>sitemap-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


text:
StringBuilder::StringBuilder(MallocFuncPtr pMallocFunc, FreeFuncPtr pFreeFunc)
{
	m_pMallocFunc = pMallocFunc;
	m_pFreeFunc = pFreeFunc;

	m_iPosition = 0;
	m_oFirstPool.m_pNext = NULL;
	m_pCurrentPool = &m_oFirstPool;
	m_iCurrentPoolIndex = 0;
}

StringBuilder::~StringBuilder()
{
	Clear(true);
}

void StringBuilder::Clear(bool bFreePools)
{
	m_iPosition = 0;
	m_pCurrentPool = &m_oFirstPool;
	m_iCurrentPoolIndex = 0;
	if (bFreePools)
	{
		Pool* pPool = m_oFirstPool.m_pNext;
		while (NULL != pPool)
		{
			Pool* pNextPool = pPool->m_pNext;
			m_pFreeFunc(pPool);
			pPool = pNextPool;
		}
	}
}

void StringBuilder::Append(char cChar)
{
	AppendInternal(&cChar, 1);
}

void StringBuilder::Append(const char* pString)
{
	AppendInternal(pString, (uint32)strlen(pString));
}

void StringBuilder::CopyTo(char* pDest)
{
	if (pDest != NULL)
	{
		Pool* pCurrentPool = &m_oFirstPool;
		for (uint32 iPos = 0; iPos < m_iPosition; iPos += c_iPoolSize)
		{
			int iLen = m_iPosition - iPos;
			if (iLen > c_iPoolSize)
				iLen = c_iPoolSize;

			memcpy(pDest + iPos, pCurrentPool->m_oData, iLen);

			pCurrentPool = pCurrentPool->m_pNext;
		}
		*(pDest + m_iPosition) = 0;
	}
}

char* StringBuilder::Export()
{
	if (m_iPosition == 0)
		return NULL;

	char* pOut = (char*)m_pMallocFunc(m_iPosition + 1);
	CopyTo(pOut);
	return pOut;
}

void StringBuilder::operator +=(char cChar)
{
	Append(cChar);
}

void StringBuilder::operator +=(const char* pString)
{
	Append(pString);
}

#ifdef __STRINGBUILDER_USE_STD_STRING__
void StringBuilder::Append(const std::string& oString)
{
	AppendInternal(oString.c_str(), (uint32)oString.length());
}

void StringBuilder::CopyTo(std::string& sOut)
{
	sOut.resize(m_iPosition);
	char* pOut = (char*)sOut.data();
	CopyTo(pOut);
}

void StringBuilder::operator +=(const std::string& oString)
{
	Append(pString);
}
#endif //__STRINGBUILDER_USE_STD_STRING__

void StringBuilder::AppendInternal(const char* pString, uint32 iLen)
{
	if (iLen == 0)
		return;

	// Copy pString to pools
	uint32 iPoolPos = m_iPosition - m_iCurrentPoolIndex * c_iPoolSize;
	uint32 iStrPos = 0;
	while (iStrPos < iLen)
	{
		if (iPoolPos >= c_iPoolSize)
		{
			if (m_pCurrentPool->m_pNext == NULL)
			{
				Pool* pNewPool = (Pool*)m_pMallocFunc(sizeof(Pool));
				pNewPool->m_pNext = NULL;
				m_pCurrentPool->m_pNext = pNewPool;
				m_pCurrentPool = pNewPool;
			}
			else
			{
				m_pCurrentPool = m_pCurrentPool->m_pNext;
			}

			++m_iCurrentPoolIndex;
			iPoolPos = iPoolPos - c_iPoolSize;
		}

		int iMaxCopySize = c_iPoolSize - iPoolPos;
		int iToCopySize = iLen - iStrPos;
		if (iToCopySize > iMaxCopySize)
			iToCopySize = iMaxCopySize;

		memcpy(m_pCurrentPool->m_oData + iPoolPos, pString + iStrPos, iToCopySize);

		iStrPos += iToCopySize;
		iPoolPos += iToCopySize;
	}

	m_iPosition += iLen;
}


text:
#include "common_tools.h"
#include "opengl.h"

typedef void (APIENTRY *glTexStorageSparseAMDPROC) (jint, jint, jint, jint, jint, jint, jint);
typedef void (APIENTRY *glTextureStorageSparseAMDPROC) (jint, jint, jint, jint, jint, jint, jint, jint);

EXTERN_C_ENTER

JNIEXPORT void JNICALL Java_org_lwjgl_opengl_AMDSparseTexture_glTexStorageSparseAMD(JNIEnv *__env, jclass clazz, jint target, jint internalFormat, jint width, jint height, jint depth, jint layers, jint flags) {
    glTexStorageSparseAMDPROC glTexStorageSparseAMD = (glTexStorageSparseAMDPROC)tlsGetFunction(1106);
    UNUSED_PARAM(clazz)
    glTexStorageSparseAMD(target, internalFormat, width, height, depth, layers, flags);
}

JNIEXPORT void JNICALL Java_org_lwjgl_opengl_AMDSparseTexture_glTextureStorageSparseAMD(JNIEnv *__env, jclass clazz, jint texture, jint target, jint internalFormat, jint width, jint height, jint depth, jint layers, jint flags) {
    glTextureStorageSparseAMDPROC glTextureStorageSparseAMD = (glTextureStorageSparseAMDPROC)tlsGetFunction(1107);
    UNUSED_PARAM(clazz)
    glTextureStorageSparseAMD(texture, target, internalFormat, width, height, depth, layers, flags);
}

EXTERN_C_EXIT


text:
require 'stackbuilder/allocator/hosts'
require 'stackbuilder/stacks/factory'

describe StackBuilder::Allocator::Hosts do
  before do
    extend Stacks::DSL
  end

  describe 'establish_availability_group_rack_distribution' do
    it 'provides a hash of racks with correct availability group counts' do
      h1 = StackBuilder::Allocator::Host.new("h1", :facts => { 'rack' => 'A' })
      h2 = StackBuilder::Allocator::Host.new("h2", :facts => { 'rack' => 'B' })
      h3 = StackBuilder::Allocator::Host.new("h3", :facts => { 'rack' => 'A' })
      h4 = StackBuilder::Allocator::Host.new("h3", :facts => { 'rack' => 'C' })

      h1.allocated_machines << { :hostname => "refapp1", :availability_group => "refapp" }
      h2.allocated_machines << { :hostname => "refapp2", :availability_group => "refapp" }
      h3.allocated_machines << { :hostname => "refapp3", :availability_group => "refapp" }

      hosts = StackBuilder::Allocator::Hosts.new(:hosts => [h1, h2, h3, h4], :preference_functions => [])
      distribution_hash = hosts.availability_group_rack_distribution
      expect(distribution_hash.key?('A')).to eql(true)
      expect(distribution_hash.key?('B')).to eql(true)
      expect(distribution_hash.key?('C')).to eql(true)

      expect(distribution_hash['A'].key?('refapp')).to eql(true)
      expect(distribution_hash['B'].key?('refapp')).to eql(true)
      expect(distribution_hash['C'].key?('refapp')).to eql(false)

      expect(distribution_hash['A']['refapp']).to eql(2)
      expect(distribution_hash['B']['refapp']).to eql(1)
    end
  end
end


text:
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@*common:drawable/ic_settings_voice_calls"
    android:tint="@*common:color/settings_side_icons" />


text:
//
//  HXPhotoViewController.h
//  微博照片选择
//
//  Created by 洪欣 on 17/2/8.
//  Copyright © 2017年 洪欣. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "HXPhotoManager.h"

/**
 *  使用说明: 如果只使用选择图片的功能,就只用跳转此控制器. 照片管理类必须在跳转前赋值
 *  选择的照片/视频通过代理返回
 */

@protocol HXPhotoViewControllerDelegate <NSObject>

@optional
/**
 点击下一步执行的代理  数组里面装的都是 HXPhotoModel 对象

 @param allList 所有对象 - 之前选择的所有对象
 @param photos 图片对象 - 之前选择的所有图片
 @param videos 视频对象 - 之前选择的所有视频
 @param original 是否原图
 */
- (void)photoViewControllerDidNext:(NSArray<HXPhotoModel *> *)allList Photos:(NSArray<HXPhotoModel *> *)photos Videos:(NSArray<HXPhotoModel *> *)videos Original:(BOOL)original;

/**
 点击取消执行的代理
 */
- (void)photoViewControllerDidCancel;

@end

@interface HXPhotoViewController : UIViewController
@property (strong, nonatomic) HXPhotoManager *manager; // 照片管理类必须在跳转前赋值
@property (weak, nonatomic) id<HXPhotoViewControllerDelegate> delegate;
@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic, readonly) NSIndexPath *currentIndexPath;
@property (assign, nonatomic) BOOL isPreview;
@property (strong, nonatomic, readonly) HXAlbumModel *albumModel;

@property (strong, nonatomic) NSMutableArray *videos;
@property (strong, nonatomic) NSMutableArray *objs;
@property (strong, nonatomic) NSMutableArray *photos;
@end

typedef enum : NSUInteger {
    HXPhotoBottomTyPepreview = 0,
    HXPhotoBottomTyOriginalPhoto,
} HXPhotoBottomType;

@protocol HXPhotoBottomViewDelegate <NSObject>

- (void)didPhotoBottomViewClick:(HXPhotoBottomType)type Button:(UIButton *)button;

@end

@interface HXPhotoBottomView : UIView
@property (weak, nonatomic) id<HXPhotoBottomViewDelegate> delegate;
@property (weak, nonatomic) UIButton *previewBtn;
@property (weak, nonatomic) UIButton *originalBtn;
- (instancetype)initWithFrame:(CGRect)frame manager:(HXPhotoManager *)manager;
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  >
  <TextView
    android:id="@+id/selection"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />
  <Spinner android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>


text:
 ////////////////////////////////////////////////////////////////////////////////

/* ------------------------------------------------------
 * Form components are provided as a place holder
 * for your application.
 * It is not expected that you will be using them
 * or customizing them
 * ------------------------------------------------------
 *//////////////////////////////////////

var SensorQueryForm = React.createClass({displayName: "SensorQueryForm",

    propTypes: {},
    mixins : [
            traceMixIn
        ],

    getDefaultProps: function() {
        return {
            sensor: "pa_1_P1",
            query: "occupied",
            map: false,
            //private props
            queries : ['occupied',
            'duration',
            'summary',
            'avgduration',
            'avgduration-daily',
            'parks',
            'turnover',
            'vacancy',
            'latestvalue',
            'peoplecount']

        } ;
    },

    getInitialState: function() {
        var sensor = this.props.sensor ;
        var query = this.props.query ;

     return {
        sensor: sensor,
        query: query,
        map: false,
        submit: false,
        queried: false
      };
    },

    selectedQuery: function(query) {
        this.setState({query: query, submit: false}) ;
    },

    handleInputChange: function(key, event) {
      var partialState = {};
      this.setState({submit: false}) ;
      partialState[key] = event.target.value;
      this.setState(partialState);
    },

    handleSubmit: function(e) {
        e.preventDefault();
        var sensor = React.findDOMNode(this.refs.sensor).value.trim();
        this.setState({sensor: sensor, queried: true, submit: true}) ;
        return ;
    },

    render: function() {
        this.trace('rendering sensorqueryform....') ;

        var results = null ;

        if (this.state.submit) {
            results =
                        React.createElement(SensorQueries, {
                             sensor: this.state.sensor,
                             query: this.state.query,
                             config: this.props.config}
                          )
                       ;

        }

        return (
            React.createElement("div", {className: "sensorquery-form"},
                React.createElement("div", {className: "jumbotron"},
                    React.createElement("div", {className: "container"},
                        React.createElement("form", {onSubmit: this.handleSubmit, role: "form"},
                            React.createElement("div", {className: "container"},
                               React.createElement("div", {className: "form-group"},
                                React.createElement("label", null, "Sensor"),
                                React.createElement("input", {type: "text", className: "form-control", id: "sensor", value: this.state.sensor, onChange: this.handleInputChange.bind(null, 'sensor'), ref: "sensor"})
                              ),
                              React.createElement("div", {className: "form-group"},
                              React.createElement("table", null, React.createElement("tbody", null, React.createElement("tr", null, React.createElement("td", {width: "150px"},
                                React.createElement(DropDown, {
                                items: this.props.queries,
                                values: this.props.queries,
                                title: "Select a query...",
                                notify: this.selectedQuery})), React.createElement("td", null,
                              React.createElement("label", null, this.state.query)))))
                              ),
                              React.createElement("div", {className: "form-group"},
                              React.createElement("button", {type: "submit", className: "btn btn-primary", value: "submit"}, "Submit")
                              )
                            )
                       )
                    )
                ),
                React.createElement("div", {id: "sensorqueryresult-container"},
                results
                )
            )
        ) ;
    }
}) ;


text:
var IO = require('utilskit/io'),
	Parser = require('utilskit/parser');

exports.processContent = Parser.compressCssWithCssMinSync;

exports.compile = require('./dynatic').compile;


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data noupdate="1">

        <record id="analytic_journal_sale" model="account.analytic.journal">
            <field name="code">SAL</field>
            <field name="name">Sales</field>
            <field name="type">sale</field>
        </record>
        <record id="exp" model="account.analytic.journal">
            <field name="code">PUR</field>
            <field name="name">Purchases</field>
            <field name="type">purchase</field>
        </record>

        <!--
        Payment term
        -->
        <record id="account_payment_term_immediate" model="account.payment.term">
            <field name="name">Immediate Payment</field>
            <field name="note">Immediate Payment</field>
        </record>

        <record id="account_payment_term_line_immediate" model="account.payment.term.line">
            <field name="value">balance</field>
            <field eval="0" name="days"/>
            <field eval="0" name="days2"/>
            <field eval="account_payment_term_immediate" name="payment_id"/>
        </record>

        <record id="account_payment_term_15days" model="account.payment.term">
            <field name="name">15 Days</field>
            <field name="note">15 Days</field>
        </record>

        <record id="account_payment_term_line_15days" model="account.payment.term.line">
            <field name="value">balance</field>
            <field eval="15" name="days"/>
            <field eval="0" name="days2"/>
            <field eval="account_payment_term_15days" name="payment_id"/>
        </record>

        <record forcecreate="True" id="decimal_payment" model="decimal.precision">
            <field name="name">Payment Term</field>
            <field name="digits">6</field>
        </record>

        <record id="account_payment_term_net" model="account.payment.term">
            <field name="name">30 Net Days</field>
            <field name="note">30 Net Days</field>
        </record>

        <record id="account_payment_term_line_net" model="account.payment.term.line">
            <field name="value">balance</field>
            <field eval="30" name="days"/>
            <field eval="0" name="days2"/>
            <field eval="account_payment_term_net" name="payment_id"/>
        </record>

        <!--
        Account Journal Sequences
        -->

        <record id="sequence_sale_journal" model="ir.sequence">
            <field name="name">Account Default Sales Journal</field>
            <field eval="3" name="padding"/>
            <field name="prefix">SAJ/%(year)s/</field>
        </record>
        <record id="sequence_refund_sales_journal" model="ir.sequence">
            <field name="name">Account Default Sales Credit Note Journal</field>
            <field eval="3" name="padding"/>
            <field name="prefix">SCNJ/%(year)s/</field>
        </record>
        <record id="sequence_purchase_journal" model="ir.sequence">
            <field name="name">Account Default Expenses Journal</field>
            <field eval="3" name="padding"/>
            <field name="prefix">EXJ/%(year)s/</field>
        </record>
        <record id="sequence_refund_purchase_journal" model="ir.sequence">
            <field name="name">Account Default Expenses Credit Notes Journal</field>
            <field eval="3" name="padding"/>
            <field name="prefix">ECNJ/%(year)s/</field>
        </record>
        <record id="sequence_bank_journal" model="ir.sequence">
            <field name="name">Account Default Bank Journal</field>
            <field eval="3" name="padding"/>
            <field name="prefix">BNK/%(year)s/</field>
        </record>
        <record id="sequence_check_journal" model="ir.sequence">
            <field name="name">Account Default Checks Journal</field>
            <field eval="3" name="padding"/>
            <field name="prefix">CHK/%(year)s/</field>
        </record>
        <record id="sequence_cash_journal" model="ir.sequence">
            <field name="name">Account Default Cash Journal</field>
            <field eval="3" name="padding"/>
            <field name="prefix">CSH/%(year)s/</field>
        </record>
        <record id="sequence_opening_journal" model="ir.sequence">
            <field name="name">Account Default Opening Entries Journal</field>
            <field eval="3" name="padding"/>
            <field name="prefix">OPEJ/%(year)s/</field>
        </record>
        <record id="sequence_miscellaneous_journal" model="ir.sequence">
            <field name="name">Account Default Miscellaneous Journal</field>
            <field eval="3" name="padding"/>
            <field name="prefix">MISJ/%(year)s/</field>
        </record>

        <!--
        Account Statement Sequences
        -->
        <record id="sequence_reconcile" model="ir.sequence.type">
            <field name="name">Account Reconcile</field>
            <field name="code">account.reconcile</field>
        </record>
        <record id="sequence_reconcile_seq" model="ir.sequence">
            <field name="name">Account reconcile sequence</field>
            <field name="code">account.reconcile</field>
            <field name="prefix">A</field>
            <field eval="1" name="number_next"/>
            <field eval="1" name="number_increment"/>
        </record>

        <record id="sequence_statement_type" model="ir.sequence.type">
            <field name="name">Account Bank Statement</field>
            <field name="code">account.bank.statement</field>
        </record>
        <record id="sequence_statement" model="ir.sequence">
            <field name="name">Account Bank Statement</field>
            <field name="code">account.bank.statement</field>
            <field name="prefix">St. %(month)s/%(day)s/</field>
            <field eval="1" name="number_next"/>
            <field eval="1" name="number_increment"/>
        </record>

        <record id="cash_sequence_statement_type" model="ir.sequence.type">
            <field name="name">Account Cash Statement</field>
            <field name="code">account.cash.statement</field>
        </record>
        <record id="cash_sequence_statement" model="ir.sequence">
            <field name="name">Account Cash Statement</field>
            <field name="code">account.cash.statement</field>
            <field name="prefix">Cr. %(month)s/%(day)s/</field>
            <field eval="1" name="number_next"/>
            <field eval="1" name="number_increment"/>
        </record>
        <!--
        Invoice requests (deprecated)
        -->
        <record id="req_link_invoice" model="res.request.link">
            <field name="name">Invoice</field>
            <field name="object">account.invoice</field>
        </record>

        <!-- Account-related subtypes for messaging / Chatter -->
        <record id="mt_invoice_validated" model="mail.message.subtype">
            <field name="name">Validated</field>
            <field name="res_model">account.invoice</field>
            <field name="default" eval="False"/>
            <field name="description">Invoice validated</field>
        </record>
        <record id="mt_invoice_paid" model="mail.message.subtype">
            <field name="name">Paid</field>
            <field name="res_model">account.invoice</field>
            <field name="default" eval="False"/>
            <field name="description">Invoice paid</field>
        </record>
    </data>
</openerp>


text:
#ifndef __itkShortestPathCostFunctionLiveWire_h
#define __itkShortestPathCostFunctionLiveWire_h

#include "itkShortestPathCostFunction.h"

#include "itkImageRegionConstIterator.h"

namespace itk
{
  /** \brief Cost function for LiveWire purposes.
  Specific features are considered to calculate cummulative
  costs of a link between two pixels. These are:

  - Gradient Magnitude
  - Gradient Direction
  - Laplacian Zero Crossing

  By default the Gradient Magnitude is mapped linearly to cost values
  between 0 (good) and 1 (bad). Via SetDynamicCostMap( std::map< int, int > &costMap)
  a cost map can be set to dynamically map Gradient Magnitude (non
  linear). Thus, lower values can be considered with lower costs
  than higher values of gradient magnitudes.
  To compute  the costs of the gradient magnitude dynamically
  an iverted map of the histogram of gradient magnitude image is used.

  */
  template <class TInputImageType>
  class ITK_EXPORT ShortestPathCostFunctionLiveWire : public ShortestPathCostFunction<TInputImageType>
  {
  public:
    /** Standard class typedefs. */
    typedef ShortestPathCostFunctionLiveWire                Self;
    typedef ShortestPathCostFunction<TInputImageType>       Superclass;
    typedef SmartPointer<Self>                              Pointer;
    typedef SmartPointer<const Self>                        ConstPointer;
    typedef itk::ImageRegionConstIterator<TInputImageType>  ConstIteratorType;

    /** Method for creation through the object factory. */
    itkFactorylessNewMacro(Self)
    itkCloneMacro(Self)

    /** Run-time type information (and related methods). */
    itkTypeMacro(ShortestPathCostFunctionLiveWire, ShortestPathCostFunction);

    typedef itk::Image<unsigned char, 2>               UnsignedCharImageType;
    typedef itk::Image<float, 2>                       FloatImageType;

    typedef float ComponentType;
    typedef itk::CovariantVector< ComponentType, 2  >  OutputPixelType;
    typedef itk::Image< OutputPixelType, 2 >           VectorOutputImageType;

    typedef typename TInputImageType::IndexType        IndexType;
    typedef TInputImageType                            ImageType;
    typedef itk::ImageRegion<2>                        RegionType;

    /** \brief calculates the costs for going from p1 to p2*/
    virtual double GetCost(IndexType p1, IndexType p2);

    /** \brief returns the minimal costs possible (needed for A*)*/
    virtual double GetMinCost();

    /** \brief Initialize the metric*/
    virtual void Initialize ();

     /** \brief Add void pixel in cost map*/
    virtual void AddRepulsivePoint( const IndexType& index );

     /** \brief Remove void pixel in cost map*/
    virtual void RemoveRepulsivePoint( const IndexType& index );

    /** \brief Clear repulsive points in cost function*/
    virtual void ClearRepulsivePoints();

    itkSetMacro (RequestedRegion, RegionType);
    itkGetMacro (RequestedRegion, RegionType);

    // Set/Get function for sigma parameter
    itkSetMacro (UseApproximateGradient, bool);
    itkGetMacro (UseApproximateGradient, bool);

    virtual void SetImage(const TInputImageType* _arg);

    void SetDynamicCostMap( std::map< int, int > &costMap)
    {
      this->m_CostMap = costMap;
      this->m_UseCostMap = true;
      this->m_MaxMapCosts = -1;
      this->Modified();
    }

    void SetUseCostMap(bool useCostMap)
    {
      this->m_UseCostMap = useCostMap;
    }

    /**
     \brief Set the maximum of the dynamic cost map to save computation time.
    */
    void SetCostMapMaximum(double max)
    {
      this->m_MaxMapCosts = max;
    }

    enum Constants{
      MAPSCALEFACTOR = 10
    };

    /** \brief Returns the y value of gaussian with given offset and amplitude

       gaussian approximation
       f(x) = v(bin) * e^ ( -1/2 * (|x-k(bin)| / sigma)^2 )

       \param x
       \param xOfGaussian - offset
       \param yOfGaussian - amplitude
    */
    static double Gaussian(double x, double xOfGaussian, double yOfGaussian);

    const UnsignedCharImageType* GetMaskImage()
        { return this->m_MaskImage.GetPointer(); };

    const FloatImageType* GetGradientMagnitudeImage()
        { return this->m_GradientMagnitudeImage.GetPointer(); };

    const FloatImageType* GetEdgeImage()
        { return this->m_EdgeImage.GetPointer(); };

    const VectorOutputImageType* GetGradientImage()
        { return this->m_GradientImage.GetPointer(); };

  protected:

    ShortestPathCostFunctionLiveWire();

    virtual ~ShortestPathCostFunctionLiveWire() {};

    FloatImageType::Pointer m_GradientMagnitudeImage;
    FloatImageType::Pointer m_EdgeImage;
    UnsignedCharImageType::Pointer m_MaskImage;
    VectorOutputImageType::Pointer m_GradientImage;

    double minCosts;

    bool m_UseRepulsivePoints;

    typename Superclass::PixelType val;

    typename Superclass::PixelType startValue;
    typename Superclass::PixelType endValue;

    double m_GradientMax;

    RegionType m_RequestedRegion;

    bool m_UseApproximateGradient;

    bool m_Initialized;

    std::map< int, int > m_CostMap;

    bool m_UseCostMap;

    double m_MaxMapCosts;

  private:

    double SigmoidFunction(double I, double max, double min, double alpha, double beta);

  };

} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#include "itkShortestPathCostFunctionLiveWire.txx"
#endif

#endif /* __itkShortestPathCostFunctionLiveWire_h */


text:
package algorithms.sorting;

import algorithms.interfaces.JSorter;
import utilities.BillBoard;

import java.util.ArrayList;
import java.util.List;

/**
 * Class which is the implementation of MergeSort
 *
 * @author lilott8
 * @version 0.2
 * @since 205-02-24
 */
public class JMergeSort extends JSort implements JSorter {

    public final String TAG = getClass().getSimpleName();

    public JMergeSort() {
        super();
    }

    public JMergeSort(int x) {
        super(x);
    }

    public JMergeSort(List<Integer> values) {
        super(values);
    }

    /**
     * Get the size of the array
     * @return int as size of array
     */
    public int getSize() {
        return mSize;
    }

    /**
     * Gets a value at an index of the array
     * @param x index to be retrieved
     * @return int value at index
     */
    public int getValue(int x) {
        return mValues.get(x);
    }

    /**
     * Sort the array using selection
     */
    public void sort() {
        mValues = mergeSort(mValues);
    } // sort

    /**
     * Split the lists recursively until they contain 1 element
     * @param list list of elements to be split
     * @return list of elements, sorted.
     */
    protected List<Integer> mergeSort(List<Integer> list) {
        // Base case, we have only 1 item in our list
        if(list.size() == 1) {
            return list;
        }

        // Get the middle value to split the list into 2
        int midPoint = list.size()/2;

        List<Integer> left = new ArrayList<Integer>();
        List<Integer> right = new ArrayList<Integer>();

        // get the left half of the list
        for(int x = 0; x < midPoint; x++) {
            left.add(list.get(x));
        }

        // get the right half of the list
        for(int x = midPoint; x < list.size(); x++) {
            right.add(list.get(x));
        }

        // merge sort again!
        left = mergeSort(left);
        right = mergeSort(right);

        // zipper the lists together
        return merge(left, right);
    }

    /**
     * Combine the fragmented lists into one big list
     * @param left left half of the lists, the lower numbers
     * @param right right half of the lists, the higher numbers
     * @return merged lists
     */
    private List<Integer> merge(List<Integer> left, List<Integer> right) {
        List<Integer> result = new ArrayList<Integer>();

        // Move elements from either side to the result list
        while(!left.isEmpty() && !right.isEmpty()) {
            if(left.get(0) <= right.get(0)) {
                result.add(left.get(0));
                left.remove(0);
            } else {
                result.add(right.get(0));
                right.remove(0);
            }
        }

        // Finish emptying either list if there are elements.
        while(!left.isEmpty()) {
            result.add(left.get(0));
            left.remove(0);
        }
        while(!right.isEmpty()) {
            result.add(right.get(0));
            right.remove(0);
        }

        return result;
    }

    /**
     * Print the array to std out.
     */
    public void printArray() {
        BillBoard.d(TAG, super.getArrayAsString());
    }

}


text:
<?php
namespace SCFViewer\Model;

class Sentence extends \AZ\Framework\ORM{
  public static $table = 'sentences';
  public static $key = 'id_sentence';
  public static $foreign_key = 'id_sentence';
  public static $order_by = array('id_sentence' => 'ASC');

  public static $has = array(
    'examples' => '\SCFViewer\Model\Example',
  );

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;

using Microsoft.Build.Construction;
using Microsoft.Build.Shared;

using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using Xunit;

namespace Microsoft.Build.UnitTests.OM.Construction
{
    /// <summary>
    /// Tests for the ProjectUsingTaskElement class
    /// </summary>
    public class ProjectUsingTaskElement_Tests
    {
        /// <summary>
        /// Read project with no usingtasks
        /// </summary>
        [Fact]
        public void ReadNone()
        {
            ProjectRootElement project = ProjectRootElement.Create();

            Assert.Equal(null, project.UsingTasks.GetEnumerator().Current);
        }

        /// <summary>
        /// Read usingtask with no task name attribute
        /// </summary>
        [Fact]
        public void ReadInvalidMissingTaskName()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask AssemblyFile='af'/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        /// <summary>
        /// Read usingtask with empty task name attribute
        /// </summary>
        [Fact]
        public void ReadInvalidEmptyTaskName()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='' AssemblyFile='af'/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        /// <summary>
        /// Read usingtask with unexpected attribute
        /// </summary>
        [Fact]
        public void ReadInvalidAttribute()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t' AssemblyFile='af' X='Y'/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        /// <summary>
        /// Read usingtask with neither AssemblyFile nor AssemblyName attributes
        /// </summary>
        [Fact]
        public void ReadInvalidMissingAssemblyFileAssemblyName()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t'/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        /// <summary>
        /// Read usingtask with only empty AssemblyFile attribute
        /// </summary>
        [Fact]
        public void ReadInvalidEmptyAssemblyFile()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t' AssemblyFile=''/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        /// <summary>
        /// Read usingtask with empty AssemblyFile attribute but AssemblyName present
        /// </summary>
        [Fact]
        public void ReadInvalidEmptyAssemblyFileAndAssemblyNameNotEmpty()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t' AssemblyFile='' AssemblyName='n'/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        /// <summary>
        /// Read usingtask with only empty AssemblyName attribute but AssemblyFile present
        /// </summary>
        [Fact]
        public void ReadInvalidEmptyAssemblyNameAndAssemblyFileNotEmpty()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t' AssemblyName='' AssemblyFile='f'/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        /// <summary>
        /// Read usingtask with both AssemblyName and AssemblyFile attributes
        /// </summary>
        [Fact]
        public void ReadInvalidBothAssemblyFileAssemblyName()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t' AssemblyName='an' AssemblyFile='af'/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        /// <summary>
        /// Read usingtask with both AssemblyName and AssemblyFile attributes but both are empty
        /// </summary>
        [Fact]
        public void ReadInvalidBothEmptyAssemblyFileEmptyAssemblyNameBoth()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t' AssemblyName='' AssemblyFile=''/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        /// <summary>
        /// Read usingtask with assembly file
        /// </summary>
        [Fact]
        public void ReadBasicUsingTaskAssemblyFile()
        {
            ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyFile();

            Assert.Equal("t1", usingTask.TaskName);
            Assert.Equal("af", usingTask.AssemblyFile);
            Assert.Equal(String.Empty, usingTask.AssemblyName);
            Assert.Equal(String.Empty, usingTask.Condition);
        }

        /// <summary>
        /// Read usingtask with assembly name
        /// </summary>
        [Fact]
        public void ReadBasicUsingTaskAssemblyName()
        {
            ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyName();

            Assert.Equal("t2", usingTask.TaskName);
            Assert.Equal(String.Empty, usingTask.AssemblyFile);
            Assert.Equal("an", usingTask.AssemblyName);
            Assert.Equal("c", usingTask.Condition);
        }

        /// <summary>
        /// Read usingtask with task factory, required runtime and required platform
        /// </summary>
        [Fact]
        public void ReadBasicUsingTaskFactoryRuntimeAndPlatform()
        {
            ProjectUsingTaskElement usingTask = GetUsingTaskFactoryRuntimeAndPlatform();

            Assert.Equal("t2", usingTask.TaskName);
            Assert.Equal(String.Empty, usingTask.AssemblyFile);
            Assert.Equal("an", usingTask.AssemblyName);
            Assert.Equal("c", usingTask.Condition);
            Assert.Equal("AssemblyFactory", usingTask.TaskFactory);
        }

        /// <summary>
        /// Verify that passing in string.empty or null for TaskFactory will remove the element from the xml.
        /// </summary>
        [Fact]
        public void RemoveUsingTaskFactoryRuntimeAndPlatform()
        {
            ProjectUsingTaskElement usingTask = GetUsingTaskFactoryRuntimeAndPlatform();

            string value = null;
            VerifyAttributesRemoved(usingTask, value);

            usingTask = GetUsingTaskFactoryRuntimeAndPlatform();
            value = String.Empty;
            VerifyAttributesRemoved(usingTask, value);
        }

        /// <summary>
        /// Set assembly file on a usingtask that already has assembly file
        /// </summary>
        [Fact]
        public void SetUsingTaskAssemblyFileOnUsingTaskAssemblyFile()
        {
            ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyFile();
            Helpers.ClearDirtyFlag(usingTask.ContainingProject);

            usingTask.AssemblyFile = "afb";
            Assert.Equal("afb", usingTask.AssemblyFile);
            Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges);
        }

        /// <summary>
        /// Set assembly name on a usingtask that already has assembly name
        /// </summary>
        [Fact]
        public void SetUsingTaskAssemblyNameOnUsingTaskAssemblyName()
        {
            ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyName();
            Helpers.ClearDirtyFlag(usingTask.ContainingProject);

            usingTask.AssemblyName = "anb";
            Assert.Equal("anb", usingTask.AssemblyName);
            Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges);
        }

        /// <summary>
        /// Set assembly file on a usingtask that already has assembly name
        /// </summary>
        [Fact]
        public void SetUsingTaskAssemblyFileOnUsingTaskAssemblyName()
        {
            Assert.Throws<InvalidOperationException>(() =>
            {
                ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyName();

                usingTask.AssemblyFile = "afb";
            }
           );
        }
        /// <summary>
        /// Set assembly name on a usingtask that already has assembly file
        /// </summary>
        [Fact]
        public void SetUsingTaskAssemblyNameOnUsingTaskAssemblyFile()
        {
            Assert.Throws<InvalidOperationException>(() =>
            {
                ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyFile();

                usingTask.AssemblyName = "anb";
            }
           );
        }
        /// <summary>
        /// Set task name
        /// </summary>
        [Fact]
        public void SetTaskName()
        {
            ProjectRootElement project = ProjectRootElement.Create();
            ProjectUsingTaskElement usingTask = project.AddUsingTask("t", "af", null);
            Helpers.ClearDirtyFlag(usingTask.ContainingProject);

            usingTask.TaskName = "tt";
            Assert.Equal("tt", usingTask.TaskName);
            Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges);
        }

        /// <summary>
        /// Set condition
        /// </summary>
        [Fact]
        public void SetCondition()
        {
            ProjectRootElement project = ProjectRootElement.Create();
            ProjectUsingTaskElement usingTask = project.AddUsingTask("t", "af", null);
            Helpers.ClearDirtyFlag(usingTask.ContainingProject);

            usingTask.Condition = "c";
            Assert.Equal("c", usingTask.Condition);
            Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges);
        }

        /// <summary>
        /// Set task factory
        /// </summary>
        [Fact]
        public void SetTaskFactory()
        {
            ProjectRootElement project = ProjectRootElement.Create();
            ProjectUsingTaskElement usingTask = project.AddUsingTask("t", "af", null);
            Helpers.ClearDirtyFlag(usingTask.ContainingProject);

            usingTask.TaskFactory = "AssemblyFactory";
            Assert.Equal("AssemblyFactory", usingTask.TaskFactory);
            Assert.Equal(true, usingTask.ContainingProject.HasUnsavedChanges);
        }

        /// <summary>
        /// Make sure there is an exception when there are multiple parameter groups in the using task tag.
        /// </summary>
        [Fact]
        public void DuplicateParameterGroup()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory'>
                            <ParameterGroup/>
                            <ParameterGroup/>
                        </UsingTask>
                    </Project>
                ";
                ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
                Assert.True(false);
            }
           );
        }
        /// <summary>
        /// Make sure there is an exception when there are multiple task groups in the using task tag.
        /// </summary>
        [Fact]
        public void DuplicateTaskGroup()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory'>
                            <Task/>
                            <Task/>
                        </UsingTask>
                    </Project>
                ";
                ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
                Assert.True(false);
            }
           );
        }
        /// <summary>
        /// Make sure there is an exception when there is an unknown child
        /// </summary>
        [Fact]
        public void UnknownChild()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory'>
                            <IAMUNKNOWN/>
                        </UsingTask>
                    </Project>
                ";
                ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
                Assert.True(false);
            }
           );
        }
        /// <summary>
        /// Make sure there is an no exception when there are children in the using task
        /// </summary>
        [Fact]
        public void WorksWithChildren()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory'>
                            <ParameterGroup>
                               <MyParameter/>
                            </ParameterGroup>
                            <Task>
                                RANDOM GOO
                            </Task>
                        </UsingTask>
                    </Project>
                ";

            ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children);
            Assert.NotNull(usingTask);
            Assert.Equal(2, usingTask.Count);
        }

        /// <summary>
        /// Make sure there is an exception when a parameter group is added but no task factory attribute is on the using task
        /// </summary>
        [Fact]
        public void ExceptionWhenNoTaskFactoryAndHavePG()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t2' AssemblyName='an' Condition='c'>
                            <ParameterGroup>
                               <MyParameter/>
                            </ParameterGroup>
                        </UsingTask>
                    </Project>
                ";

                ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
                ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children);
                Assert.True(false);
            }
           );
        }
        /// <summary>
        /// Make sure there is an exception when a parameter group is added but no task factory attribute is on the using task
        /// </summary>
        [Fact]
        public void ExceptionWhenNoTaskFactoryAndHaveTask()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t2' AssemblyName='an' Condition='c'>
                            <Task/>
                        </UsingTask>
                    </Project>
                ";

                ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
                ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children);
                Assert.True(false);
            }
           );
        }
        /// <summary>
        /// Helper to get a ProjectUsingTaskElement with a task factory, required runtime and required platform
        /// </summary>
        private static ProjectUsingTaskElement GetUsingTaskFactoryRuntimeAndPlatform()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t2' AssemblyName='an' Condition='c' TaskFactory='AssemblyFactory' />
                    </Project>
                ";

            ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children);
            return usingTask;
        }

        /// <summary>
        /// Helper to get a ProjectUsingTaskElement with an assembly file set
        /// </summary>
        private static ProjectUsingTaskElement GetUsingTaskAssemblyFile()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t1' AssemblyFile='af' />
                        <UsingTask TaskName='t2' AssemblyName='an' Condition='c'/>
                    </Project>
                ";

            ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children);
            return usingTask;
        }

        /// <summary>
        /// Helper to get a ProjectUsingTaskElement with an assembly name set
        /// </summary>
        private static ProjectUsingTaskElement GetUsingTaskAssemblyName()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <UsingTask TaskName='t2' AssemblyName='an' Condition='c'/>
                    </Project>
                ";

            ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            ProjectUsingTaskElement usingTask = (ProjectUsingTaskElement)Helpers.GetFirst(project.Children);
            return usingTask;
        }

        /// <summary>
        /// Verify the attributes are removed from the xml when string.empty and null are passed in
        /// </summary>
        private static void VerifyAttributesRemoved(ProjectUsingTaskElement usingTask, string value)
        {
            Assert.True(usingTask.ContainingProject.RawXml.Contains("TaskFactory"));
            usingTask.TaskFactory = value;
            Assert.False(usingTask.ContainingProject.RawXml.Contains("TaskFactory"));
        }
    }
}


text:
package org.donderom.sbt.published

case class IvyArtifact(scalaVersion: String, version: String, sbtVersion: Option[String] = None) {
  override def toString: String = sbtVersion match {
    case Some(ver) => s"Scala $scalaVersion, sbt $ver: $version"
    case _ => s"Scala $scalaVersion: $version"
  }
}


text:
Template.campSubmit.events({
    'submit form': function(e) {
        e.preventDefault();

        var camp = {
            url: $(e.target).find('[name=url]').val(),
            name: $(e.target).find('[name=name]').val()
        };

        Meteor.call('campInsert', camp, function(error, result) {
            // display the error to the user and abort
            if (error)
                return alert(error.reason);
            Router.go('campPage', {_id: result._id});
        });
    }
});


text:
package com.thingtrack.konekti.dao.sensor.api;

import com.thingtrack.konekti.dao.template.Dao;
import com.thingtrack.konekti.domain.sensor.CaptureLocation;

public interface CaptureLocationDao extends Dao<CaptureLocation, Integer> {

}


text:
IF YOU CANNOT DESIGN A WORKING `UNINSTALL` STANZA, PLEASE SUBMIT YOUR CASK ANYWAY. The maintainers will help you write an `uninstall` stanza, just ask!

## uninstall pkgutil: Is The Easiest and Most Useful

`pkgutil:` is the easiest and most useful `uninstall` directive. See [Uninstall Key pkgutil:](#uninstall-key-pkgutil).

## uninstall Is Required for Casks That Install a pkg or installer manual:

For most Casks, uninstall actions are determined automatically, and an explicit `uninstall` stanza is not needed. However, a Cask which uses the `pkg` or `installer manual:` stanzas will **not** know how to uninstall correctly unless an `uninstall` stanza is given.

So, while the Cask language does not enforce the requirement, it is much better for end-users if every `pkg` and `installer manual:` has a corresponding `uninstall`.

The `uninstall` stanza is available for non-`pkg` Casks, and is useful for a few corner cases. However, the documentation below concerns the typical case of using `uninstall` to define procedures for a `pkg`.

## There Are Multiple Uninstall Techniques

Since `pkg` installers can do arbitrary things, different techniques are needed to uninstall in each case. You may need to specify one, or several, of the following key/value pairs as arguments to `uninstall`.

## Summary of Keys

* `early_script:` (string or hash) - like `script:`, but runs early (for special cases, best avoided)
* `launchctl:` (string or array) - ids of `launchctl` jobs to remove
* `quit:` (string or array) - bundle ids of running applications to quit
* `signal:` (array of arrays) - signal numbers and bundle ids of running applications to send a Unix signal to (used when `quit:` does not work)
* `login_item:` (string or array) - names of login items to remove
* `kext:` (string or array) - bundle ids of kexts to unload from the system
* `script:` (string or hash) - relative path to an uninstall script to be run via sudo; use hash if args are needed
  - `executable:` - relative path to an uninstall script to be run via sudo (required for hash form)
  - `args:` - array of arguments to the uninstall script
  - `input:` - array of lines of input to be sent to `stdin` of the script
  - `must_succeed:` - set to `false` if the script is allowed to fail
  - `sudo:` - set to `true` if the script needs `sudo`
* `pkgutil:` (string, regexp or array of strings and regexps) - strings or regexps matching bundle ids of packages to uninstall using `pkgutil`
* `delete:` (string or array) - single-quoted, absolute paths of files or directory trees to remove. `delete:` should only be used as a last resort. `pkgutil:` is strongly preferred.
* `rmdir:` (string or array) - single-quoted, absolute paths of directories to remove if empty
* `trash:` (string or array) - single-quoted, absolute paths of files or directory trees to move to Trash.

Each `uninstall` technique is applied according to the order above. The order in which `uninstall` keys appear in the Cask file is ignored.

For assistance filling in the right values for `uninstall` keys, there are several helper scripts found under `developer/bin` in the Homebrew Cask repository. Each of these scripts responds to the `-help` option with additional documentation.

The easiest way to work out an `uninstall` stanza is on a system where the `pkg` is currently installed and operational. To operate on an uninstalled `pkg` file, see [Working With a pkg File Manually](#working-with-a-pkg-file-manually), below.

## uninstall Key pkgutil:

This is the most useful uninstall key. `pkgutil:` is often sufficient to completely uninstall a `pkg`, and is strongly preferred over `delete:`.

IDs for the most recently-installed packages can be listed using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_recent_pkg_ids"
```

`pkgutil:` also accepts a regular expression match against multiple package IDs. The regular expressions are somewhat nonstandard. To test a `pkgutil:` regular expression against currently-installed packages, use the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_pkg_ids_by_regexp" <regular-expression>
```

## List Files Associated With a pkg Id

Once you know the ID for an installed package, (above), you can list all files on your system associated with that package ID using the macOS command:

```bash
$ pkgutil --files <package.id.goes.here>
```

Listing the associated files can help you assess whether the package included any `launchctl` jobs or kernel extensions (kexts).

## uninstall Key launchctl:

IDs for currently loaded `launchctl` jobs can be listed using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_loaded_launchjob_ids"
```

IDs for all installed `launchctl` jobs can be listed using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_installed_launchjob_ids"
```

## uninstall Key quit:

Bundle IDs for currently running Applications can be listed using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_running_app_ids"
```

Bundle IDs inside an Application bundle on disk can be listed using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_ids_in_app" '/path/to/application.app'
```

## uninstall Key signal:

`signal:` should only be needed in the rare case that a process does not respond to `quit:`.

Bundle IDs for `signal:` targets may be obtained as for `quit:`. The value for `signal:` is an array-of-arrays, with each cell containing two elements: the desired Unix signal followed by the corresponding bundle ID.

The Unix signal may be given in numeric or string form (see the `kill` man page for more details).

The elements of the `signal:` array are applied in order, only if there is an existing process associated the bundle ID, and stopping when that process terminates. A bundle ID may be repeated to send more than one signal to the same process.

It is better to use the least-severe signals which are sufficient to stop a process. The `KILL` signal in particular can have unwanted side-effects.

An example, with commonly-used signals in ascending order of severity:

```ruby
  uninstall signal: [
                      ['TERM', 'fr.madrau.switchresx.daemon'],
                      ['QUIT', 'fr.madrau.switchresx.daemon'],
                      ['INT',  'fr.madrau.switchresx.daemon'],
                      ['HUP',  'fr.madrau.switchresx.daemon'],
                      ['KILL', 'fr.madrau.switchresx.daemon'],
                    ]
```

Note that when multiple running processes match the given Bundle ID, all matching processes will be signaled.

Unlike `quit:` directives, Unix signals originate from the current user, not from the superuser. This is construed as a safety feature, since the superuser is capable of bringing down the system via signals. However, this inconsistency may also be considered a bug, and should be addressed in some fashion in a future version.

## uninstall key login_item:

Login items associated with an Application bundle on disk can be listed using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_login_items_for_app" '/path/to/application.app'
```

Note that you will likely need to have opened the app at least once for any login items to be present.

## uninstall Key kext:

IDs for currently loaded kernel extensions can be listed using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_loaded_kext_ids"
```

IDs inside a kext bundle you have located on disk can be listed using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_id_in_kext" '/path/to/name.kext'
```

## uninstall Key script:

`uninstall script:` introduces a series of key-value pairs describing a command which will automate completion of the uninstall. Example (from [gpgtools.rb](https://github.com/Homebrew/homebrew-cask/blob/4a0a49d1210a8202cbdd54bce2986f15049b8b61/Casks/gpgtools.rb#L33-#L37)):

```ruby
  uninstall script:    {
                         executable: "#{staged_path}/Uninstall.app/Contents/Resources/GPG Suite Uninstaller.app/Contents/Resources/uninstall.sh",
                         sudo:       true,
                       }
```

It is important to note that, although `script:` in the above example does attempt to completely uninstall the `pkg`, it should not be used in detriment of [`pkgutil:`](#uninstall-key-pkgutil), but as a complement when possible.

## uninstall Key delete:

`delete:` should only be used as a last resort, if other `uninstall` methods are insufficient.

Arguments to `uninstall delete:` should use the following basic rules:

* Only single quotes should be used, except when invoking [`#{version}` interpolation](https://github.com/Homebrew/homebrew-cask/blob/master/doc/cask_language_reference/stanzas/version.md). `ENV['HOME']` and other variables should not be interpolated in the value.
* Basic tilde expansion is performed on paths, i.e., leading `~` is expanded to the home directory.
* Paths must be absolute.
* Glob expansion is performed using the [standard set of characters](https://en.wikipedia.org/wiki/Glob_(programming)).

To remove user-specific files, use the [`zap` stanza](https://github.com/Homebrew/homebrew-cask/blob/master/doc/cask_language_reference/stanzas/zap.md).

## uninstall Key trash:

`trash:` arguments follow the same rules listed above for `delete:`.

## Working With a pkg File Manually

Advanced users may wish to work with a `pkg` file manually, without having the package installed.

A list of files which may be installed from a `pkg` can be extracted using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_payload_in_pkg" '/path/to/my.pkg'
```

Candidate application names helpful for determining the name of a Cask may be extracted from a `pkg` file using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_apps_in_pkg" '/path/to/my.pkg'
```

Candidate package IDs which may be useful in a `pkgutil:` key may be extracted from a `pkg` file using the command:

```bash
$ "$(brew --repository)/Library/Taps/homebrew/homebrew-cask/developer/bin/list_ids_in_pkg" '/path/to/my.pkg'
```

A fully manual method for finding bundle ids in a package file follows:

1. Unpack `/path/to/my.pkg` (replace with your package name) with `pkgutil --expand /path/to/my.pkg /tmp/expanded.unpkg`.
2. The unpacked package is a folder. Bundle ids are contained within files named `PackageInfo`. These files can be found with the command `find /tmp/expanded.unpkg -name PackageInfo`.
3. `PackageInfo` files are XML files, and bundle ids are found within the `identifier` attributes of `<pkg-info>` tags that look like `<pkg-info ... identifier="com.oracle.jdk7u51" ... >`, where extraneous attributes have been snipped out and replaced with ellipses.
4. Kexts inside packages are also described in `PackageInfo` files. If any kernel extensions are present, the command `find /tmp/expanded.unpkg -name PackageInfo -print0 | xargs -0 grep -i kext` should return a `<bundle id>` tag with a `path` attribute that contains a `.kext` extension, for example `<bundle id="com.wavtap.driver.WavTap" ... path="./WavTap.kext" ... />`.
5. Once bundle ids have been identified, the unpacked package directory can be deleted.