text:
package peersim.config;

import java.lang.reflect.*;
import java.util.*;
import org.lsmp.djep.groupJep.*;

/**
 * This class is the container for the configuration data used in
 * {@link Configuration}; see that class for more information.
 */
public class ConfigContainer
{

// =================== static fields =================================
// ===================================================================

/** Symbolic constant for no debug */
private static final int DEBUG_NO = 0;

/** Symbolic constant for regular debug */
private static final int DEBUG_REG = 1;

/** Symbolic constant for extended debug */
private static final int DEBUG_CONTEXT = 2;

//========================== fields =================================
//===================================================================

/**
 * The properties object that stores all configuration information.
 */
private Properties config;

/**
 * Map associating string protocol names to the numeric protocol
 * identifiers. The protocol names are understood without prefix.
 */
private Map<String, Integer> protocols;

/**
 * The maximum depth that can be reached when analyzing expressions. This
 * value can be substituted by setting the configuration parameter
 * PAR_MAXDEPTH.
 */
private int maxdepth;

/** Debug level */
private int debugLevel;

/**
 * If true, no exception is thrown. Instead, an error is printed and the
 * Configuration tries to return a reasonable return value
 */
private boolean check = false;

// =================== initialization ================================
// ===================================================================

public ConfigContainer(Properties config, boolean check)
{
	this.config = config;
	this.check = check;
	maxdepth = getInt(Configuration.PAR_MAXDEPTH, Configuration.DEFAULT_MAXDEPTH);

	// initialize protocol id-s
	protocols = new HashMap<String, Integer>();
	String[] prots = getNames(Configuration.PAR_PROT);// they're returned in correct order
	for (int i = 0; i < prots.length; ++i) {
		protocols.put(prots[i].substring(Configuration.PAR_PROT.length() + 1), Integer.valueOf(i));
	}
	String debug = config.getProperty(Configuration.PAR_DEBUG);
	if (Configuration.DEBUG_EXTENDED.equals(debug))
		debugLevel = DEBUG_CONTEXT;
	else if (Configuration.DEBUG_FULL.equals(debug)) {
		Map<String, String> map = new TreeMap<String, String>();
		Enumeration e = config.propertyNames();
		while (e.hasMoreElements()) {
			String name = (String) e.nextElement();
			String value = config.getProperty(name);
			map.put(name, value);
		}
		Iterator i = map.keySet().iterator();
		while (i.hasNext()) {
			String name = (String) i.next();
			System.err.println("DEBUG " + name
					+ ("".equals(map.get(name)) ? "" : " = " + map.get(name)));
		}
	} else if (debug != null) {
		debugLevel = DEBUG_REG;
	} else {
		debugLevel = DEBUG_NO;
	}
}

// =================== static public methods =========================
// ===================================================================

/**
 * @return true if and only if name is a specified (existing) property.
 */
public boolean contains(String name)
{
	boolean ret = config.containsKey(name);
	debug(name, "" + ret);
	return ret;
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, throws a
 * {@link MissingParameterException}.
 * @param name
 *          Name of configuration property
 * @param def
 *          default value
 */
public boolean getBoolean(String name, boolean def)
{
	try {
		return getBool(name);
	} catch (RuntimeException e) {
		manageDefault(name, def, e);
		return def;
	}
}

// -------------------------------------------------------------------

/**
 * Reads given property. If not found, or the value is empty string then
 * throws a {@link MissingParameterException}. Empty string is not
 * accepted as false due to the similar function of {@link #contains} which
 * returns true in that case. True is returned if the lowercase value of
 * the property is "true", otherwise false is returned.
 * @param name
 *          Name of configuration property
 */
public boolean getBoolean(String name)
{
	try {
		return getBool(name);
	} catch (RuntimeException e) {
		manageException(name, e);
		return false;
	}
}

//-------------------------------------------------------------------

/**
 * The actual methods that implements getBoolean.
 */
private boolean getBool(String name)
{
	if (config.getProperty(name) == null) {
		throw new MissingParameterException(name);
//				"\nPossibly incorrect property: " + getSimilarProperty(name));
	}
	if (config.getProperty(name).matches("\\p{Blank}*")) {
		throw new MissingParameterException(name,
				"Blank value is not accepted when parsing Boolean.");
	}
	boolean ret = Boolean.valueOf(config.getProperty(name));
	debug(name, "" + ret);
	return ret;
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, returns the default
 * value.
 * @param name
 *          Name of configuration property
 * @param def
 *          default value
 */
public int getInt(String name, int def)
{
	try {
		Number ret = getVal(name, name, 0);
		debug(name, "" + ret);
		return ret.intValue();
	} catch (RuntimeException e) {
		manageDefault(name, def, e);
		return def;
	}
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, throws a
 * {@link MissingParameterException}.
 * @param name
 *          Name of configuration property
 */
public int getInt(String name)
{
	try {
		Number ret = getVal(name, name, 0);
		debug(name, "" + ret);
		return ret.intValue();
	} catch (RuntimeException e) {
		manageException(name, e);
		return 0;
	}
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, returns the default
 * value.
 * @param name
 *          Name of configuration property
 * @param def
 *          default value
 */
public long getLong(String name, long def)
{
	try {
		Number ret = getVal(name, name, 0);
		debug(name, "" + ret);
		return ret.longValue();
	} catch (RuntimeException e) {
		manageDefault(name, def, e);
		return def;
	}
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, throws a
 * {@link MissingParameterException}.
 * @param name
 *          Name of configuration property
 */
public long getLong(String name)
{
	try {
		Number ret = getVal(name, name, 0);
		debug(name, "" + ret);
		return ret.longValue();
	} catch (RuntimeException e) {
		manageException(name, e);
			return 0;
	}
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, returns the default
 * value.
 * @param name
 *          Name of configuration property
 * @param def
 *          default value
 */
public double getDouble(String name, double def)
{
	try {
		Number ret = getVal(name, name, 0);
		debug(name, "" + ret);
		return ret.doubleValue();
	} catch (RuntimeException e) {
		manageDefault(name, def, e);
		return def;
	}
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, throws a
 * MissingParameterException.
 * @param name
 *          Name of configuration property
 */
public double getDouble(String name)
{
	try {
		Number ret = getVal(name, name, 0);
		debug(name, "" + ret);
		return ret.doubleValue();
	} catch (RuntimeException e) {
		manageException(name, e);
		return 0;
	}
}

// -------------------------------------------------------------------

/**
 * Read numeric property values, parsing expression if necessary.
 *
 * @param initial
 *          the property name that started this expression evaluation
 * @param property
 *          the current property name to be evaluated
 * @param depth
 *          the depth reached so far
 * @return the evaluation of the expression associated to property
 */
private Number getVal(String initial, String property, int depth)
{
	if (depth > maxdepth) {
		throw new IllegalParameterException(initial,
				"Probable recursive definition - exceeded maximum depth " +
				maxdepth);
	}

	String s = config.getProperty(property);
	if (s == null || s.equals("")) {
		throw new MissingParameterException(property,
				" when evaluating property " + initial);
//						+ "\nPossibly incorrect property: " + getSimilarProperty(property));
	}

	GroupJep jep = new GroupJep(new Operators());
	jep.setAllowUndeclared(true);

	jep.parseExpression(s);
	String[] symbols = getSymbols(jep);
	for (int i = 0; i < symbols.length; i++) {
		Object d = getVal(initial, symbols[i], depth + 1);
		jep.addVariable(symbols[i], d);
	}
	Object ret = jep.getValueAsObject();
	if (jep.hasError())
		System.err.println(jep.getErrorInfo());
	return (Number) ret;
}

// -------------------------------------------------------------------

/**
 * Returns an array of string, containing the symbols contained in the
 * expression parsed by the specified JEP parser.
 * @param jep
 *          the java expression parser containing the list of variables
 * @return an array of strings.
 */
private String[] getSymbols(org.nfunk.jep.JEP jep)
{
	Hashtable h = jep.getSymbolTable();
	String[] ret = new String[h.size()];
	Enumeration e = h.keys();
	int i = 0;
	while (e.hasMoreElements()) {
		ret[i++] = (String) e.nextElement();
	}
	return ret;
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, returns the default
 * value.
 * @param name
 *          Name of configuration property
 * @param def
 *          default value
 */
public String getString(String name, String def)
{
	try {
		return getStr(name);
	} catch (RuntimeException e) {
		manageDefault(name, def, e);
		return def;
	}
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, throws a
 * MissingParameterException. Removes trailing whitespace characters.
 * @param name
 *          Name of configuration property
 */
public String getString(String name)
{
	try {
		return getStr(name);
	} catch (RuntimeException e) {
		manageException(name, e);
		return "";
	}
}

/**
 * The actual method implementing getString().
 */
private String getStr(String name)
{
	String result = config.getProperty(name);
	if (result == null) {
		throw new MissingParameterException(name);
//				"\nPossibly incorrect property: " + getSimilarProperty(name));
	}
	debug(name, "" + result);

	return result.trim();
}

// -------------------------------------------------------------------

/**
 * Reads the given property from the configuration interpreting it as a
 * protocol name. Returns the numeric protocol identifier of this protocol
 * name. See the discussion of protocol name at {@link Configuration} for
 * details on how this numeric id is calculated
 *
 * @param name
 *          Name of configuration property
 * @return the numeric protocol identifier associated to the value of the
 *         property
 */
public int getPid(String name)
{
	try {
		String protname = getStr(name);
		return lookupPid(protname);
	} catch (RuntimeException e) {
		manageException(name, e);
		return 0;
	}
}

// -------------------------------------------------------------------

/**
 * Calls {@link #getPid(String)}, and returns the default if no property
 * is defined with the given name.
 *
 * @param name
 *          Name of configuration property
 * @param pid
 *          the default protocol identifier
 * @return the numeric protocol identifier associated to the value of the
 *         property, or the default if not defined
 */
public int getPid(String name, int pid)
{
	try {
		String protname = getStr(name);
		return lookupPid(protname);
	} catch (RuntimeException e) {
		manageDefault(name, pid, e);
		return pid;
	}
}

// -------------------------------------------------------------------

/**
 * Returns the numeric protocol identifier of the given protocol name.
 *
 * @param protname
 *          the protocol name.
 * @return the numeric protocol identifier associated to the protocol name
 */
public int lookupPid(String protname)
{
	Integer ret = protocols.get(protname);
	if (ret == null) {
		throw new MissingParameterException(Configuration.PAR_PROT + "." + protname);
//				"\nPossibly incorrect property: "
//				+ getSimilarProperty(PAR_PROT + "." + protname));
	}
	return ret.intValue();
}

// -------------------------------------------------------------------

/**
 * Returns the name of a protocol that has the given identifier.
 *

 * Note that this is not a constant time operation in the number of
 * protocols, although typically there are very few protocols defined.
 *
 * @param pid
 *          numeric protocol identifier.
 * @return name of the protocol that has the given id. null if no protocols
 *         have the given id.
 */
public String lookupPid(int pid)
{

	if (!protocols.containsValue(pid))
		return null;
	for (Map.Entry<String, Integer> i : protocols.entrySet()) {
		if (i.getValue().intValue() == pid)
			return i.getKey();
	}

	// never reached but java needs it...
	return null;
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, throws a
 * {@link MissingParameterException}. When creating the Class object, a
 * few attempts are done to resolve the classname. See
 * {@link Configuration} for details.
 * @param name
 *          Name of configuration property
 */
public Class getClass(String name)
{
	try {
		return getClazz(name);
	} catch (RuntimeException e) {
		manageException(name, e);
		return null;
	}
}

private Class getClazz(String name)
{
	String classname = config.getProperty(name);
	if (classname == null) {
		throw new MissingParameterException(name);
//				"\nPossibly incorrect property: " + getSimilarProperty(name));
	}
	debug(name, classname);

	Class c = null;

	try {
		// Maybe classname is just a fully-qualified name
		c = Class.forName(classname);
	} catch (ClassNotFoundException e) {
	}
	if (c == null) {
		// Maybe classname is a non-qualified name?
		String fullname = ClassFinder.getQualifiedName(classname);
		if (fullname != null) {
			try {
				c = Class.forName(fullname);
			} catch (ClassNotFoundException e) {
			}
		}
	}
	if (c == null) {
		// Maybe there are multiple classes with the same
		// non-qualified name.
		String fullname = ClassFinder.getQualifiedName(classname);
		if (fullname != null) {
			String[] names = fullname.split(",");
			if (names.length > 1) {
				for (int i = 0; i < names.length; i++) {
					for (int j = i + 1; j < names.length; j++) {
						if (names[i].equals(names[j])) {
							throw new IllegalParameterException(name,
									"The class " + names[i]
								+ " appears more than once in the classpath; please check"
								+ " your classpath to avoid duplications.");
						}
					}
				}
				throw new IllegalParameterException(name,
						"The non-qualified class name " + classname
								+ "corresponds to multiple fully-qualified classes:" + fullname);
			}
		}
	}
	if (c == null) {
		// Last attempt: maybe the fully classified name is wrong,
		// but the classname is correct.
		String shortname = ClassFinder.getShortName(classname);
		String fullname = ClassFinder.getQualifiedName(shortname);
		if (fullname != null) {
			throw new IllegalParameterException(name, "Class "
					+ classname + " does not exist. Possible candidate(s): " + fullname);
		}
	}
	if (c == null) {
		throw new IllegalParameterException(name, "Class "
				+ classname + " not found");
	}
	return c;
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property. If not found, returns the default
 * value.
 * @param name
 *          Name of configuration property
 * @param def
 *          default value
 * @see #getClass(String)
 */
public Class getClass(String name, Class def)
{

	try {
		return Configuration.getClass(name);
	} catch (RuntimeException e) {
		manageDefault(name, def, e);
		return def;
	}
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property for a class name. It returns an
 * instance of the class. The class must implement a constructor that takes
 * a String as an argument. The value of this string will be <tt>name</tt>.
 * The constructor of the class can see the configuration so it can make
 * use of this name to read its own parameters from it.
 * @param name
 *          Name of configuration property
 * @throws MissingParameterException
 *           if the given property is not defined
 * @throws IllegalParameterException
 *           if there is any problem creating the instance
 */
public Object getInstance(String name)
{
  try {
  	return getInst(name);
  } catch (RuntimeException e) {
		manageException(name, e);
		return null;
  }
}

/**
 * The actual method implementing getInstance().
 */
private Object getInst(String name)
{
	Class c = getClass(name);
	if (c == null)
		return null;
	final String classname = c.getSimpleName();

	try {
		Class pars[] = {String.class};
		Constructor cons = c.getConstructor(pars);
		Object objpars[] = {name};
		return cons.newInstance(objpars);
	} catch (NoSuchMethodException e) {
		throw new IllegalParameterException(name, "Class "
				+ classname + " has no " + classname + "(String) constructor");
	} catch (InvocationTargetException e) {
		if (e.getTargetException() instanceof RuntimeException) {
			throw (RuntimeException) e.getTargetException();
		} else {
			e.getTargetException().printStackTrace();
			throw new RuntimeException("" + e.getTargetException());
		}
	} catch (Exception e) {
		throw new IllegalParameterException(name, e + "");
	}
}

// -------------------------------------------------------------------

/**
 * Reads given configuration property for a class name. It returns an
 * instance of the class. The class must implement a constructor that takes
 * a String as an argument. The value of this string will be <tt>name</tt>.
 * The constructor of the class can see the configuration so it can make
 * use of this name to read its own parameters from it.
 * @param name
 *          Name of configuration property
 * @param def
 *          The default object that is returned if there is no property
 *          defined with the given name
 * @throws IllegalParameterException
 *           if the given name is defined but there is a problem creating
 *           the instance.
 */
public Object getInstance(String name, Object def)
{
  if (!contains(name))
  	return def;
	try {
		return getInst(name);
	} catch (RuntimeException e) {
		manageException(name, e);
		return def;
	}
}

// -------------------------------------------------------------------

/**
 * It returns an array of class instances. The instances are constructed by
 * calling {@link #getInstance(String)} on the names returned by
 * {@link #getNames(String)}.
 * @param name
 *          The component type (i.e. prefix of the list of configuration
 *          properties) which will be passed to {@link #getNames(String)}.
 */
public Object[] getInstanceArray(String name)
{

	String names[] = getNames(name);
	Object[] result = new Object[names.length];

	for (int i = 0; i < names.length; ++i) {
		result[i] = getInstance(names[i]);
	}

	return result;
}

// -------------------------------------------------------------------

/**
 * Returns an array of names prefixed by the specified name. The array is
 * sorted as follows. If there is no config entry
 * {@value peersim.config.Configuration#PAR_INCLUDE}+"."+name or
 * {@value peersim.config.Configuration#PAR_ORDER}+"."+name then the order is
 * alphabetical. Otherwise this entry defines the order. For more
 * information see {@link Configuration}.
 * @param name
 *          the component type (i.e., the prefix)
 * @return the full property names in the order specified by the
 *         configuration
 */
public String[] getNames(String name)
{
	ArrayList<String> ll = new ArrayList<String>();
	final String pref = name + ".";

	Enumeration e = config.propertyNames();
	while (e.hasMoreElements()) {
		String key = (String) e.nextElement();
		if (key.startsWith(pref) && key.indexOf(".", pref.length()) < 0)
			ll.add(key);
	}
	String[] ret = ll.toArray(new String[ll.size()]);
	return order(ret, name);
}

// -------------------------------------------------------------------

/**
 * The input of this method is a set of property names (e.g.
 * initializers, controls and protocols) and a string specifying the type
 * (prefix) of these. The output is in names, which will
 * contain a permutation of the original array. Parameter
 * PAR_INCLUDE+"."+type, or if not present, PAR_ORDER+"."+type is read from
 * the configuration. If none of them are defined then the order is
 * identical to that of names. Otherwise the configuration
 * entry must contain entries from names. It is assumed
 * that the entries in names contain only word characters
 * (alphanumeric and underscore '_'. The order configuration entry thus
 * contains a list of entries from names separated by any
 * non-word characters.
 *

 * It is not required that all entries are listed. If PAR_INCLUDE is used,
 * then only those entries are returned that are listed. If PAR_ORDER is
 * used, then all names are returned, but the array will start with those
 * that are listed. The rest of the names follow in alphabetical order.
 *
 *
 * @param names
 *          the set of property names to be searched
 * @param type
 *          the string identifying the particular set of properties to be
 *          inspected
 */
private String[] order(String[] names, String type)
{
	String order = getString(Configuration.PAR_INCLUDE + "." + type, null);
	boolean include = order != null;
	if (!include)
		order = getString(Configuration.PAR_ORDER + "." + type, null);

	int i = 0;
	if (order != null && !order.equals("")) {
		// split around non-word characters
		String[] sret = order.split("\\W+");
		for (; i < sret.length; i++) {
			int j = i;
			for (; j < names.length; ++j)
				if (names[j].equals(type + "." + sret[i]))
					break;
			if (j == names.length) {
				throw new IllegalParameterException(
						(include ? Configuration.PAR_INCLUDE : Configuration.PAR_ORDER)
						+ "." + type, type + "." + sret[i] + " is not defined.");
			} else // swap the element to current position
			{
				String tmps = names[j];
				names[j] = names[i];
				names[i] = tmps;
			}
		}
	}

	Arrays.sort(names, i, names.length);
	int retsize = (include ? i : names.length);
	String[] ret = new String[retsize];
	for (int j = 0; j < retsize; ++j)
		ret[j] = names[j];
	return ret;
}

// -------------------------------------------------------------------

/**
 * Print debug information for configuration. The amount of information
 * depends on the debug level DEBUG. 0 = nothing 1 = just the config name 2 =
 * config name plus method calling
 *
 * @param name
 */
private void debug(String name, String result)
{
	if (debugLevel == DEBUG_NO)
		return;
	StringBuffer buffer = new StringBuffer();
	buffer.append("DEBUG ");
	buffer.append(name);
	buffer.append(" = ");
	buffer.append(result);

	// Additional info
	if (debugLevel == DEBUG_CONTEXT) {

		buffer.append("\n  at ");
		// Obtain the stack trace
		StackTraceElement[] stack = null;
		try {
			throw new Exception();
		} catch (Exception e) {
			stack = e.getStackTrace();
		}

		// Search the element that invoked Configuration
		// It's the first whose class is different from Configuration
		int pos;
		for (pos = 0; pos < stack.length; pos++) {
			if (!stack[pos].getClassName().equals(Configuration.class.getName()))
				break;
		}

		buffer.append(stack[pos].getClassName());
		buffer.append(":");
		buffer.append(stack[pos].getLineNumber());
		buffer.append(", method ");
		buffer.append(stack[pos - 1].getMethodName());
		buffer.append("()");
	}

	System.err.println(buffer);
}

// -------------------------------------------------------------------

/**
 * @return an array of adjacent letter pairs contained in the input string
 *         http://www.catalysoft.com/articles/StrikeAMatch.html
 */
private String[] letterPairs(String str)
{
	int numPairs = str.length() - 1;
	String[] pairs = new String[numPairs];
	for (int i = 0; i < numPairs; i++) {
		pairs[i] = str.substring(i, i + 2);
	}
	return pairs;
}

// -------------------------------------------------------------------

/**
 * @return an ArrayList of 2-character Strings.
 *         http://www.catalysoft.com/articles/StrikeAMatch.html
 */
private ArrayList<String> wordLetterPairs(String str)
{
	ArrayList<String> allPairs = new ArrayList<String>();
	// Tokenize the string and put the tokens/words into an array
	String[] words = str.split("\\s");
	// For each word
	for (int w = 0; w < words.length; w++) {
		// Find the pairs of characters
		String[] pairsInWord = letterPairs(words[w]);
		for (int p = 0; p < pairsInWord.length; p++) {
			allPairs.add(pairsInWord[p]);
		}
	}
	return allPairs;
}

// -------------------------------------------------------------------

/**
 * @return lexical similarity value in the range [0,1]
 *         http://www.catalysoft.com/articles/StrikeAMatch.html
 */
private double compareStrings(String str1, String str2)
{
	ArrayList pairs1 = wordLetterPairs(str1.toUpperCase());
	ArrayList pairs2 = wordLetterPairs(str2.toUpperCase());
	int intersection = 0;
	int union_ = pairs1.size() + pairs2.size();
	for (int i = 0; i < pairs1.size(); i++) {
		Object pair1 = pairs1.get(i);
		for (int j = 0; j < pairs2.size(); j++) {
			Object pair2 = pairs2.get(j);
			if (pair1.equals(pair2)) {
				intersection++;
				pairs2.remove(j);
				break;
			}
		}
	}
	return (2.0 * intersection) / union_;
}

// -------------------------------------------------------------------

/**
 * Among the defined properties, returns the one more similar to String
 * property
 */
private String getSimilarProperty(String property)
{
	String bestProperty = null;
	double bestValue = 0.0;
	Enumeration e = config.keys();
	while (e.hasMoreElements()) {
		String key = (String) e.nextElement();
		double compare = compareStrings(key, property);
		if (compare > bestValue) {
			bestValue = compare;
			bestProperty = key;
		}
	}
	return bestProperty;
}

//-------------------------------------------------------------------

private void manageDefault(String name, Object def,
		RuntimeException e)
{
	debug(name, "" + def + " (DEFAULT)");
	if (check) {
		System.out.println("Warning: Property " + name + " = " +
				def + " (DEFAULT)");
	}
	if (e instanceof MissingParameterException) {
		// Do nothing
	} else {
		manageException(name, e);
	}
}

//-------------------------------------------------------------------

private void manageException(String name, RuntimeException e)
{
	if (check) {
		if (e instanceof MissingParameterException) {
			// Print just the short message in this case
			System.out.println("Error: " +
					((MissingParameterException) e).getShortMessage());
		} else if (e instanceof IllegalParameterException) {
			// Print just the short message in this case
			System.out.println("Error: " +
					((IllegalParameterException) e).getShortMessage());
		} else {
			System.out.println("Error: " + e.getMessage());
		}
	} else {
		throw e;
	}
}

//-------------------------------------------------------------------

}


text:
namespace blink {

class ProgrammaticScrollTest : public testing::Test {
 public:
  ProgrammaticScrollTest() : base_url_("http://www.test.com/") {}

  void TearDown() override {
    url_test_helpers::UnregisterAllURLsAndClearMemoryCache();
  }

 protected:
  void RegisterMockedHttpURLLoad(const String& file_name) {
    // TODO(crbug.com/751425): We should use the mock functionality
    // via the WebViewHelper instance in each test case.
    url_test_helpers::RegisterMockedURLLoadFromBase(
        WebString(base_url_), test::CoreTestDataPath(), WebString(file_name));
  }

  String base_url_;
};

TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithScale) {
  RegisterMockedHttpURLLoad("long_scroll.html");

  frame_test_helpers::WebViewHelper web_view_helper;
  WebViewImpl* web_view =
      web_view_helper.InitializeAndLoad(base_url_.Utf8() + "long_scroll.html");
  web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
  web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
      DocumentUpdateReason::kTest);

  FrameLoader& loader = web_view->MainFrameImpl()->GetFrame()->Loader();
  loader.GetDocumentLoader()->SetLoadType(WebFrameLoadType::kBackForward);

  web_view->SetPageScaleFactor(3.0f);
  web_view->MainFrameImpl()->SetScrollOffset(WebSize(0, 500));
  loader.GetDocumentLoader()->GetInitialScrollState().was_scrolled_by_user =
      false;
  loader.GetDocumentLoader()->GetHistoryItem()->SetPageScaleFactor(2);
  loader.GetDocumentLoader()->GetHistoryItem()->SetScrollOffset(
      ScrollOffset(0, 200));

  // Flip back the wasScrolledByUser flag which was set to true by
  // setPageScaleFactor because otherwise
  // FrameLoader::restoreScrollPositionAndViewState does nothing.
  loader.GetDocumentLoader()->GetInitialScrollState().was_scrolled_by_user =
      false;
  loader.RestoreScrollPositionAndViewState();
  web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
      DocumentUpdateReason::kTest);

  // Expect that both scroll and scale were restored.
  EXPECT_EQ(2.0f, web_view->PageScaleFactor());
  EXPECT_EQ(200, web_view->MainFrameImpl()->GetScrollOffset().height);
}

TEST_F(ProgrammaticScrollTest, RestoreScrollPositionAndViewStateWithoutScale) {
  RegisterMockedHttpURLLoad("long_scroll.html");

  frame_test_helpers::WebViewHelper web_view_helper;
  WebViewImpl* web_view =
      web_view_helper.InitializeAndLoad(base_url_.Utf8() + "long_scroll.html");
  web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
  web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
      DocumentUpdateReason::kTest);

  FrameLoader& loader = web_view->MainFrameImpl()->GetFrame()->Loader();
  loader.GetDocumentLoader()->SetLoadType(WebFrameLoadType::kBackForward);

  web_view->SetPageScaleFactor(3.0f);
  web_view->MainFrameImpl()->SetScrollOffset(WebSize(0, 500));
  loader.GetDocumentLoader()->GetInitialScrollState().was_scrolled_by_user =
      false;
  loader.GetDocumentLoader()->GetHistoryItem()->SetPageScaleFactor(0);
  loader.GetDocumentLoader()->GetHistoryItem()->SetScrollOffset(
      ScrollOffset(0, 400));

  // FrameLoader::restoreScrollPositionAndViewState flows differently if scale
  // is zero.
  loader.RestoreScrollPositionAndViewState();
  web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
      DocumentUpdateReason::kTest);

  // Expect that only the scroll position was restored.
  EXPECT_EQ(3.0f, web_view->PageScaleFactor());
  EXPECT_EQ(400, web_view->MainFrameImpl()->GetScrollOffset().height);
}

TEST_F(ProgrammaticScrollTest, SaveScrollStateClearsAnchor) {
  RegisterMockedHttpURLLoad("long_scroll.html");

  frame_test_helpers::WebViewHelper web_view_helper;
  WebViewImpl* web_view =
      web_view_helper.InitializeAndLoad(base_url_.Utf8() + "long_scroll.html");
  web_view->MainFrameWidget()->Resize(WebSize(1000, 1000));
  web_view->MainFrameWidget()->UpdateAllLifecyclePhases(
      DocumentUpdateReason::kTest);

  FrameLoader& loader = web_view->MainFrameImpl()->GetFrame()->Loader();
  loader.GetDocumentLoader()->SetLoadType(WebFrameLoadType::kBackForward);

  web_view->MainFrameImpl()->SetScrollOffset(WebSize(0, 500));
  loader.GetDocumentLoader()->GetInitialScrollState().was_scrolled_by_user =
      true;
  loader.SaveScrollState();
  loader.SaveScrollAnchor();

  web_view->MainFrameImpl()->SetScrollOffset(WebSize(0, 0));
  loader.SaveScrollState();
  loader.GetDocumentLoader()->GetInitialScrollState().was_scrolled_by_user =
      false;

  loader.RestoreScrollPositionAndViewState();

  EXPECT_EQ(0, web_view->MainFrameImpl()->GetScrollOffset().height);
}

class ProgrammaticScrollSimTest : public SimTest {};

TEST_F(ProgrammaticScrollSimTest, NavigateToHash) {
  WebView().MainFrameWidget()->Resize(WebSize(800, 600));
  SimRequest main_resource("https://example.com/test.html#target", "text/html");
  SimSubresourceRequest css_resource("https://example.com/test.css",
                                     "text/css");

  LoadURL("https://example.com/test.html#target");

  // Finish loading the main document before the stylesheet is loaded so that
  // rendering is blocked when parsing finishes. This will delay closing the
  // document until the load event.
  main_resource.Write(
      "<!DOCTYPE html><link id=link rel=stylesheet href=test.css>");
  css_resource.Start();
  main_resource.Write(R"HTML(

Target

  )HTML");
  main_resource.Finish();
  css_resource.Complete();

  // Run pending tasks to fire the load event and close the document. This
  // should cause the document to scroll to the hash.
  test::RunPendingTasks();
  Compositor().BeginFrame();

  ScrollableArea* layout_viewport = GetDocument().View()->LayoutViewport();
  EXPECT_EQ(3000, layout_viewport->GetScrollOffset().Height());
}

}  // namespace blink

redpajama_set_name: RedPajamaGithub


text:
package cs.man.ac.uk.tavernamobile.serverresource.xml;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Order;
import org.simpleframework.xml.Root;

@Root(name = "serverDescription")
@Namespace(reference = "http://ns.taverna.org.uk/2010/xml/server/rest/")
@Order(elements={"runs", "policy", "feed"})
public class ServerDescription extends VersionedElement {

	@Element(required = false)
	protected Location runs;

	@Element(required = false)
    protected Location policy;

	@Element(required = false)
    protected Location feed;

	public Location getRuns() {
		return runs;
	}
	public void setRuns(Location runs) {
		this.runs = runs;
	}
	public Location getPolicy() {
		return policy;
	}
	public void setPolicy(Location policy) {
		this.policy = policy;
	}
	public Location getFeed() {
		return feed;
	}
	public void setFeed(Location feed) {
		this.feed = feed;
	}
}


text:
# evenity
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard)
[![travis][travis-image]][travis-url]
[![npm][npm-image]][npm-url]
[![downloads][downloads-image]][downloads-url]

[travis-image]: https://img.shields.io/travis/nopnop/evenity.svg?style=flat&branch=master
[travis-url]: https://travis-ci.org/nopnop/evenity
[npm-image]: https://img.shields.io/npm/v/evenity.svg?style=flat
[npm-url]: https://npmjs.org/package/evenity
[downloads-image]: https://img.shields.io/npm/dm/evenity.svg?style=flat
[downloads-url]: https://npmjs.org/package/evenity

Unified event attachment utility

## Features

  - Attach event to any kind of event-enabled object
  - Same event API for both node-like event emitter instance and html element
  - Return a closable object to detach event

## Getting Started
Install the module with: `npm install --save evenity`

```javascript
var evenity = require('evenity')
var EventEmitter = require('events').EventEmitter

var el = document.createElement('div')
var obj = new EventEmitter()

function handler(event) {
  // ...
  // event.detail contain the emitted datas
}

// Attach event on any eventemitter-kind object
var eventOnElement = evenity.on(el, 'myevent', handler)
var eventOnObject = evenity.on(obj, 'myevent', handler)

// Attach event once
evenity.once( /* ... */ )

// Detach event
evenity.off(el, 'myevent', handler)
evenity.off(obj, 'myevent', handler)

// Emit event
evenity.emit(el, 'click', {foo:'bar'})
//  {foo:'bar'} is the detail of the CustomEvent for HTMLElement

// Detach event using close method returned by evenity
eventOnElement.close()
eventOnObject.close()

```

## API

### evenity.on()
`evenity.on({EventEmitter|HTMLElement} obj, {String} eventname, {Function} handler) => {Object} closable`

Attach an event handler to an object. If `obj` is an `HTMLElement` the `handler` will receive an event object. Else, `handler` receive the emitted data.

The returned `closable` object has a `closable.close()` method to detach the handler:

```javascript
var e = evenity.on(obj, 'eventname', function(event) { /* handle event.detail */ } )
e.close() // Detach event handler
```

### evenity.once()
`evenity.once({EventEmitter|HTMLElement} obj, {String} eventname, {Function} handler)`

Same as `evenity.on()` but the handler is called only once, then the event is automatically
detached

### evenity.off()
`evenity.off({EventEmitter|HTMLElement} obj, {String} eventname, {Function} handler)`

Detach an event handler

### evenity.emit()
`evenity.emit({EventEmitter|HTMLElement} obj, {String|CustomEvent} eventnameOrCustomEvent, [{mixed|Event} data])`

Emit an event. If `obj` is an HTMLElement, then a `CustomEvent` is emitted with data as detail. If data is a `window.Event instance` then

```javascript
evenity.emit(el, 'myEvent', { foo: 'bar' })
evenity.emit(el, new CustomEvent('myEvent', { detail: {}, bubbles: true, cancelable: true }))
var canceled = !evenity.emit(el, new MouseEvent('click', { view: window, bubbles: true, cancelable: true }))
```

---

[The MIT License](./LICENSE)

[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)


text:
filename: /packages/material-ui/src/CardActionArea/CardActionArea.js
---

# CardActionArea API

The API documentation of the CardActionArea React component. Learn more about the props and the CSS customization points.

## Import

```js
import CardActionArea from '@material-ui/core/CardActionArea';
// or
import { CardActionArea } from '@material-ui/core';
```

You can learn more about the difference by [reading this guide](/guides/minimizing-bundle-size/).

## Component name

The `MuiCardActionArea` name can be used for providing [default props](/customization/globals/#default-props) or [style overrides](/customization/globals/#css) at the theme level.

## Props

| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| children | node |  | The content of the component. |
| classes | object |  | Override or extend the styles applied to the component. See [CSS API](#css) below for more details. |

The `ref` is forwarded to the root element.

Any other props supplied will be provided to the root element ([ButtonBase](/api/button-base/)).

## CSS

| Rule name | Global class | Description |
|:-----|:-------------|:------------|
| root | .MuiCardActionArea-root | Styles applied to the root element.
| focusVisible | .Mui-focusVisible | Pseudo-class applied to the ButtonBase root element if the action area is keyboard focused.
| focusHighlight | .MuiCardActionArea-focusHighlight | Styles applied to the overlay that covers the action area when it is keyboard focused.

You can override the style of the component thanks to one of these customization points:

- With a rule name of the [`classes` object prop](/customization/components/#overriding-styles-with-classes).
- With a [global class name](/customization/components/#overriding-styles-with-global-class-names).
- With a theme and an [`overrides` property](/customization/globals/#css).

If that's not sufficient, you can check the [implementation of the component](https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/CardActionArea/CardActionArea.js) for more detail.

## Inheritance

The props of the [ButtonBase](/api/button-base/) component are also available.
You can take advantage of this behavior to [target nested components](/guides/api/#spread).

## Demos

- [Cards](/components/cards/)


text:
https://www.quora.com/How-can-I-recover-a-file-I-deleted-in-my-local-repo-from-the-remote-repo-in-Git

* If the deletion has not been committed, the command below will restore the deleted file in the working tree.

```
$ git checkout -- <file>
```

* You can get a list of all the deleted files in the working tree using the command below.

```
$ git ls-files --deleted
```

* If the deletion has been committed, find the commit where it happened, then recover the file from this commit.

```
$ git rev-list -n 1 HEAD -- <file>
$ git checkout <commit>^ -- <file>
```

* In case you are looking for the path of the file to recover, the following command will display a summary of all deleted files.

```
$ git log --diff-filter=D --summary
```

*[ How to list all the files in a commit?](https://stackoverflow.com/questions/424071/how-to-list-all-the-files-in-a-commit)

```
% git diff-tree --no-commit-id --name-only  -r bdfec3
```


text:
import React from "react";
import { Text } from "@chakra-ui/react";

type BlogCustomDateProps = {
  date: Date;
};

export const BlogCustomDate: React.FC<BlogCustomDateProps> = (props) => {
  const { date } = props;
  return (
    <Text fontSize="xl" marginTop="0.75rem" as="span">
      {new Date(date).toLocaleDateString()}
    </Text>
  );
};


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class SteamApiLogin extends CI_Controller {

	public function login()
	{
		$openid = new Openid();
		try{
			  $button['small'] = "small";
		    $button['large_no'] = "large_noborder";
		    $button['large'] = "large_border";
		    $button = $button[button_style];
			if(!$openid->mode) {
		        if(isset($_GET['login'])) {
		            $openid->identity = 'http://steamcommunity.com/openid';
		            header('Location: ' . $openid->authUrl());
		        }

			    $data['form'] = "<form action=\"?login\" method=\"post\"> <input type=\"image\" src=\"http://cdn.steamcommunity.com/public/images/signinthroughsteam/sits_".$button.".png\"></form>";
			    $this->load->view('home',$data);
			    }

			}elseif($openid->mode == 'cancel') {
	        echo 'User has canceled authentication!';
		    } else {
		        if($openid->validate()) {
		                $id = $openid->identity;
		                $ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/";
		                preg_match($ptn, $id, $matches);

		                $_SESSION['steamid'] = $matches[1];

		                //Determine the return to page. We substract "login&"" to remove the login var from the URL.
		                //"file.php?login&foo=bar" would become "file.php?foo=bar"
		                $returnTo = str_replace('login&', '', $_GET['openid_return_to']);
		                //If it didn't change anything, it means that there's no additionals vars, so remove the login var so that we don't get redirected to Steam over and over.
		                if($returnTo === $_GET['openid_return_to']) $returnTo = str_replace('?login', '', $_GET['openid_return_to']);
		                header('Location: '.$returnTo);
		        } else {
		                echo "User is not logged in.\n";
		        }

		    }
		} catch(ErrorException $e) {
		    echo $e->getMessage();
		}
	}

	public function logout()
	{

        $this->session->sess_destroy();
	}

}


text: Return on investment on property


text:
class PlinkSNPItem:
  def __init__(self, row):
    parts = row.split('\t')
    self.Chromosome = parts[0]
    self.Name = parts[1]
    self.Position = parts[3];
    self.MinorAllele = parts[4]
    self.MajorAllele = parts[5]
    self.Locus = self.Chromosome + "_" + self.Position
    self.MinorKey = self.Locus + "_" + self.MinorAllele + "_" + self.MajorAllele
    self.MajorKey = self.Locus + "_" + self.MajorAllele + "_" + self.MinorAllele

def readPlinkSNP(bimFile):
  result = list()
  with open(bimFile, "r") as f:
    for row in f:
      item = PlinkSNPItem(row.rstrip())
      result.append(item)
  return(result)


text:
import os
import pytest
import graphviz

from .context import graphlink
from .context import OUTPUT_TEST_PATH

from graphlink.core.gk_node import GKNode
from graphlink.core.gk_node import GK_SHAPE_TYPE

@pytest.fixture()
def get_test_data_folder():
    return os.path.join(os.path.dirname(os.path.realpath(__file__)), "data")

def test_graphviz():
    dot = graphviz.Digraph(comment='test_graph')
    dot.node("A")
    dot.node("B")
    dot.node("C")
    dot.edges(['AB', 'BC'])
    dot.render(filename=os.path.join(OUTPUT_TEST_PATH, "test_graph1.gv"))
    assert os.path.exists(os.path.join(OUTPUT_TEST_PATH, "test_graph1.gv"))

def test_gknode():
    mym1 = GKNode("test1")
    mym2 = GKNode("test2")

    dot = graphviz.Graph(comment='test_graph2')
    mym1.create_node(dot)
    mym2.create_node(dot)
    dot.edge('test1', 'test2')
    dot.render(filename=os.path.join(OUTPUT_TEST_PATH, "test_graph2.gv"))
    assert os.path.exists(os.path.join(OUTPUT_TEST_PATH, "test_graph2.gv"))

def test_gknode_init():
    mym1 = GKNode()
    assert mym1.m_name is None
    assert mym1.m_description is None
    assert mym1.m_shapetype == GK_SHAPE_TYPE[0]
    assert mym1.m_external_link is None

    mym2 = GKNode("coucou", shape=GK_SHAPE_TYPE[2])
    assert mym2.m_name == "coucou"
    assert mym2.m_shapetype == GK_SHAPE_TYPE[2]
    assert mym2.m_external_link is None
    assert mym2.m_description is None

def test_gknode_image(get_test_data_folder):
    mym1 = GKNode("Chief")
    assert mym1.set_image("not_existing_picture.png") is False

    img_path = os.path.join(get_test_data_folder, "person-icon.jpg")
    assert mym1.set_image(img_path) is True
    assert mym1.m_shapetype == GK_SHAPE_TYPE[4]  # image
    assert mym1.m_external_link == img_path

    mym3 = GKNode("John", img_path)
    assert mym3.m_external_link == img_path

    mym2 = GKNode("Bob", img_path)
    assert mym2.m_external_link == img_path
    mym4 = GKNode("+41791234567")

    # test printing with image
    dot = graphviz.Graph()

    mym1.create_node(dot)
    mym2.create_node(dot)
    mym3.create_node(dot)

    dot.edge(mym1.m_name, mym2.m_name)
    dot.edge(mym1.m_name, mym3.m_name)
    dot.edge(mym3.m_name, mym4.m_name)
    dot.edge(mym4.m_name, mym2.m_name)

    dot.render(filename=os.path.join(OUTPUT_TEST_PATH, "test_img1.gv"))
    assert os.path.exists(os.path.join(OUTPUT_TEST_PATH, "test_img1.gv"))

def test_gknode_save():
    testfile = os.path.join(OUTPUT_TEST_PATH, "save_test_file.gkn")
    os.remove(testfile) if os.path.exists(testfile) else None

    mym1 = GKNode("John", shape=GK_SHAPE_TYPE[2])
    assert mym1.save_to_file(testfile) is True

def test_gknode_load():
    mym2 = GKNode()
    assert mym2.load_from_file("toto") is False
    assert mym2.load_from_file(os.path.join(OUTPUT_TEST_PATH, "save_test_file.gkn")) is True
    assert mym2.m_name == "John"
    assert mym2.m_shapetype == GK_SHAPE_TYPE[2]


text:
import { BROWSING_HISTORY_ILLUSTS } from '../constants/actionTypes';

export function addBrowsingHistoryIllusts(item) {
  return {
    type: BROWSING_HISTORY_ILLUSTS.ADD,
    payload: {
      item,
    },
  };
}

export function removeBrowsingHistoryIllusts(item) {
  return {
    type: BROWSING_HISTORY_ILLUSTS.REMOVE,
    payload: {
      item,
    },
  };
}

export function clearBrowsingHistoryIllusts() {
  return {
    type: BROWSING_HISTORY_ILLUSTS.CLEAR,
  };
}


text:
class CaptionDefProto;
class CircleRuleProto;
class ShieldRuleProto;
class SymbolRuleProto;

//#define CALC_FILTERED_POINTS

namespace df
{

struct TextViewParams;
class MapShape;

using TInsertShapeFn = function<void(drape_ptr<MapShape> && shape)>;

class BaseApplyFeature
{
public:
  BaseApplyFeature(TInsertShapeFn const & insertShape, FeatureID const & id,
                   int minVisibleScale, uint8_t rank, CaptionDescription const & captions);

  virtual ~BaseApplyFeature() {}

protected:
  void ExtractCaptionParams(CaptionDefProto const * primaryProto,
                            CaptionDefProto const * secondaryProto,
                            double depth, TextViewParams & params) const;

  TInsertShapeFn m_insertShape;
  FeatureID m_id;
  CaptionDescription const & m_captions;
  int m_minVisibleScale;
  uint8_t m_rank;
};

class ApplyPointFeature : public BaseApplyFeature
{
  using TBase = BaseApplyFeature;

public:
  ApplyPointFeature(TInsertShapeFn const & insertShape, FeatureID const & id,
                    int minVisibleScale, uint8_t rank, CaptionDescription const & captions);

  void operator()(m2::PointD const & point);
  void ProcessRule(Stylist::TRuleWrapper const & rule);
  void Finish();

private:
  bool m_hasPoint;
  double m_symbolDepth;
  double m_circleDepth;
  SymbolRuleProto const * m_symbolRule;
  CircleRuleProto const * m_circleRule;
  m2::PointF m_centerPoint;
};

class ApplyAreaFeature : public ApplyPointFeature
{
  using TBase = ApplyPointFeature;

public:
  ApplyAreaFeature(TInsertShapeFn const & insertShape, FeatureID const & id,
                   int minVisibleScale, uint8_t rank, CaptionDescription const & captions);

  using TBase::operator ();

  void operator()(m2::PointD const & p1, m2::PointD const & p2, m2::PointD const & p3);
  void ProcessRule(Stylist::TRuleWrapper const & rule);

private:
  vector<m2::PointF> m_triangles;
};

class ApplyLineFeature : public BaseApplyFeature
{
  using TBase = BaseApplyFeature;

public:
  ApplyLineFeature(TInsertShapeFn const & insertShape, FeatureID const & id,
                   int minVisibleScale, uint8_t rank, CaptionDescription const & captions,
                   double currentScaleGtoP, bool simplify, size_t pointsCount);

  void operator() (m2::PointD const & point);
  bool HasGeometry() const;
  void ProcessRule(Stylist::TRuleWrapper const & rule);
  void Finish();

private:
  m2::SharedSpline m_spline;
  double m_currentScaleGtoP;
  double m_sqrScale;
  m2::PointD m_lastAddedPoint;
  bool m_simplify;
  size_t m_initialPointsCount;
  double m_shieldDepth;
  ShieldRuleProto const * m_shieldRule;

#ifdef CALC_FILTERED_POINTS
  int m_readedCount;
#endif
};

} // namespace df


text:
package org.darkestapp.money_exchange_rater.api.c_cex.processors;

import org.darkestapp.money_exchange_rater.api.c_cex.util.CCexCurrencyPair;
import org.darkestapp.money_exchange_rater.interfaces.MoneyExchangeRaterException;
import org.junit.Test;

import static org.darkestapp.money_exchange_rater.enums.PublicCurrencyCode.ARS;
import static org.darkestapp.money_exchange_rater.enums.PublicCurrencyCode.BTC;
import static org.darkestapp.money_exchange_rater.enums.PublicCurrencyCode.USD;
import static org.hamcrest.number.OrderingComparison.greaterThan;
import static org.junit.Assert.*;

/**
 * Created by Manuel Perez P. (darkpriestrelative@gmail.com) on 16/04/17.
 */
public class JsonCCexParserTest {

    private JsonCCexParser parser = new JsonCCexParser(JsonCCexParser.class);
    private CCexCurrencyPair validCurrencyPair = new CCexCurrencyPair(BTC, USD);

    @Test
    public void getDefaultApiObjectTest() throws Exception {

        CCexObject cCexObject = parser.getApiObject(validCurrencyPair);
        assertNotNull(cCexObject);
        assertEquals(validCurrencyPair, cCexObject.getCurrencyPair());
        assertThat(cCexObject.getBuyPrice().longValue(), greaterThan(0L));
        assertThat(cCexObject.getSellPrice().longValue(), greaterThan(0L));
        assertThat(cCexObject.getRequestTime().getTime(), greaterThan(0L));
    }

    @Test(expected = MoneyExchangeRaterException.class)
    public void getDefaultApiURLObjectInvalidCurrentPairTest() throws Exception {

        CCexCurrencyPair invalidCurrencyPair = new CCexCurrencyPair(ARS, USD);
        parser.getApiObject(invalidCurrencyPair);
    }

    @Test(expected = MoneyExchangeRaterException.class)
    public void getOtherValidApiURLObjectTest() throws Exception {

        parser.getApiObject(
                "https://c-cex.com/t/api_pub.html?a=getmarketsummaries",
                validCurrencyPair);
    }

    @Test(expected = MoneyExchangeRaterException.class)
    public void getApiObjectMalformedURLTest() throws Exception {

        parser.getApiObject("Malformed URL", validCurrencyPair);
    }

    @Test(expected = MoneyExchangeRaterException.class)
    public void getApiObjectNullURLTest() throws Exception {

        parser.getApiObject(null, validCurrencyPair);
    }

}


text:
//
//  UIViewController+JWTitleView.m
//  leshi-OA
//
//  Created by administrator on 16/4/20.
//  Copyright © 2016年 YANGWW. All rights reserved.
//

#import "UIViewController+JWTitleView.h"
#import <objc/runtime.h>

@interface UIViewController ()

/**
 *  当前UIViewController如果已创建了JWTitleView,则jwtitleView不为空;jwtitleView用于避免同一个UIViewController中JWTitleView重复创建;
 */
@property (weak,nonatomic) UIView *jwtitleView;

@property (strong,nonatomic) UIView *originTitleView;

@property  (strong,nonatomic) NSString *originTitle;

/**
 *  加载计数
 */
@property (assign,atomic) int loadCount;

@end

@implementation UIViewController (JWTitleView)

-(int)loadCount{
    return [objc_getAssociatedObject(self, @selector(loadCount)) intValue];
}

-(void)setLoadCount:(int)loadCount{
    objc_setAssociatedObject(self, @selector(loadCount), @(loadCount), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIView *)jwtitleView{
    return objc_getAssociatedObject(self, @selector(jwtitleView));
}

-(void)setJwtitleView:(UIView *)jwtitleView{
    objc_setAssociatedObject(self, @selector(jwtitleView), jwtitleView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIView *)originTitleView{
    return objc_getAssociatedObject(self, @selector(originTitleView));
}

-(void)setOriginTitleView:(UIView *)originTitleView{
    objc_setAssociatedObject(self, @selector(originTitleView), originTitleView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSString *)originTitle{
    return objc_getAssociatedObject(self, @selector(originTitle));
}

-(void)setOriginTitle:(NSString *)originTitle{
    objc_setAssociatedObject(self, @selector(originTitle), originTitle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

-(void)loadingData{

    [self loadingDataForTitle:@"接收数据..."];
}

-(void)loadingDataForTitle:(NSString *)title{

    self.loadCount++;

    if(self.jwtitleView){
        return;
    }

    // save origin view
    if (self.navigationItem.titleView) {
        self.originTitleView = self.navigationItem.titleView;
    }else if(self.navigationItem.title){
        self.originTitle = self.navigationItem.title;
    }

    UIView * titleView = [[UIView alloc] init];

    UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activity.frame = CGRectMake(0, 13, activity.frame.size.width, activity.frame.size.height);
    [activity startAnimating];
    [titleView addSubview:activity];

    UILabel *titleLabel = [[UILabel alloc] init];
    [titleView addSubview:titleLabel];
    titleLabel.text = title;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font  = [UIFont boldSystemFontOfSize:18];

    CGSize size = [titleLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT,30) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18]} context:nil].size;

    titleLabel.frame = CGRectMake(activity.bounds.size.width + 5,12,size.width,size.height);

    titleView.frame = CGRectMake(0, 0,activity.bounds.size.width + 5 + size.width, 44);

    self.navigationItem.titleView = titleView;
    self.jwtitleView = titleView;

}

-(void)LoadComplete{

    self.loadCount--;

    if (self.loadCount != 0) {
        return;
    }

    self.navigationItem.titleView = nil;
    self.jwtitleView = nil;

    if (self.originTitleView) {
        self.navigationItem.titleView = self.originTitleView;
    }else if(self.originTitle){
        self.navigationItem.title = self.originTitle;
    }

}

@end


text:
import re
import time
from threading import Lock

from mycroft.configuration import Configuration
from mycroft.metrics import report_timing, Stopwatch
from mycroft.tts import TTSFactory
from mycroft.util import check_for_signal
from mycroft.util.log import LOG
from mycroft.messagebus.message import Message
from mycroft.tts.remote_tts import RemoteTTSException
from mycroft.tts.mimic_tts import Mimic

bus = None  # Mycroft messagebus connection
config = None
tts = None
tts_hash = None
lock = Lock()
mimic_fallback_obj = None

_last_stop_signal = 0

def handle_speak(event):
    """Handle "speak" message

    Parse sentences and invoke text to speech service.
    """
    config = Configuration.get()
    Configuration.set_config_update_handlers(bus)
    global _last_stop_signal

    # if the message is targeted and audio is not the target don't
    # don't synthezise speech
    event.context = event.context or {}
    if event.context.get('destination') and not \
            ('debug_cli' in event.context['destination'] or
             'audio' in event.context['destination']):
        return

    # Get conversation ID
    if event.context and 'ident' in event.context:
        ident = event.context['ident']
    else:
        ident = 'unknown'

    start = time.time()  # Time of speech request
    with lock:
        stopwatch = Stopwatch()
        stopwatch.start()
        utterance = event.data['utterance']
        listen = event.data.get('expect_response', False)
        # This is a bit of a hack for Picroft.  The analog audio on a Pi blocks
        # for 30 seconds fairly often, so we don't want to break on periods
        # (decreasing the chance of encountering the block).  But we will
        # keep the split for non-Picroft installs since it give user feedback
        # faster on longer phrases.
        #
        # TODO: Remove or make an option?  This is really a hack, anyway,
        # so we likely will want to get rid of this when not running on Mimic
        if (config.get('enclosure', {}).get('platform') != "picroft" and
                len(re.findall('<[^>]*>', utterance)) == 0):
            chunks = tts.preprocess_utterance(utterance)
            # Apply the listen flag to the last chunk, set the rest to False
            chunks = [(chunks[i], listen if i == len(chunks) - 1 else False)
                      for i in range(len(chunks))]
            for chunk, listen in chunks:
                # Check if somthing has aborted the speech
                if (_last_stop_signal > start or
                        check_for_signal('buttonPress')):
                    # Clear any newly queued speech
                    tts.playback.clear()
                    break
                try:
                    mute_and_speak(chunk, ident, listen)
                except KeyboardInterrupt:
                    raise
                except Exception:
                    LOG.error('Error in mute_and_speak', exc_info=True)
        else:
            mute_and_speak(utterance, ident, listen)

        stopwatch.stop()
    report_timing(ident, 'speech', stopwatch, {'utterance': utterance,
                                               'tts': tts.__class__.__name__})

def mute_and_speak(utterance, ident, listen=False):
    """Mute mic and start speaking the utterance using selected tts backend.

    Args:
        utterance:  The sentence to be spoken
        ident:      Ident tying the utterance to the source query
    """
    global tts_hash
    # update TTS object if configuration has changed
    if tts_hash != hash(str(config.get('tts', ''))):
        global tts
        # Create new tts instance
        if tts:
            tts.playback.detach_tts(tts)
        tts = TTSFactory.create()
        tts.init(bus)
        tts_hash = hash(str(config.get('tts', '')))

    LOG.info("Speak: " + utterance)
    try:
        tts.execute(utterance, ident, listen)
    except RemoteTTSException as e:
        LOG.error(e)
        mimic_fallback_tts(utterance, ident, listen)
    except Exception:
        LOG.exception('TTS execution failed.')

def _get_mimic_fallback():
    """Lazily initializes the fallback TTS if needed."""
    global mimic_fallback_obj
    if not mimic_fallback_obj:
        config = Configuration.get()
        tts_config = config.get('tts', {}).get("mimic", {})
        lang = config.get("lang", "en-us")
        tts = Mimic(lang, tts_config)
        tts.validator.validate()
        tts.init(bus)
        mimic_fallback_obj = tts

    return mimic_fallback_obj

def mimic_fallback_tts(utterance, ident, listen):
    """Speak utterance using fallback TTS if connection is lost.

    Args:
        utterance (str): sentence to speak
        ident (str): interaction id for metrics
        listen (bool): True if interaction should end with mycroft listening
    """
    tts = _get_mimic_fallback()
    LOG.debug("Mimic fallback, utterance : " + str(utterance))
    tts.execute(utterance, ident, listen)

def handle_stop(event):
    """Handle stop message.

    Shutdown any speech.
    """
    global _last_stop_signal
    if check_for_signal("isSpeaking", -1):
        _last_stop_signal = time.time()
        tts.playback.clear()  # Clear here to get instant stop
        bus.emit(Message("mycroft.stop.handled", {"by": "TTS"}))

def init(messagebus):
    """Start speech related handlers.

    Args:
        messagebus: Connection to the Mycroft messagebus
    """

    global bus
    global tts
    global tts_hash
    global config

    bus = messagebus
    Configuration.set_config_update_handlers(bus)
    config = Configuration.get()
    bus.on('mycroft.stop', handle_stop)
    bus.on('mycroft.audio.speech.stop', handle_stop)
    bus.on('speak', handle_speak)

    tts = TTSFactory.create()
    tts.init(bus)
    tts_hash = hash(str(config.get('tts', '')))

def shutdown():
    """Shutdown the audio service cleanly.

    Stop any playing audio and make sure threads are joined correctly.
    """
    if tts:
        tts.playback.stop()
        tts.playback.join()
    if mimic_fallback_obj:
        mimic_fallback_obj.playback.stop()
        mimic_fallback_obj.playback.join()


text:
package views.supervision

import forms.EmptyForm
import models.supervision._
import org.joda.time.LocalDate
import org.jsoup.nodes.Element
import org.scalatest.prop.TableDrivenPropertyChecks
import play.api.i18n.Messages
import play.api.test.FakeRequest
import utils.AmlsSummaryViewSpec
import views.Fixture
import views.html.supervision.summary

import scala.collection.JavaConversions._

class summarySpec extends AmlsSummaryViewSpec with TableDrivenPropertyChecks{

  trait ViewFixture extends Fixture {
    lazy val summary = app.injector.instanceOf[summary]
    implicit val requestWithToken = addTokenForView(FakeRequest())

    val start = Some(SupervisionStart(new LocalDate(1990, 2, 24)))  //scalastyle:off magic.number
    val end = Some(SupervisionEnd(new LocalDate(1998, 2, 24)))//scalastyle:off magic.number
    val reason = Some(SupervisionEndReasons("Ending reason"))
  }

  "summary view" must {
    "have correct title" in new ViewFixture {
      def view = summary(EmptyForm, Supervision())

      doc.title must startWith(Messages("title.cya") + " - " + Messages("summary.supervision"))
    }

    "have correct headings" in new ViewFixture {
      def view = summary(EmptyForm, Supervision())

      heading.html must be(Messages("title.cya"))
      subHeading.html must include(Messages("summary.supervision"))
    }

    "include the provided data if there is another body provided" in new ViewFixture {

      def view = {
        val testdata = Supervision(
          Some(AnotherBodyYes("Company A", start, end, reason)),
          Some(ProfessionalBodyMemberYes),
          Some(ProfessionalBodies(Set(AccountingTechnicians, CharteredCertifiedAccountants, Other("anotherProfessionalBody")))),
          Some(ProfessionalBodyYes("details")),
          hasAccepted = true
        )

        summary(EmptyForm, testdata)
      }

      val sectionChecks = Table[String, Element => Boolean](
        ("title key", "check"),
        ("supervision.another_body.title",checkElementTextIncludes(_, "lbl.yes")),
        ("supervision.another_body.lbl.supervisor",checkElementTextIncludes(_, "Company A")),
        ("supervision.supervision_start.title",checkElementTextIncludes(_, "24 February 1990")),
        ("supervision.supervision_end.title",checkElementTextIncludes(_, "24 February 1998")),
        ("supervision.supervision_end_reasons.title",checkElementTextIncludes(_, "Ending reason")),
        ("supervision.memberofprofessionalbody.title",checkElementTextIncludes(_, "lbl.yes")),
        ("supervision.whichprofessionalbody.title",checkElementTextIncludes(_,
          "supervision.memberofprofessionalbody.lbl.01",
          "supervision.memberofprofessionalbody.lbl.02",
          "anotherProfessionalBody"
        )),
        ("supervision.penalisedbyprofessional.title",checkElementTextIncludes(_, "lbl.yes")),
        ("supervision.penalisedbyprofessional.details.lbl",checkElementTextIncludes(_, "details"))
      )

      forAll(sectionChecks) { (key, check) => {
        val Elements = doc.select("span.bold")
        val maybeElement = Elements.toList.find(e => e.text() == Messages(key))

        maybeElement must not be None
        val section = maybeElement.get.parents().select("div").first()
        check(section) must be(true)
      }}
    }

    "include the provided data if there is no another body provided" in new ViewFixture {

      def view = {
        val testdata = Supervision(
          Some(AnotherBodyNo),
          Some(ProfessionalBodyMemberYes),
          Some(ProfessionalBodies(Set(AccountingTechnicians, CharteredCertifiedAccountants, Other("anotherProfessionalBody")))),
          Some(ProfessionalBodyYes("details")),
          hasAccepted = true
        )

        summary(EmptyForm, testdata)
      }

      val sectionChecks = Table[String, Element => Boolean](
        ("title key", "check"),
        ("supervision.another_body.title",checkElementTextIncludes(_, "lbl.no")),
        ("supervision.memberofprofessionalbody.title",checkElementTextIncludes(_, "lbl.yes")),
        ("supervision.whichprofessionalbody.title",checkElementTextIncludes(_,
          "supervision.memberofprofessionalbody.lbl.01",
          "supervision.memberofprofessionalbody.lbl.02",
          "anotherProfessionalBody"
        )),
        ("supervision.penalisedbyprofessional.title",checkElementTextIncludes(_, "lbl.yes")),
        ("supervision.penalisedbyprofessional.details.lbl",checkElementTextIncludes(_, "details"))
      )

      forAll(sectionChecks) { (key, check) => {
        val Elements = doc.select("span.bold")
        val maybeElement = Elements.toList.find(e => e.text() == Messages(key))

        maybeElement must not be None
        val section = maybeElement.get.parents().select("div").first()
        check(section) must be(true)
      }}
    }
  }
}


text:
@extends('backend::layouts.app')

@section('content')

@lang('backend::user.destroy.title')

                    @if (session('status'))

                            {{ session('status') }}

                    @endif

                    <form class="form-horizontal" role="form" method="post" action="{{ route('backend.user.destroy', $user) }}">

                        {{ csrf_field() }}
                        {{ method_field('DELETE') }}

@lang('backend::user.destroy.text', ['name' => $user->name, 'email' => $user->email])

                                        <button type="submit" class="btn btn-danger">

                                            @lang('backend::user.destroy.button.yes')
                                        </button>

                                            @lang('backend::user.destroy.button.no')

                    </form>

@endsection


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/cardView"
    xmlns:cardview="http://schemas.android.com/apk/res-auto"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="?attr/selectableItemBackground"
    cardview:cardBackgroundColor="@android:color/white"
    cardview:cardElevation="10dp"
    android:layout_margin="10dp"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <com.facebook.drawee.view.SimpleDraweeView
            android:id="@+id/iv_image"
            android:layout_width="100dp"
            android:layout_height="100dp"
            fresco:actualImageScaleType="centerCrop"
            fresco:placeholderImageScaleType="centerCrop"
            fresco:placeholderImage="@mipmap/ic_launcher"
            fresco:fadeDuration="500"
            android:layout_gravity="center_vertical"
            android:layout_margin="10dp"
            />
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
            <RelativeLayout
                android:id="@+id/rl_top"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:paddingRight="10dp"
                android:paddingTop="10dp"
                >
                <TextView
                    android:id="@+id/tv_creator"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true"
                    android:text="作者"
                    />
                <TextView
                    android:id="@+id/tv_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentEnd="true"
                    android:text="时间"
                    />
            </RelativeLayout>

            <LinearLayout
                android:id="@+id/ll_bottom"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_marginTop="5dp"
                android:layout_alignParentBottom="true"
                >
                <LinearLayout
                    android:id="@+id/btn_collect"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:clickable="true"
                    android:padding="10dp"
                    android:background="?attr/selectableItemBackground"
                    >
                    <TextView
                        android:id="@+id/tv_collect"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:text="收藏"
                        android:textColor="@drawable/btn_text_color_selector"
                        android:textSize="16dp"
                        android:duplicateParentState="true"
                        />
                </LinearLayout>
                <LinearLayout
                    android:id="@+id/btn_share"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:clickable="true"
                    android:padding="10dp"
                    android:background="?attr/selectableItemBackground"
                    >
                    <TextView
                        android:id="@+id/tv_share"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:textColor="@drawable/btn_text_color_selector"
                        android:text="分享"
                        android:textSize="16dp"
                        android:duplicateParentState="true"
                        />
                </LinearLayout>
            </LinearLayout>
            <TextView
                android:id="@+id/tv_desc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/rl_top"
                android:layout_above="@id/ll_bottom"
                android:layout_marginRight="10dp"
                android:layout_marginTop="5dp"
                android:textSize="16dp"
                android:maxEms="20"
                android:ellipsize="end"
                android:maxLines="2"
                android:text="描述sadjfka"
                />
        </RelativeLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>


text:
import { Component, ChangeDetectionStrategy } from '@angular/core';
import {
  CalendarEvent,
  CalendarEventTimesChangedEvent,
  CalendarView,
} from 'angular-calendar';
import { Subject } from 'rxjs';
import { colors } from '../demo-utils/colors';

@Component({
  selector: 'mwl-demo-component',
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: 'template.html',
  styles: [
    `
      .drag-active {
        position: relative;
        z-index: 1;
        pointer-events: none;
      }
      .drag-over {
        background-color: #eee;
      }
    `,
  ],
})
export class DemoComponent {
  CalendarView = CalendarView;

  view = CalendarView.Month;

  viewDate = new Date();

  externalEvents: CalendarEvent[] = [
    {
      title: 'Event 1',
      color: colors.yellow,
      start: new Date(),
      draggable: true,
    },
    {
      title: 'Event 2',
      color: colors.blue,
      start: new Date(),
      draggable: true,
    },
  ];

  events: CalendarEvent[] = [];

  activeDayIsOpen = false;

  refresh = new Subject<void>();

  eventDropped({
    event,
    newStart,
    newEnd,
    allDay,
  }: CalendarEventTimesChangedEvent): void {
    const externalIndex = this.externalEvents.indexOf(event);
    if (typeof allDay !== 'undefined') {
      event.allDay = allDay;
    }
    if (externalIndex > -1) {
      this.externalEvents.splice(externalIndex, 1);
      this.events.push(event);
    }
    event.start = newStart;
    if (newEnd) {
      event.end = newEnd;
    }
    if (this.view === 'month') {
      this.viewDate = newStart;
      this.activeDayIsOpen = true;
    }
    this.events = [...this.events];
  }

  externalDrop(event: CalendarEvent) {
    if (this.externalEvents.indexOf(event) === -1) {
      this.events = this.events.filter((iEvent) => iEvent !== event);
      this.externalEvents.push(event);
    }
  }
}


text:
import socket, sys, struct, argparse, signal

rates = {20000:0, 50000:1, 100000:2, 250000:3, 500000:4, 1250000:5}
activeReceiver = None

class Transceiver(object):

    def __init__(self, ipaddr):
        self.p_ip_address = ipaddr
        self.run = True;
        self.control_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.data_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def shutdown(self):
        sys.stderr.write("shutdown\n")
        self.run = False

        self.data_socket.close()
        self.control_socket.close()
        sys.stdout.flush()

        sys.stderr.write("bye\n")
        sys.exit(0)

    def start_rx(self, freq, rate_index, corr):
        """
        Connects to the Red Pitaya Transeiver server and writes the data to stdout
        :param freq: Frequency in Hz
        :param rate_index: Sample rate index
        :param corr: correction in ppm
        :return:
        """
        # Setup control socket
        self.control_socket.connect((self.p_ip_address, 1001))
        self.control_socket.send(struct.pack('<I', 0))

        # Setup data socket
        self.data_socket.connect((self.p_ip_address, 1001))
        self.data_socket.send(struct.pack('<I', 1))

        # Set frequency and rate
        self.control_socket.send(struct.pack('<I', 0<<28 | int((1.0 + 1e-6 * corr ) * freq)))
        self.control_socket.send(struct.pack('<I', 1<<28 | rate_index))

        # write aquisition parameters to console
        sys.stderr.write(
            "...receiving at: {0} Hz sample sample rate: {1}  / correction (ppm): {2}\n".format(freq, list(rates.keys())[list(rates.values()).index(rate_index)],
                                                                                corr))

        "fetch data"
        try:
            while self.run:
                sys.stdout.write(self.data_socket.recv(1024))
        except Exception:
            sys.stderr.write(">>> rx force shutdown\n")
            self.shutdown()

def signal_term_handler(signal, frame):
    activeReceiver.shutdown()

if __name__ == "__main__":

    # Parse arguments
    parser = argparse.ArgumentParser(description='Receive raw data I/Q from Pavel''s SDR Transceiver app (http://pavel-demin.github.io/red-pitaya-notes/sdr-transceiver/)')

    parser.add_argument("--address", help="IP address Red Pitaya", default="192.168.188.21")
    parser.add_argument("--freq", help="Center Frequency, default 14100000 Hz", type=int, default=14100000)
    parser.add_argument("--rate", help="Sample rate, allowed values: 20000 50000 100000 250000 500000 1250000", type=int, default=500000)
    parser.add_argument("--corr", help="Correction in ppm, dafault 0", type=int, default=0)

    args = parser.parse_args()

    # Register SIGTERM handler
    signal.signal(signal.SIGINT, signal_term_handler)

    trx = Transceiver(args.address)

    activeReceiver = trx;
    trx.start_rx(args.freq, rates[args.rate], args.corr)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Action</title>
<meta name="date" content="2018-11-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.mercadopago.android.px.model

Class Action

java.lang.Object

com.mercadopago.android.px.model.Action

Direct Known Subclasses:

ExitAction

public class Action
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

Action()

Method Summary

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Action

public Action()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.taskadapter.redmineapi;

import java.util.Collection;
import java.util.List;

import com.taskadapter.redmineapi.bean.Membership;
import com.taskadapter.redmineapi.bean.MembershipFactory;
import com.taskadapter.redmineapi.bean.Project;
import com.taskadapter.redmineapi.bean.ProjectFactory;
import com.taskadapter.redmineapi.bean.Role;
import com.taskadapter.redmineapi.bean.UserFactory;
import com.taskadapter.redmineapi.internal.Transport;

/**
 * Works with User-Project Memberships.
 *
Obtain it via RedmineManager:
 *

 RedmineManager mgr = RedmineManagerFactory.createWithUserAuth(redmineURI, login, password);
 MembershipManager membershipManager = mgr.getMembershipManager();
 *

 *
 *
Sample usage:
 *

 roles = mgr.getUserManager().getRoles();
 currentUser = mgr.getUserManager().getCurrentUser();
 final Membership membershipForUser = membershipManager.createMembershipForUser(project.getId(), currentUser.getId(), roles);
 memberships = membershipManager.getMemberships(project.getId());
 membershipManager.delete(membershipForUser);
 *

 *
 * @see RedmineManager
 */
public class MembershipManager {
    private final Transport transport;

    MembershipManager(Transport transport) {
        this.transport = transport;
    }

    public List<Membership> getMemberships(String projectKey)
            throws RedmineException {
        return transport.getChildEntries(Project.class, projectKey, Membership.class);
    }

    public List<Membership> getMemberships(int projectId) throws RedmineException {
        return transport.getChildEntries(Project.class, projectId, Membership.class);
    }

    /**
     * Add a membership.
     *
     * @param membership
     *            membership.
     * @throws RedmineException
     */
    private Membership addMembership(Membership membership) throws RedmineException {
        final Project project = membership.getProject();
        if (project == null) {
            throw new IllegalArgumentException("Project must be set");
        }
        if (membership.getUser() == null && membership.getRoles().isEmpty()) {
            throw new IllegalArgumentException("Either User or Roles field must be set");
        }
        return transport.addChildEntry(Project.class, project.getId()+"", membership);
    }

    public Membership getMembership(int membershipId) throws RedmineException {
        return transport.getObject(Membership.class, membershipId);
    }

    public void delete(int membershipId) throws RedmineException {
        transport.deleteObject(Membership.class, Integer.toString(membershipId));
    }

    public void delete(Membership membership) throws RedmineException {
        transport.deleteObject(Membership.class, membership.getId().toString());
    }

    public void update(Membership membership) throws RedmineException {
        transport.updateObject(membership);
    }

    public Membership createMembershipForGroup(int projectId, int groupId, Collection<Role> roles) throws RedmineException {
        final Membership membership = MembershipFactory.create();
        final Project project = ProjectFactory.create(projectId);
        membership.setProject(project);
        // This is nuts, but according to the documentation the way it is supposed
        // to work:
        // http://www.redmine.org/projects/redmine/wiki/Rest_Memberships#POST
        // http://www.redmine.org/issues/17904
        membership.setUser(UserFactory.create(groupId));
        membership.addRoles(roles);

        return addMembership(membership);
    }

    public Membership createMembershipForUser(int projectId, int userId, Collection<Role> roles) throws RedmineException {
        final Membership membership = MembershipFactory.create();
        final Project project = ProjectFactory.create(projectId);
        membership.setProject(project);
        membership.setUser(UserFactory.create(userId));
        membership.addRoles(roles);
        return addMembership(membership);
    }
}


text:
root = File.expand_path('../', File.dirname(__FILE__))

puts 'Clearing catalog credentials ...'

require root + '/app'

default_project = ::DTK::Project.get_all(::DTK::ModelHandle.new(c = 2, :project)).first
::DTK::Model.get_objs(default_project.model_handle(:user), { cols: ::DTK::User.common_columns })

session = ::DTK::CurrentSession.new
session.set_user_object(default_project.get_field?(:user))
session.set_auth_filters(:c, :group_ids)

users = ::DTK::Model.get_objs(default_project.model_handle(:user), { cols: [:id, :catalog_username, :catalog_password] })

users.each do |user|
  user.update(catalog_password: nil, catalog_username: nil)
end

::DTK::Model.update_from_rows(default_project.model_handle(:user), users)

puts 'Catalog credentials have been purged successfully!'


text:
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2011 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.wikipathways.applet.gui;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.security.AccessControlException;

import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;

import org.pathvisio.core.Engine;
import org.pathvisio.core.debug.Logger;
import org.pathvisio.core.model.PathwayElement;
import org.pathvisio.core.model.PathwayElementEvent;
import org.pathvisio.core.model.PathwayElementListener;
import org.pathvisio.core.model.StaticProperty;
import org.pathvisio.core.preferences.GlobalPreference;
import org.pathvisio.core.preferences.PreferenceManager;
import org.pathvisio.core.util.ProgressKeeper;
import org.pathvisio.core.util.ProgressKeeper.ProgressEvent;
import org.pathvisio.core.util.ProgressKeeper.ProgressListener;
import org.pathvisio.gui.MainPanel;
import org.pathvisio.gui.SwingEngine;
import org.wikipathways.applet.Parameter;
import org.wikipathways.applet.RunnableWithProgress;
import org.wikipathways.applet.UserInterfaceHandler;
import org.wikipathways.applet.WikiPathways;

public class PathwayPageApplet extends JApplet {
	UserInterfaceHandler uiHandler;
	WikiPathways wiki;

	public final void init() {
		/* Do not force LAF, seems to give problems
  		try {
		    UIManager.setLookAndFeel(
		        UIManager.getSystemLookAndFeelClassName());
		} catch (Exception ex) {
			Logger.log.error("Unable to load native look and feel", ex);
		}
		*/

		//Add a mouse listener that requests focus on clicking
		//To fix bug 299
		addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				PathwayPageApplet.this.requestFocus();
				PathwayPageApplet.this.requestFocusInWindow();
			}
		});

		try {
			Logger.log.trace(this + ": INIT CALLED....");

			PreferenceManager.init();
			final Engine engine = new Engine();
			SwingEngine swingEngine = new SwingEngine(engine);

			uiHandler = new UserInterfaceHandler(PathwayPageApplet.this);
			wiki = new WikiPathways(uiHandler, swingEngine);

			parseArguments();

			//Init with progress monitor
			final RunnableWithProgress<Void> r = new RunnableWithProgress<Void>() {
				public Void excecuteCode() {
					try {
						doInitWiki(getProgressKeeper(), getDocumentBase());
					} catch(AccessControlException ae) {
							onError("You didn't accept the certificate needed to run this applet.\n" +
									"After restarting the browser, click the edit button and choose" +
									"\n'Run' in the security dialog that pops up.",
							"Security exception");
					} catch(Exception e) {
						Logger.log.error("Error while starting applet", e);
						String msg =  e.getClass() +
						"\n See error log (" + PreferenceManager.getCurrent().get(GlobalPreference.WP_FILE_LOG) + ") for details";
						JOptionPane.showMessageDialog(
								PathwayPageApplet.this, msg, "Error while initializing editor", JOptionPane.ERROR_MESSAGE);
					};
					doInit();
					getProgressKeeper().finished();
					return null;
				}
			};
			//Perform some actions after the runnable is done
			r.getProgressKeeper().addListener(new ProgressListener() {
				public void progressEvent(ProgressEvent e) {
					if(e.getType() == ProgressEvent.FINISHED) {
						afterInit();
					}
				}
			});

			Logger.log.trace(this + ": Performing init in background");
			uiHandler.runWithProgress(r, "", false, true);
		} catch(Exception e) {
			onError("Error: " + e.getClass() + ": " + e.getMessage(), "Error");
		}
	}

	public void stop() {
		Logger.log.trace("Applet.stop called, stopping save reminder");
		if(wiki != null) SaveReminder.stopSaveReminder(wiki);
	}

	public void start() {
		Logger.log.trace("Applet.start called, starting save reminder");
		if(wiki != null) wiki.startSaveReminder();
	}

	public void destroy() {
		Logger.log.trace("Applet.destroy called, stopping save reminder");
		if(wiki != null) {
			SaveReminder.stopSaveReminder(wiki);
			wiki.dispose();
			wiki = null;
		}
		uiHandler = null;
	}

	private void onError(String msg, String title) {
		JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
		getAppletContext().showDocument(getDocumentBase(), "_self");
	}

	private void afterInit() {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				Logger.log.trace(this + ": Creating GUI");
				if(!this.getClass().equals(PathwayPageApplet.class)) {
					createToolbar();
					createGui();
					validate();
				}
			}
		});
	}

	/**
	 * In this method the WikiPathways class is initiated,
	 * by calling {@link WikiPathways#init(ProgressKeeper, URL)}
	 * @see {@link WikiPathways#init(ProgressKeeper, URL)}
	 * @param pk
	 * @param base
	 * @throws Exception
	 */
	protected void doInitWiki(ProgressKeeper pk, URL base) throws Exception {
		Logger.log.trace(this + ":doInitWiki");
		wiki.init(pk, base);
	}

	public boolean mayExit() {
		return wiki != null ? wiki.mayExit() : true;
	}

	protected void doInit() {
		//May be implemented by subclasses
	}

	protected void createGui() {
		//May be implemented by subclasses
	}

	private JFrame fullScreenFrame;

	public boolean isFullScreen() {
		return fullScreenFrame != null;
	}

	/**
	 * Makes the applet go to fullscreen mode.
	 * Creates a new frame and transfers the mainPanel from
	 * the applet to the frame.
	 * @see #toEmbedded(boolean)
	 */
	protected void toFullScreen() {
		final MainPanel mainPanel = wiki.getMainPanel();
		fullScreenFrame = new JFrame();

		PathwayElement mappInfo = wiki.getPathway().getMappInfo();

		fullScreenFrame.setTitle("WikiPathways editor - " + mappInfo.getMapInfoName());

		wiki.getPathway().getMappInfo().addListener(new PathwayElementListener() {
			public void gmmlObjectModified(PathwayElementEvent e) {
				if (e.affectsProperty(StaticProperty.MAPINFONAME)) {
					fullScreenFrame.setTitle("WikiPathways editor - " +
							e.getModifiedPathwayElement().getMapInfoName());
				}
			}
		});
		getContentPane().repaint();

		fullScreenFrame.getContentPane().add(mainPanel);

		fullScreenFrame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				if(wiki.exit(false, null)) {
					fullScreenFrame.dispose();
				}
			}
		});

		fullScreenFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		fullScreenFrame.setVisible(true);
		fullScreenFrame.setSize(800, 600);
		fullScreenFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
		fullScreenFrame.validate();
	}

	/**
	 * Closes the fullscreen mode and returns the applet
	 * to embedded mode
	 * @see PathwayPageApplet#toFullScreen()
	 */
	public void toEmbedded() {
		MainPanel mainPanel = wiki.getMainPanel();

		fullScreenFrame.getContentPane().remove(mainPanel);
		getContentPane().add(mainPanel, BorderLayout.CENTER);

		fullScreenFrame.setVisible(false);
		fullScreenFrame.dispose();
		fullScreenFrame = null;

		validate();
		repaint();
	}

	/**
	 * Get the default description that will be used
	 * when the changes are saved to the server
	 * If the return value is null, the user will be prompted
	 * for a description
	 */
	protected String getDefaultDescription() {
		return null;
	}

	protected void createToolbar() {
		JToolBar toolbar = new JToolBar(JToolBar.VERTICAL);
		toolbar.setFloatable(false);
		toolbar.add(new Actions.ExitAction(wiki.getUserInterfaceHandler(), wiki, true, getDefaultDescription()));
		toolbar.add(new Actions.ExitAction(wiki.getUserInterfaceHandler(), wiki, false, getDefaultDescription()));
		getContentPane().add(toolbar, BorderLayout.WEST);
	}

	void parseArguments() {
		Parameter parameters = wiki.getParameters();
		for(String name : parameters.getNames()) {
			parameters.setValue(name, getParameter(name));
		}
	}

	public String toString() {
		return this.getClass() + ": " + getName() + hashCode();
	}
}


text:
package org.aieonf.commons.ui.wizard;

import java.util.EventObject;

import org.aieonf.commons.ui.flow.IFlowControl;
import org.aieonf.commons.ui.wizard.IAddWizardPageListener.PageActions;
import org.eclipse.jface.wizard.IWizard;

public class PageActionEvent extends EventObject {
	private static final long serialVersionUID = 1L;

	private PageActions event;
	private String pageName;
	private String description;
	private String message;
	private IFlowControl flow;

	public PageActionEvent( IWizard source, IFlowControl flow, PageActions event, String pageName, String description, String message ){
		super(source);
		this.event = event;
		this.pageName = pageName;
		this.description = description;
		this.message = message;
		this.flow = flow;
	}

	public IFlowControl getFlow() {
		return flow;
	}

	public PageActions getEvent() {
		return event;
	}

	public String getPageName() {
		return pageName;
	}

	public String getDescription() {
		return description;
	}

	public String getMessage() {
		return message;
	}
}


text:
package in.srain.cube.cache;

import in.srain.cube.request.JsonData;

/**
 * Describe the behaviour of a object who can be cached
 */
public interface ICacheAble<T> {

    /**
     * set cache time, in seconds
     *
     * @param time
     * @return
     */
    public ICacheAble<T> setCacheTime(long time);

    /**
     * In seconds
     *
     * @return
     */
    public long getCacheTime();

    public ICacheAble<T> setCacheKey(String key);

    public String getCacheKey();

    /**
     * Using cache data if existent, ignore whether it is expired or not.
     *
     * @param use
     */
    public ICacheAble<T> setUseCacheAnyway(boolean use);

    /**
     * check if use cache anyway
     *
     * @return
     */
    public boolean useCacheAnyway();

    /**
     * @param path file path under /res, For example: "/cache_init/test.json";
     * @return
     */
    public ICacheAble<T> setAssertInitDataPath(String path);

    /**
     * @return file path under /res, For example: "/cache_init/test.json";
     */
    public String getAssertInitDataPath();

    /**
     * We need to process the data from data source, do some filter of convert the structure.
     * <p/>
     * As the "Assert Data" is a special data source, we also need to do the same work.
     */
    public T processRawDataFromCache(JsonData rawData);

    /**
     * when data loaded from cache
     *
     * @param cacheData
     * @param outOfDate
     */
    public void onCacheData(CacheResultType cacheResultType, T cacheData, boolean outOfDate);

    /**
     * When there is no cache data is available, this method will be called.
     * Will always in Main UI thread
     */
    public void onNoCacheData(CacheManager cacheManager);

    /**
     * temporarily disable cache. The data will no be load from cache and will also not be put into cache
     */
    public ICacheAble<T> setDisableCache(boolean disable);

    /**
     * check if cache is disabled
     *
     * @return
     */
    public boolean cacheIsDisabled();
}


text:
title: Kalender
---


text:
<?php

namespace PhpBench\Expression\Parselet;

use PhpBench\Expression\Ast\ArgumentListNode;
use PhpBench\Expression\Ast\FunctionNode;
use PhpBench\Expression\Ast\Node;
use PhpBench\Expression\Parser;
use PhpBench\Expression\PrefixParselet;
use PhpBench\Expression\Token;
use PhpBench\Expression\Tokens;

class FunctionParselet implements PrefixParselet
{
    public function tokenType(): string
    {
        return Token::T_FUNCTION;
    }

    public function parse(Parser $parser, Tokens $tokens): Node
    {
        $functionToken = $tokens->chomp();

        if ($tokens->current()->type === Token::T_CLOSE_PAREN) {
            $arguments = null;
        } else {
            $arguments = $parser->parseList($tokens);
            $arguments = $this->resolveArguments($arguments);
        }

        $tokens->chomp(Token::T_CLOSE_PAREN);

        return new FunctionNode(rtrim($functionToken->value, '('), $arguments);
    }

    private function resolveArguments(Node $arguments): ArgumentListNode
    {
        if ($arguments instanceof ArgumentListNode) {
            return $arguments;
        }

        return new ArgumentListNode([$arguments]);
    }
}


text:
namespace boost {
    namespace locale {
        namespace conv {
            ///
            /// \addtogroup codepage
            ///
            /// @{

            ///
            /// \brief The excepton that is thrown in case of conversion error
            ///
            class BOOST_SYMBOL_VISIBLE conversion_error : public std::runtime_error {
            public:
                conversion_error() : std::runtime_error("Conversion failed") {}
            };

            ///
            /// \brief This exception is thrown in case of use of unsupported
            /// or invalid character set
            ///
            class BOOST_SYMBOL_VISIBLE invalid_charset_error : public std::runtime_error {
            public:

                /// Create an error for charset \a charset
                invalid_charset_error(std::string charset) :
                    std::runtime_error("Invalid or unsupported charset:" + charset)
                {
                }
            };

            ///
            /// enum that defines conversion policy
            ///
            typedef enum {
                skip            = 0,    ///< Skip illegal/unconvertable characters
                stop            = 1,    ///< Stop conversion and throw conversion_error
                default_method  = skip  ///< Default method - skip
            } method_type;

            /// @}

        } // conv

    } // locale
} // boost

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

#endif

// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4