text:
package org.keplerproject.luajava;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;

/**
 * Class that contains functions accessed by lua.
 *
 * @author Thiago Ponte
 */
@SuppressWarnings("serial")
public final class LuaJavaAPI {

	private LuaJavaAPI() {
	}

	private static void addStack(StringBuilder sb, Throwable e) {
		sb.append("\n**\n** ").append(e.toString()).append(":")
				.append(e.getLocalizedMessage()).append("/")
				.append(e.getMessage()).append('\n');
		StackTraceElement[] stackTrace = e.getStackTrace();
		for (StackTraceElement s : stackTrace) {
			sb.append("** ");
			sb.append(s.getClassName());
			sb.append('.');
			sb.append(s.getMethodName());
			sb.append('(');
			sb.append(s.getFileName());
			sb.append(':');
			sb.append(s.getLineNumber());
			sb.append(')');
			sb.append('\n');
		}
	}

	private static void wrapException(Exception e, HashMap<String, Object> m)
			throws LuaException {
		StringBuilder sb = new StringBuilder("** ").append(m.toString());
		Throwable e1 = e, e2 = null;
		while (e1 != null && e1 != e2) {
			addStack(sb, e1);
			e2 = e1;
			e1 = e1.getCause();
		}
		throw new LuaException(sb.toString(), e);
	}

	/**
	 * Java implementation of the metamethod __index for normal objects
	 *
	 * @param luaState
	 *            int that indicates the state used
	 * @param obj
	 *            Object to be indexed
	 * @param methodName
	 *            the name of the method
	 * @return number of returned objects
	 */
	public static int objectIndex(int luaState, Object obj, String methodName)
			throws LuaException {
		try {
			LuaState L = LuaStateFactory.getExistingState(luaState);

			synchronized (L) {
				int top = L.getTop();

				Object[] objs = new Object[top - 1];
				Method method = null;

				Class<?> clazz;

				if (obj instanceof Class) {
					clazz = (Class<?>) obj;
					// First try. Static methods of the object
					method = getMethod(L, clazz, methodName, objs, top);

					if (method == null)
						clazz = Class.class;

					// Second try. Methods of the Class class
					method = getMethod(L, clazz, methodName, objs, top);
				} else {
					clazz = obj.getClass();
					method = getMethod(L, clazz, methodName, objs, top);
				}

				/*
				 * Method[] methods = clazz.getMethods(); Method method = null;
				 *
				 * // gets method and arguments for (int i = 0; i <
				 * methods.length; i++) { if
				 * (!methods[i].getName().equals(methodName))
				 *
				 * continue;
				 *
				 * Class[] parameters = methods[i].getParameterTypes(); if
				 * (parameters.length != top - 1) continue;
				 *
				 * boolean okMethod = true;
				 *
				 * for (int j = 0; j < parameters.length; j++) { try { objs[j] =
				 * compareTypes(L, parameters[j], j + 2); } catch (Exception e)
				 * { okMethod = false; break; } }
				 *
				 * if (okMethod) { method = methods[i]; break; }
				 *
				 * }
				 */

				// If method is null means there isn't one receiving the given
				// arguments
				if (method == null) {
					throw new LuaException(
							"Invalid method call. No such method.");
				}

				Object ret;
				try {
					if (Modifier.isPublic(method.getModifiers())) {
						method.setAccessible(true);
					}

					// if (obj instanceof Class)
					if (Modifier.isStatic(method.getModifiers())) {
						ret = method.invoke(null, objs);
					} else {
						ret = method.invoke(obj, objs);
					}
				} catch (Exception e) {
					throw new LuaException(e);
				}

				// Void function returns null
				if (ret == null) {
					return 0;
				}

				// push result
				L.pushObjectValue(ret);

				return 1;
			}
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {
				{
					put("luaState", luaState);
					put("obj", obj);
					put("methodName", methodName);
				}
			});
			return 0;// can't reach
		}
	}

	/**
	 * Java function that implements the __index for Java arrays
	 *
	 * @param luaState
	 *            int that indicates the state used
	 * @param obj
	 *            Object to be indexed
	 * @param index
	 *            index number of array. Since Lua index starts from 1, the
	 *            number used will be (index - 1)
	 * @return number of returned objects
	 */
	public static int arrayIndex(int luaState, Object obj, int index)
			throws LuaException {
		try {
			LuaState L = LuaStateFactory.getExistingState(luaState);

			synchronized (L) {

				if (!obj.getClass().isArray())
					throw new LuaException("Object indexed is not an array.");

				if (Array.getLength(obj) < index)
					throw new LuaException("Index out of bounds.");

				L.pushObjectValue(Array.get(obj, index - 1));

				return 1;
			}
		} catch (Exception e) {
			if (e instanceof LuaException) {
				throw e;
			} else {
				throw new LuaException(new HashMap<String, Object>() {
					{
						put("luaState", luaState);
						put("obj", obj);
						put("index", index);
					}
				}.toString(), e);
			}
		}
	}

	/**
	 * Java function to be called when a java Class metamethod __index is
	 * called. This function returns 1 if there is a field with searchName and 2
	 * if there is a method if the searchName
	 *
	 * @param luaState
	 *            int that represents the state to be used
	 * @param clazz
	 *            class to be indexed
	 * @param searchName
	 *            name of the field or method to be accessed
	 * @return number of returned objects
	 * @throws LuaException
	 */
	public static int classIndex(int luaState, Class<?> clazz, String searchName)
			throws LuaException {
		try {
			synchronized (LuaStateFactory.getExistingState(luaState)) {
				int res;

				res = checkField(luaState, clazz, searchName);

				if (res != 0) {
					return 1;
				}

				res = checkMethod(luaState, clazz, searchName);

				if (res != 0) {
					return 2;
				}

				return 0;
			}
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {
				{
					put("luaState", luaState);
					put("clazz", clazz);
					put("searchName", searchName);
				}
			});
			return 0;// can't reach
		}
	}

	/**
	 * Java function to be called when a java object metamethod __newindex is
	 * called.
	 *
	 * @param luaState
	 *            int that represents the state to be used
	 * @param object
	 *            to be used
	 * @param fieldName
	 *            name of the field to be set
	 * @return number of returned objects
	 * @throws LuaException
	 */
	public static int objectNewIndex(int luaState, Object obj, String fieldName)
			throws LuaException {
		try {
			LuaState L = LuaStateFactory.getExistingState(luaState);

			synchronized (L) {
				Field field = null;
				Class<?> objClass;

				if (obj instanceof Class) {
					objClass = (Class<?>) obj;
				} else {
					objClass = obj.getClass();
				}

				try {
					field = objClass.getField(fieldName);
				} catch (Exception e) {
					throw new LuaException("Error accessing field.", e);
				}

				Class<?> type = field.getType();
				Object setObj = compareTypes(L, type, 3);

				if (field.isAccessible())
					field.setAccessible(true);

				try {
					field.set(obj, setObj);
				} catch (IllegalArgumentException e) {
					throw new LuaException("Ilegal argument to set field.", e);
				} catch (IllegalAccessException e) {
					throw new LuaException("Field not accessible.", e);
				}
			}

			return 0;
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {
				{
					put("luaState", luaState);
					put("obj", obj);
					put("fieldName", fieldName);
				}
			});
			return 0;// can't reach
		}
	}

	public static ClassLoader getClassLoader(LuaState L) {
		synchronized (L) {
			ClassLoader cl = L.getClassLoader();
			if (cl == null) {
				cl = Thread.currentThread().getContextClassLoader();
			}
			if (cl == null) {
				cl = LuaJavaAPI.class.getClassLoader();
			}
			return cl;
		}
	}

	public static Class<?> getClass(LuaState L, String className)
			throws ClassNotFoundException {
		synchronized (L) {
			ClassLoader cl = getClassLoader(L);
			if (cl == null) {
				return Class.forName(className);
			} else {
				return Class.forName(className, true, cl);
			}
		}
	}

	/**
	 * Class.forName with Context ClassLoader
	 *
	 * @see Class.forName
	 * @throws ClassNotFoundException
	 */
	public static Class<?> getClassForName(int luaState, String className)
			throws ClassNotFoundException {
		LuaState L = LuaStateFactory.getExistingState(luaState);
		return getClass(L, className);
	}

	/**
	 * Java function to be called when a java array metamethod __newindex is
	 * called.
	 *
	 * @param luaState
	 *            int that represents the state to be used
	 * @param object
	 *            to be used
	 * @param index
	 *            index number of array. Since Lua index starts from 1, the
	 *            number used will be (index - 1)
	 * @return number of returned objects
	 * @throws LuaException
	 */
	public static int arrayNewIndex(int luaState, Object obj, int index)
			throws LuaException {
		try {
			LuaState L = LuaStateFactory.getExistingState(luaState);

			synchronized (L) {
				if (!obj.getClass().isArray())
					throw new LuaException("Object indexed is not an array.");

				if (Array.getLength(obj) < index)
					throw new LuaException("Index out of bounds.");

				Class<?> type = obj.getClass().getComponentType();
				Object setObj = compareTypes(L, type, 3);

				Array.set(obj, index - 1, setObj);
			}

			return 0;
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {
				{
					put("luaState", luaState);
					put("obj", obj);
					put("index", index);
				}
			});
			return 0;// can't reach
		}
	}

	/**
	 * Pushes a new instance of a java Object of the type className
	 *
	 * @param luaState
	 *            int that represents the state to be used
	 * @param className
	 *            name of the class
	 * @return number of returned objects
	 * @throws LuaException
	 */
	public static int javaNewInstance(int luaState, String className)
			throws LuaException {
		try {
			LuaState L = LuaStateFactory.getExistingState(luaState);

			synchronized (L) {
				Class<?> clazz;
				try {
					clazz = getClass(L, className);
				} catch (ClassNotFoundException e) {
					throw new LuaException(e);
				}
				Object ret = getObjInstance(L, clazz);

				L.pushJavaObject(ret);

				return 1;
			}
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {
				{
					put("luaState", luaState);
					put("className", className);
				}
			});
			return 0;// can't reach
		}
	}

	/**
	 * javaNew returns a new instance of a given clazz
	 *
	 * @param luaState
	 *            int that represents the state to be used
	 * @param clazz
	 *            class to be instanciated
	 * @return number of returned objects
	 * @throws LuaException
	 */
	public static int javaNew(int luaState, Class<?> clazz) throws LuaException {
		try {
			LuaState L = LuaStateFactory.getExistingState(luaState);

			synchronized (L) {
				Object ret = getObjInstance(L, clazz);

				L.pushJavaObject(ret);

				return 1;
			}
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {
				{
					put("luaState", luaState);
					put("clazz	", clazz);
				}
			});
			return 0;// can't reach
		}
	}

	/**
	 * Calls the static method methodName in class
	 * className that receives a LuaState as first parameter.
	 *
	 * @param luaState
	 *            int that represents the state to be used
	 * @param className
	 *            name of the class that has the open library method
	 * @param methodName
	 *            method to open library
	 * @return number of returned objects
	 * @throws LuaException
	 */
	public static int javaLoadLib(int luaState, String className,
			String methodName) throws LuaException {
		try {
			LuaState L = LuaStateFactory.getExistingState(luaState);

			synchronized (L) {
				Class<?> clazz;
				try {
					clazz = getClass(L, className);
				} catch (ClassNotFoundException e) {
					throw new LuaException(e);
				}

				try {
					Method mt = clazz.getMethod(methodName,
							new Class[] { LuaState.class });
					Object obj = mt.invoke(null, new Object[] { L });

					if (obj != null && obj instanceof Integer) {
						return ((Integer) obj).intValue();
					} else
						return 0;
				} catch (Exception e) {
					throw new LuaException(
							"Error on calling method. Library could not be loaded. "
									+ e.getMessage());
				}
			}
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {

				{
					put("luaState", luaState);
					put("className	", className);
					put("methodName", methodName);
				}
			});
			return 0;// can't reach
		}
	}

	private static Object getObjInstance(LuaState L, Class<?> clazz)
			throws LuaException {
		try {
			synchronized (L) {
				int top = L.getTop();

				Object[] objs = new Object[top - 1];

				Constructor<?>[] constructors = clazz.getConstructors();
				Constructor<?> constructor = null;

				// gets method and arguments
				for (int i = 0; i < constructors.length; i++) {
					Class<?>[] parameters = constructors[i].getParameterTypes();
					if (parameters.length != top - 1)
						continue;

					boolean okConstruc = true;

					for (int j = 0; j < parameters.length; j++) {
						try {
							objs[j] = compareTypes(L, parameters[j], j + 2);
						} catch (Exception e) {
							okConstruc = false;
							break;
						}
					}

					if (okConstruc) {
						constructor = constructors[i];
						break;
					}

				}

				// If method is null means there isn't one receiving the given
				// arguments
				if (constructor == null) {
					throw new LuaException(
							"Invalid method call. No such method.");
				}

				Object ret;
				try {
					ret = constructor.newInstance(objs);
				} catch (Exception e) {
					throw new LuaException(e);
				}

				if (ret == null) {
					throw new LuaException("Couldn't instantiate java Object");
				}

				return ret;
			}
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {

				{
					put("clazz", clazz);
				}
			});
			return 0;// can't reach
		}
	}

	/**
	 * Checks if there is a field on the obj with the given name
	 *
	 * @param luaState
	 *            int that represents the state to be used
	 * @param obj
	 *            object to be inspected
	 * @param fieldName
	 *            name of the field to be inpected
	 * @return number of returned objects
	 */
	public static int checkField(int luaState, Object obj, String fieldName)
			throws LuaException {
		try {
			LuaState L = LuaStateFactory.getExistingState(luaState);

			synchronized (L) {
				Field field = null;
				Class<?> objClass;

				if (obj instanceof Class) {
					objClass = (Class<?>) obj;
				} else {
					objClass = obj.getClass();
				}

				try {
					field = objClass.getField(fieldName);
				} catch (Exception e) {
					return 0;
				}

				if (field == null) {
					return 0;
				}

				Object ret = null;
				try {
					ret = field.get(obj);
				} catch (Exception e1) {
					return 0;
				}

				if (ret == null) {
					return 0;
				}

				L.pushObjectValue(ret);

				return 1;
			}
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {

				{
					put("luaState", luaState);
					put("obj", obj);
					put("fieldName", fieldName);
				}
			});
			return 0;// can't reach
		}
	}

	/**
	 * Checks to see if there is a method with the given name.
	 *
	 * @param luaState
	 *            int that represents the state to be used
	 * @param obj
	 *            object to be inspected
	 * @param methodName
	 *            name of the field to be inpected
	 * @return number of returned objects
	 */
	private static int checkMethod(int luaState, Object obj, String methodName) {
		LuaState L = LuaStateFactory.getExistingState(luaState);

		synchronized (L) {
			Class<?> clazz;

			if (obj instanceof Class) {
				clazz = (Class<?>) obj;
			} else {
				clazz = obj.getClass();
			}

			Method[] methods = clazz.getMethods();

			for (int i = 0; i < methods.length; i++) {
				if (methods[i].getName().equals(methodName))
					return 1;
			}

			return 0;
		}
	}

	/**
	 * Function that creates an object proxy and pushes it into the stack
	 *
	 * @param luaState
	 *            int that represents the state to be used
	 * @param implem
	 *            interfaces implemented separated by comma (,)
	 * @return number of returned objects
	 * @throws LuaException
	 */
	public static int createProxyObject(int luaState, String implem)
			throws LuaException {
		try {
			LuaState L = LuaStateFactory.getExistingState(luaState);

			synchronized (L) {
				try {
					if (!(L.isTable(2)))
						throw new LuaException(
								"Parameter is not a table. Can't create proxy.");

					LuaObject luaObj = L.getLuaObject(2);

					Object proxy = luaObj.createProxy(implem);
					L.pushJavaObject(proxy);
				} catch (Exception e) {
					throw new LuaException(e);
				}

				return 1;
			}
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {

				{
					put("luaState", luaState);
					put("implem", implem);
				}
			});
			return 0;// can't reach
		}
	}

	private static Object compareTypes(LuaState L, Class<?> parameter, int idx)
			throws LuaException {
		try {
			boolean okType = true;
			Object obj = null;

			if (L.isBoolean(idx)) {
				if (parameter.isPrimitive()) {
					if (parameter != Boolean.TYPE) {
						okType = false;
					}
				} else if (!parameter.isAssignableFrom(Boolean.class)) {
					okType = false;
				}
				obj = new Boolean(L.toBoolean(idx));
			} else if (L.type(idx) == LuaState.LUA_TSTRING.intValue()) {
				if (!parameter.isAssignableFrom(String.class)) {
					okType = false;
				} else {
					obj = L.toString(idx);
				}
			} else if (L.isFunction(idx)) {
				if (!parameter.isAssignableFrom(LuaObject.class)) {
					okType = false;
				} else {
					obj = L.getLuaObject(idx);
				}
			} else if (L.isTable(idx)) {
				if (!parameter.isAssignableFrom(LuaObject.class)) {
					okType = false;
				} else {
					obj = L.getLuaObject(idx);
				}
			} else if (L.type(idx) == LuaState.LUA_TNUMBER.intValue()) {
				Double db = new Double(L.toNumber(idx));

				obj = LuaState.convertLuaNumber(db, parameter);
				if (obj == null) {
					okType = false;
				}
			} else if (L.isUserdata(idx)) {
				if (L.isObject(idx)) {
					Object userObj = L.getObjectFromUserdata(idx);
					if (!parameter.isAssignableFrom(userObj.getClass())) {
						okType = false;
					} else {
						obj = userObj;
					}
				} else {
					if (!parameter.isAssignableFrom(LuaObject.class)) {
						okType = false;
					} else {
						obj = L.getLuaObject(idx);
					}
				}
			} else if (L.isNil(idx)) {
				obj = null;
			} else {
				throw new LuaException("Invalid Parameters.");
			}

			if (!okType) {
				throw new LuaException("Invalid Parameter.");
			}

			return obj;
		} catch (Exception e) {
			wrapException(e, new HashMap<String, Object>() {

				{
					put("parameter", parameter);
					put("idx", idx);
				}
			});
			return 0;// can't reach
		}
	}

	private static Method getMethod(LuaState L, Class<?> clazz,
			String methodName, Object[] retObjs, int top) {
		Object[] objs = new Object[top - 1];

		Method[] methods = clazz.getMethods();
		Method method = null;

		// gets method and arguments
		for (int i = 0; i < methods.length; i++) {
			if (!methods[i].getName().equals(methodName))

				continue;

			Class<?>[] parameters = methods[i].getParameterTypes();
			if (parameters.length != top - 1)
				continue;

			boolean okMethod = true;

			for (int j = 0; j < parameters.length; j++) {
				try {
					objs[j] = compareTypes(L, parameters[j], j + 2);
				} catch (Exception e) {
					okMethod = false;
					break;
				}
			}

			if (okMethod) {
				method = methods[i];
				for (int k = 0; k < objs.length; k++)
					retObjs[k] = objs[k];

				break;
			}

		}

		return method;
	}
}


text:
*(optional, in `fixes #<issue number>(, fixes #<issue_number>, ...)` format, will close that issue when PR gets merged)*
  - fixes #

#### Special notes:

#### Checklist chart
[Place an '[x]' (no spaces) in all applicable fields. Please remove unrelated fields.]
- [ ] Chart Version bumped
- [ ] Variables are documented in the README.md

redpajama_set_name: RedPajamaGithub


text:
"""
Setup the strides, padding and filter weight/bias such that
the output shape is (1, 2, 2, 3).
"""
import tensorflow as tf
import numpy as np

# `tf.nn.conv2d` requires the input be 4D (batch_size, height, width, depth)
# (1, 4, 4, 1)
x = np.array([
    [0, 1, 0.5, 10],
    [2, 2.5, 1, -8],
    [4, 0, 5, 6],
    [15, 1, 2, 3]], dtype=np.float32).reshape((1, 4, 4, 1))
X = tf.constant(x)

def conv2d(input):
    # Filter (weights and bias)
    # The shape of the filter weight is (height, width, input_depth, output_depth)
    # The shape of the filter bias is (output_depth,)
    # Define the filter weights `F_W` and filter bias `F_b`.
    # Remember to wrap them in `tf.Variable`, they are trainable parameters after all.
    F_W = tf.Variable(tf.truncated_normal((2, 2, 1, 3)))
    F_b = tf.Variable(tf.zeros(3))
    # Set the stride for each dimension (batch_size, height, width, depth)
    strides = [1, 2, 2, 1]
    # set the padding, either 'VALID' or 'SAME'.
    padding = 'VALID'
    # https://www.tensorflow.org/versions/r0.11/api_docs/python/nn.html#conv2d
    # `tf.nn.conv2d` does not include the bias computation so we have to add it ourselves after.
    return tf.nn.conv2d(input, F_W, strides, padding) + F_b

out = conv2d(X)


text:
An [Ant][ant] & [Ivy][ivy] build for downloading commonly used XML and HTML
schemas.

## Installation

1. Install Ant if not already installed.
2. Run:

    ```bash
    $ git clone https://github.com/eerohele/catalogs.git
    $ cd catalogs
    $ ant
    ```

3. (*Optional*) Set your [`XML_CATALOG_FILES`][xml-catalog-files] environment
   variable to point to the `catalog.xml` file in the repo.

[ant]: https://ant.apache.org
[ivy]: https://ant.apache.org/ivy
[xml-catalog-files]: http://www.xmlsoft.org/catalog.html


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

<title>B-Index</title>
<meta name="date" content="2013-08-16">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L O P Q R S T U V

B

bar - Static variable in class de.mein_plattenregal.R.string

black_overlay - Static variable in class de.mein_plattenregal.R.color

bottom - Static variable in class de.mein_plattenregal.R.id

button2 - Static variable in class de.mein_plattenregal.R.id

button3 - Static variable in class de.mein_plattenregal.R.id

button4 - Static variable in class de.mein_plattenregal.R.id

ButtonBar - Static variable in class de.mein_plattenregal.R.style

ButtonBarButton - Static variable in class de.mein_plattenregal.R.style

buttonBarButtonStyle - Static variable in class de.mein_plattenregal.R.attr

Must be a reference to another resource, in the form "@[+][package:]type:name"
or to a theme attribute in the form "?

ButtonBarContainerTheme - Static variable in class de.mein_plattenregal.R.styleable

Declare custom theme attributes that allow changing which styles are
         used for button bars depending on the API level.
         ?

ButtonBarContainerTheme_buttonBarButtonStyle - Static variable in class de.mein_plattenregal.R.styleable

This symbol is the offset where the R.attr.buttonBarButtonStyle
          attribute's value can be found in the ButtonBarContainerTheme array.

ButtonBarContainerTheme_buttonBarStyle - Static variable in class de.mein_plattenregal.R.styleable

This symbol is the offset where the R.attr.buttonBarStyle
          attribute's value can be found in the ButtonBarContainerTheme array.

buttonBarStyle - Static variable in class de.mein_plattenregal.R.attr

Must be a reference to another resource, in the form "@[+][package:]type:name"
or to a theme attribute in the form "?

buttonSaveSettings - Static variable in class de.mein_plattenregal.R.id

buttonStartActivation - Static variable in class de.mein_plattenregal.R.id

buttonTakeImage - Static variable in class de.mein_plattenregal.R.id

buttonTextActivateDevice - Static variable in class de.mein_plattenregal.R.string

buttonTextAddVinyl - Static variable in class de.mein_plattenregal.R.string

buttonTextSettings - Static variable in class de.mein_plattenregal.R.string

buttonTextShowMyVinyls - Static variable in class de.mein_plattenregal.R.string

A B C D E F G H I L O P Q R S T U V

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package org.elasticsearch.search.aggregations.metrics;

/**
 * Statistics over a set of values (either aggregated over field data or scripts)
 */
public interface ExtendedStats extends Stats {

    /**
     * The sum of the squares of the collected values.
     */
    double getSumOfSquares();

    /**
     * The population variance of the collected values.
     */
    double getVariance();

    /**
     * The population variance of the collected values.
     */
    double getVariancePopulation();

    /**
     * The sampling variance of the collected values.
     */
    double getVarianceSampling();

    /**
     * The population standard deviation of the collected values.
     */
    double getStdDeviation();

    /**
     * The population standard deviation of the collected values.
     */
    double getStdDeviationPopulation();

    /**
     * The sampling standard deviation of the collected values.
     */
    double getStdDeviationSampling();

    /**
     * The upper or lower bounds of the stdDeviation
     */
    double getStdDeviationBound(Bounds bound);

    /**
     * The population standard deviation of the collected values as a String.
     */
    String getStdDeviationAsString();

    /**
     * The population standard deviation of the collected values as a String.
     */
    String getStdDeviationPopulationAsString();

    /**
     * The sampling standard deviation of the collected values as a String.
     */
    String getStdDeviationSamplingAsString();

    /**
     * The upper or lower bounds of stdDev of the collected values as a String.
     */
    String getStdDeviationBoundAsString(Bounds bound);

    /**
     * The sum of the squares of the collected values as a String.
     */
    String getSumOfSquaresAsString();

    /**
     * The population variance of the collected values as a String.
     */
    String getVarianceAsString();

    /**
     * The population variance of the collected values as a String.
     */
    String getVariancePopulationAsString();

    /**
     * The sampling variance of the collected values as a String.
     */
    String getVarianceSamplingAsString();

    enum Bounds {
        UPPER, LOWER, UPPER_POPULATION, LOWER_POPULATION, UPPER_SAMPLING, LOWER_SAMPLING
    }

}


text:
<?php

namespace Cinhetic\PublicBundle\AST\Functions;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\Lexer;

/**
 * Class DateFormat
 * @package Cinhetic\PublicBundle\AST\Functions
 */
class DateFormat extends FunctionNode {

    /*
     * holds the timestamp of the DATE_FORMAT DQL statement
     * @var mixed
     */

    protected $dateExpression;

    /**
     * holds the '%format' parameter of the DATE_FORMAT DQL statement
     * @var string
     */
    protected $formatChar;

    /**
     * getSql - allows ORM to inject a DATE_FORMAT() statement into an SQL string being constructed
     * @param \Doctrine\ORM\Query\SqlWalker $sqlWalker
     * @return void
     */
    public function getSql(SqlWalker $sqlWalker) {
        return sprintf('DATE_FORMAT(%s, %s)',
                $this->dateExpression->dispatch($sqlWalker),
                $this->formatChar->dispatch($sqlWalker));
    }

    /**
     * parse - allows DQL to breakdown the DQL string into a processable structure
     * @param \Doctrine\ORM\Query\Parser $parser
     */
    public function parse(Parser $parser) {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
        $this->dateExpression = $parser->ArithmeticPrimary();
        $parser->match(Lexer::T_COMMA);
        $this->formatChar = $parser->ArithmeticExpression();
        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }

}


text:
package com.xemplar.libs.crypto.server.domain.enums;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonValue;
import com.xemplar.libs.crypto.common.Errors;

@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public enum ConnectionTypes {

	FALSE("false"),
	INBOUND("inbound"),
	OUTBOUND("outbound");

	private final String name;
	ConnectionTypes(String name){
		this.name = name;
	}

	@JsonValue
	public String getName() {
		return name;
	}

	@JsonCreator
	public static ConnectionTypes forName(String name) {
		if (name != null) {
			for (ConnectionTypes connectionType : ConnectionTypes.values()) {
				if (name.equals(connectionType.getName())) {
					return connectionType;
				}
			}
		}
		throw new IllegalArgumentException(Errors.ARGS_CRYPTO_CONNECTIONTYPE_UNSUPPORTED.getDescription());
	}

	public String toString(){
		return name;
	}
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class graph_communicator</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../mpi/reference.html#header.boost.mpi.graph_communicator_hpp" title="Header <boost/mpi/graph_communicator.hpp>">
<link rel="prev" href="../../BOOST_MPI_CHECK_RESULT.html" title="Macro BOOST_MPI_CHECK_RESULT">
<link rel="next" href="get_idp45146672.html" title="Function get">

Home
Libraries
People
FAQ
More

Class graph_communicator

boost::mpi::graph_communicator — An MPI communicator with a graph topology.

Synopsis

// In header: <boost/mpi/graph_communicator.hpp>

class graph_communicator : public boost::mpi::communicator {
public:
  // construct/copy/destruct
  graph_communicator(const MPI_Comm &, comm_create_kind);
  template<typename Graph>
    explicit graph_communicator(const communicator &, const Graph &,
                                bool = false);
  template<typename Graph, typename RankMap>
    explicit graph_communicator(const communicator &, const Graph &, RankMap,
                                bool = false);
};

Description

A graph_communicator is a communicator whose topology is expressed as a graph. Graph communicators have the same functionality as (intra)communicators, but also allow one to query the relationships among processes. Those relationships are expressed via a graph, using the interface defined by the Boost Graph Library. The graph_communicator class meets the requirements of the BGL Graph, Incidence Graph, Adjacency Graph, Vertex List Graph, and Edge List Graph concepts.

graph_communicator
        public
       construct/copy/destruct

graph_communicator(const MPI_Comm & comm, comm_create_kind kind);

Build a new Boost.MPI graph communicator based on the MPI communicator comm with graph topology.

comm may be any valid MPI communicator. If comm is MPI_COMM_NULL, an empty communicator (that cannot be used for communication) is created and the kind parameter is ignored. Otherwise, the kind parameter determines how the Boost.MPI communicator will be related to comm:

If kind is comm_duplicate, duplicate comm to create a new communicator. This new communicator will be freed when the Boost.MPI communicator (and all copies of it) is destroyed. This option is only permitted if the underlying MPI implementation supports MPI 2.0; duplication of intercommunicators is not available in MPI 1.x.

If kind is comm_take_ownership, take ownership of comm. It will be freed automatically when all of the Boost.MPI communicators go out of scope.

If kind is comm_attach, this Boost.MPI communicator will reference the existing MPI communicator comm but will not free comm when the Boost.MPI communicator goes out of scope. This option should only be used when the communicator is managed by the user.

template<typename Graph>
  explicit graph_communicator(const communicator & comm, const Graph & graph,
                              bool reorder = false);

Create a new communicator whose topology is described by the given graph. The indices of the vertices in the graph will be assumed to be the ranks of the processes within the communicator. There may be fewer vertices in the graph than there are processes in the communicator; in this case, the resulting communicator will be a NULL communicator.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Parameters:

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

comm

The communicator that the new, graph communicator will be based on.

graph

Any type that meets the requirements of the Incidence Graph and Vertex List Graph concepts from the Boost Graph Library. This structure of this graph will become the topology of the communicator that is returned.

reorder

Whether MPI is permitted to re-order the process ranks within the returned communicator, to better optimize communication. If false, the ranks of each process in the returned process will match precisely the rank of that process within the original communicator.

template<typename Graph, typename RankMap>
  explicit graph_communicator(const communicator & comm, const Graph & graph,
                              RankMap rank, bool reorder = false);

Create a new communicator whose topology is described by the given graph. The rank map (rank) gives the mapping from vertices in the graph to ranks within the communicator. There may be fewer vertices in the graph than there are processes in the communicator; in this case, the resulting communicator will be a NULL communicator.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Parameters:

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

comm

The communicator that the new, graph communicator will be based on. The ranks in rank refer to the processes in this communicator.

graph

Any type that meets the requirements of the Incidence Graph and Vertex List Graph concepts from the Boost Graph Library. This structure of this graph will become the topology of the communicator that is returned.

rank

This map translates vertices in the graph into ranks within the current communicator. It must be a Readable Property Map (see the Boost Property Map library) whose key type is the vertex type of the graph and whose value type is int.

reorder

Whether MPI is permitted to re-order the process ranks within the returned communicator, to better optimize communication. If false, the ranks of each process in the returned process will match precisely the rank of that process within the original communicator.

Copyright © 2005-2007 Douglas Gregor,
      Matthias Troyer, Trustees of Indiana University

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at
        http://www.boost.org/LICENSE_1_0.txt )


text:
declare module "inuit.tools.functions" {
	/**
	* divides a number by 4 and rounds
	*/
	function quarter(n: number): number;
	/**
	* divides a number by 2 and rounds
	*/
	function halve(n: number): number;
	// ReSharper disable once UsingOfReservedWord
	/**
	* doubles and rounds a number
	*/
	function double(n: number): number;
	/**
	* quadruples and rounds a number
	*/
	function quadruple(n: number): number;
}


text:
require 'test_helper'

class SurveyResponsesHelperTest < ActionView::TestCase
  include SurveysHelper

  describe '#survey_release_text' do
    it "returns 'Pull release' if the survey is released" do
      survey = surveys(:ps1)
      assert_equal true, survey.released?
      assert_equal 'Pull release', survey_release_text(survey)
    end

    it "returns 'Release' if the survey is not released" do
      survey = surveys(:project)
      assert_equal false, survey.released?
      assert_equal 'Release', survey_release_text(survey)
    end
  end
end


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="com.sbhachu.audioplayer.presentation.fragment.ArtistListFragment">

    <ListView
        android:id="@+id/genre_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:choiceMode="singleChoice"
        android:divider="@color/navigation_drawer_list_divider"
        android:listSelector="@drawable/track_list_item_background_selector"
        android:dividerHeight="1dp" />

    <ProgressBar
        android:id="@+id/genre_progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        android:indeterminate="true"
        android:indeterminateDrawable="@drawable/custom_progressbar_round" />

</FrameLayout>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Brittonia 30:468. 1978

#### Original name
null

### Remarks
null


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// System.MonoTODOAttribute
struct MonoTODOAttribute_t2091695242;
// System.String
struct String_t;

#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_String7231557.h"

// System.Void System.MonoTODOAttribute::.ctor()
extern "C"  void MonoTODOAttribute__ctor_m754636072 (MonoTODOAttribute_t2091695242 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.MonoTODOAttribute::.ctor(System.String)
extern "C"  void MonoTODOAttribute__ctor_m3809503962 (MonoTODOAttribute_t2091695242 * __this, String_t* ___comment0, const MethodInfo* method) IL2CPP_METHOD_ATTR;


text: module.exports = require('./bin/gitj');


text:
import { all, call, put, select, takeEvery } from 'redux-saga/effects';

import {
  FETCH_MORE_RECIPES,
  fetchMoreRecipesFailure,
  fetchMoreRecipesPending,
  fetchMoreRecipesSuccessful,
  SEARCH,
  searchFailure,
  searchPending,
  searchSuccessful
} from './actions';
import { search } from '../api/edamam';
import { currentSearchQuery, numLoadedRecipes } from './selectors';
import { BATCH_RECIPE_FETCH_SIZE } from '../enums/app';

function* searchWorker({ payload }) {
  yield put(searchPending());
  try {
    const { data } = yield call(search, { queryString: payload.toLowerCase() });
    yield put(searchSuccessful(data));
  } catch (e) {
    console.error(e);
    yield put(searchFailure());
  }
}

function* searchSaga() {
  yield takeEvery(SEARCH, searchWorker);
}

function* fetchMoreRecipesWorker() {
  yield put(fetchMoreRecipesPending());

  const queryString = yield select(currentSearchQuery);
  const from = yield select(numLoadedRecipes);

  try {
    const { data } = yield call(search, {
      from,
      queryString,
      to: from + BATCH_RECIPE_FETCH_SIZE
    });
    yield put(fetchMoreRecipesSuccessful(data));
  } catch (e) {
    console.error(e);
    yield put(fetchMoreRecipesFailure());
  }
}

function* fetchMoreRecipesSaga() {
  yield takeEvery(FETCH_MORE_RECIPES, fetchMoreRecipesWorker);
}

export default function* rootSaga() {
  yield all([searchSaga(), fetchMoreRecipesSaga()]);
}


text:
from django.db.backends import BaseDatabaseOperations
from sql_server.pyodbc import query
import datetime
import time
import decimal

class DatabaseOperations(BaseDatabaseOperations):
    compiler_module = "sql_server.pyodbc.compiler"
    def __init__(self, connection):
        super(DatabaseOperations, self).__init__(connection)
        self.connection = connection
        self._ss_ver = None

    def _get_sql_server_ver(self):
        """
        Returns the version of the SQL Server in use:
        """
        if self._ss_ver is not None:
            return self._ss_ver
        cur = self.connection.cursor()
        cur.execute("SELECT CAST(SERVERPROPERTY('ProductVersion') as varchar)")
        ver_code = int(cur.fetchone()[0].split('.')[0])
        if ver_code >= 10:
            self._ss_ver = 2008
        elif ver_code == 9:
            self._ss_ver = 2005
        else:
            self._ss_ver = 2000
        return self._ss_ver
    sql_server_ver = property(_get_sql_server_ver)

    def date_extract_sql(self, lookup_type, field_name):
        """
        Given a lookup_type of 'year', 'month', 'day' or 'week_day', returns
        the SQL that extracts a value from the given date field field_name.
        """
        if lookup_type == 'week_day':
            return "DATEPART(dw, %s)" % field_name
        else:
            return "DATEPART(%s, %s)" % (lookup_type, field_name)

    def date_trunc_sql(self, lookup_type, field_name):
        """
        Given a lookup_type of 'year', 'month' or 'day', returns the SQL that
        truncates the given date field field_name to a DATE object with only
        the given specificity.
        """
        if lookup_type == 'year':
            return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/01/01')" % field_name
        if lookup_type == 'month':
            return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/' + Convert(varchar, DATEPART(month, %s)) + '/01')" % (field_name, field_name)
        if lookup_type == 'day':
            return "Convert(datetime, Convert(varchar(12), %s, 112))" % field_name

    def field_cast_sql(self, db_type):
        """
        Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessary
        to cast it before using it in a WHERE statement. Note that the
        resulting string should contain a '%s' placeholder for the column being
        searched against.
        """
        if self.sql_server_ver < 2005 and db_type and db_type.lower() == 'ntext':
            return 'CAST(%s as nvarchar)'
        return '%s'

    def fulltext_search_sql(self, field_name):
        """
        Returns the SQL WHERE clause to use in order to perform a full-text
        search of the given field_name. Note that the resulting string should
        contain a '%s' placeholder for the value being searched against.
        """
        return 'CONTAINS(%s, %%s)' % field_name

    def last_insert_id(self, cursor, table_name, pk_name):
        """
        Given a cursor object that has just performed an INSERT statement into
        a table that has an auto-incrementing ID, returns the newly created ID.

        This method also receives the table name and the name of the primary-key
        column.
        """
        # TODO: Check how the `last_insert_id` is being used in the upper layers
        #       in context of multithreaded access, compare with other backends

        # IDENT_CURRENT:  http://msdn2.microsoft.com/en-us/library/ms175098.aspx
        # SCOPE_IDENTITY: http://msdn2.microsoft.com/en-us/library/ms190315.aspx
        # @@IDENTITY:     http://msdn2.microsoft.com/en-us/library/ms187342.aspx

        # IDENT_CURRENT is not limited by scope and session; it is limited to
        # a specified table. IDENT_CURRENT returns the value generated for
        # a specific table in any session and any scope.
        # SCOPE_IDENTITY and @@IDENTITY return the last identity values that
        # are generated in any table in the current session. However,
        # SCOPE_IDENTITY returns values inserted only within the current scope;
        # @@IDENTITY is not limited to a specific scope.

        table_name = self.quote_name(table_name)
        cursor.execute("SELECT CAST(IDENT_CURRENT(%s) as bigint)", [table_name])
        return cursor.fetchone()[0]

    def fetch_returned_insert_id(self, cursor):
        """
        Given a cursor object that has just performed an INSERT/OUTPUT statement
        into a table that has an auto-incrementing ID, returns the newly created
        ID.
        """
        return cursor.fetchone()[0]

    def lookup_cast(self, lookup_type):
        if lookup_type in ('iexact', 'icontains', 'istartswith', 'iendswith'):
            return "UPPER(%s)"
        return "%s"

    def query_class(self, DefaultQueryClass):
        """
        Given the default Query class, returns a custom Query class
        to use for this backend. Returns None if a custom Query isn't used.
        See also BaseDatabaseFeatures.uses_custom_query_class, which regulates
        whether this method is called at all.
        """
        return query.query_class(DefaultQueryClass)

    def quote_name(self, name):
        """
        Returns a quoted version of the given table, index or column name. Does
        not quote the given name if it's already been quoted.
        """
        if name.startswith('[') and name.endswith(']'):
            return name # Quoting once is enough.
        return '[%s]' % name

    def random_function_sql(self):
        """
        Returns a SQL expression that returns a random value.
        """
        return "RAND()"

    def last_executed_query(self, cursor, sql, params):
        """
        Returns a string of the query last executed by the given cursor, with
        placeholders replaced with actual values.

        `sql` is the raw query containing placeholders, and `params` is the
        sequence of parameters. These are used by default, but this method
        exists for database backends to provide a better implementation
        according to their own quoting schemes.
        """
        return super(DatabaseOperations, self).last_executed_query(cursor, cursor.last_sql, cursor.last_params)

    #def savepoint_create_sql(self, sid):
    #    """
    #    Returns the SQL for starting a new savepoint. Only required if the
    #    "uses_savepoints" feature is True. The "sid" parameter is a string
    #    for the savepoint id.
    #    """
    #    return "SAVE TRANSACTION %s" % sid

    #def savepoint_commit_sql(self, sid):
    #    """
    #    Returns the SQL for committing the given savepoint.
    #    """
    #    return "COMMIT TRANSACTION %s" % sid

    #def savepoint_rollback_sql(self, sid):
    #    """
    #    Returns the SQL for rolling back the given savepoint.
    #    """
    #    return "ROLLBACK TRANSACTION %s" % sid

    def sql_flush(self, style, tables, sequences):
        """
        Returns a list of SQL statements required to remove all data from
        the given database tables (without actually removing the tables
        themselves).

        The `style` argument is a Style object as returned by either
        color_style() or no_style() in django.core.management.color.
        """
        if tables:
            # Cannot use TRUNCATE on tables that are referenced by a FOREIGN KEY
            # So must use the much slower DELETE
            from django.db import connection
            cursor = connection.cursor()
            # Try to minimize the risks of the braindeaded inconsistency in
            # DBCC CHEKIDENT(table, RESEED, n) behavior.
            seqs = []
            for seq in sequences:
                cursor.execute("SELECT COUNT(*) FROM %s" % self.quote_name(seq["table"]))
                rowcnt = cursor.fetchone()[0]
                elem = {}
                if rowcnt:
                    elem['start_id'] = 0
                else:
                    elem['start_id'] = 1
                elem.update(seq)
                seqs.append(elem)
            cursor.execute("SELECT TABLE_NAME, CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE not in ('PRIMARY KEY','UNIQUE')")
            fks = cursor.fetchall()
            sql_list = ['ALTER TABLE %s NOCHECK CONSTRAINT %s;' % \
                    (self.quote_name(fk[0]), self.quote_name(fk[1])) for fk in fks]
            sql_list.extend(['%s %s %s;' % (style.SQL_KEYWORD('DELETE'), style.SQL_KEYWORD('FROM'),
                             style.SQL_FIELD(self.quote_name(table)) ) for table in tables])
            # Then reset the counters on each table.
            sql_list.extend(['%s %s (%s, %s, %s) %s %s;' % (
                style.SQL_KEYWORD('DBCC'),
                style.SQL_KEYWORD('CHECKIDENT'),
                style.SQL_FIELD(self.quote_name(seq["table"])),
                style.SQL_KEYWORD('RESEED'),
                style.SQL_FIELD('%d' % seq['start_id']),
                style.SQL_KEYWORD('WITH'),
                style.SQL_KEYWORD('NO_INFOMSGS'),
                ) for seq in seqs])
            sql_list.extend(['ALTER TABLE %s CHECK CONSTRAINT %s;' % \
                    (self.quote_name(fk[0]), self.quote_name(fk[1])) for fk in fks])
            return sql_list
        else:
            return []

    #def sequence_reset_sql(self, style, model_list):
    #    """
    #    Returns a list of the SQL statements required to reset sequences for
    #    the given models.
    #
    #    The `style` argument is a Style object as returned by either
    #    color_style() or no_style() in django.core.management.color.
    #    """
    #    from django.db import models
    #    output = []
    #    for model in model_list:
    #        for f in model._meta.local_fields:
    #            if isinstance(f, models.AutoField):
    #                output.append(...)
    #                break # Only one AutoField is allowed per model, so don't bother continuing.
    #        for f in model._meta.many_to_many:
    #            output.append(...)
    #    return output

    def start_transaction_sql(self):
        """
        Returns the SQL statement required to start a transaction.
        """
        return "BEGIN TRANSACTION"

    def sql_for_tablespace(self, tablespace, inline=False):
        """
        Returns the SQL that will be appended to tables or rows to define
        a tablespace. Returns '' if the backend doesn't use tablespaces.
        """
        return "ON %s" % self.quote_name(tablespace)

    def prep_for_like_query(self, x):
        """Prepares a value for use in a LIKE query."""
        from django.utils.encoding import smart_unicode
        # http://msdn2.microsoft.com/en-us/library/ms179859.aspx
        return smart_unicode(x).replace('\\', '\\\\').replace('[', '[[]').replace('%', '[%]').replace('_', '[_]')

    def prep_for_iexact_query(self, x):
        """
        Same as prep_for_like_query(), but called for "iexact" matches, which
        need not necessarily be implemented using "LIKE" in the backend.
        """
        return x

    def value_to_db_datetime(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.
        """
        if value is None:
            return None
        # SQL Server doesn't support microseconds
        return value.replace(microsecond=0)

    def value_to_db_time(self, value):
        """
        Transform a time value to an object compatible with what is expected
        by the backend driver for time columns.
        """
        if value is None:
            return None
        # SQL Server doesn't support microseconds
        if isinstance(value, basestring):
            return datetime.datetime(*(time.strptime(value, '%H:%M:%S')[:6]))
        return datetime.datetime(1900, 1, 1, value.hour, value.minute, value.second)

    def year_lookup_bounds(self, value):
        """
        Returns a two-elements list with the lower and upper bound to be used
        with a BETWEEN operator to query a field value using a year lookup

        `value` is an int, containing the looked-up year.
        """
        first = '%s-01-01 00:00:00'
        # SQL Server doesn't support microseconds
        last = '%s-12-31 23:59:59'
        return [first % value, last % value]
    def value_to_db_decimal(self, value, max_digits, decimal_places):
        """
        Transform a decimal.Decimal value to an object compatible with what is
        expected by the backend driver for decimal (numeric) columns.
        """
        if value is None:
            return None
        if isinstance(value, decimal.Decimal):
            context = decimal.getcontext().copy()
            context.prec = max_digits
            return u"%.*f" % (decimal_places, value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
        else:
            return u"%.*f" % (decimal_places, value)

    def convert_values(self, value, field):
        """
        Coerce the value returned by the database backend into a consistent
        type that is compatible with the field type.

        In our case, cater for the fact that SQL Server < 2008 has no
        separate Date and Time data types.
        TODO: See how we'll handle this for SQL Server >= 2008
        """
        if value is None:
            return None
        if field and field.get_internal_type() == 'DateTimeField':
            return value
        elif field and field.get_internal_type() == 'DateField':
            value = value.date() # extract date
        elif field and field.get_internal_type() == 'TimeField' or (isinstance(value, datetime.datetime) and value.year == 1900 and value.month == value.day == 1):
            value = value.time() # extract time
        # Some cases (for example when select_related() is used) aren't
        # caught by the DateField case above and date fields arrive from
        # the DB as datetime instances.
        # Implement a workaround stealing the idea from the Oracle
        # backend. It's not perfect so the same warning applies (i.e. if a
        # query results in valid date+time values with the time part set
        # to midnight, this workaround can surprise us by converting them
        # to the datetime.date Python type).
        elif isinstance(value, datetime.datetime) and value.hour == value.minute == value.second == value.microsecond == 0:
            value = value.date()
        # Force floats to the correct type
        elif value is not None and field and field.get_internal_type() == 'FloatField':
            value = float(value)
        return value


text:
class DigitalSignatureStringToInt < ActiveRecord::Migration
  def change
    remove_column :digital_signatures, :intent
    add_column :digital_signatures, :intent, :integer
  end
end


text:
[![Build Status](https://travis-ci.org/chicio/Ray-tracing.svg?branch=master)](https://travis-ci.org/chicio/Ray-tracing)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/chicio/Ray-Tracing/master/LICENSE.md)
[![Supported platform](https://img.shields.io/badge/platforms-iOS-orange.svg)](https://img.shields.io/badge/platforms-iOS-orange.svg)

Ray tracer for iPad developed as final project for my computer graphics course at University Milano-Bicocca.

***

### Main features
- Support sphere and convex polygon
- Phong and Blinn-Phong lighting model
    * light attenuation factor
- Reflection and Refraction
    * Reflective objects
    * Transparent objects
    * Realistic transparency for dieletrics using:
         * Fresnel equations
         * Schlick's approximation
    * Multiple reflective objects in the same scene.
- Camera
- Soft shadow
- Antialiasing (Supersampling)
- Cube mapping (used for skybox at infinite distance)
- Procedural texture with Perlin Noise
    * Marble
    * Turbulence
- Bump mapping

***

### Screenshot

These are some images rendered using the ray tracer. For each one there's a complete list of the setup used during rendering.

**Scene 1**: Antialisasing, soft shadow (128 shadow feeler ray), Phong lighting, cube mapping infinite skybox, bump mapping,  sphere dielectric (glass refractive index) using Fresnel equation

**Scene 1**: Antialisasing, soft shadow (128 shadow feeler ray), Blinn-Phong lighting, cube mapping infinite skybox, bump mapping, sphere dielectric (glass refractive index) using Fresnel equation

**Scene 2a**: Antialisasing, soft shadow (128 shadow feeler ray), Phong lighting, polygon skybox, bump mapping, procedural texture with perlin noise, sphere dielectric (glass refractive index) using Fresnel equation

**Scene 2a**:  Antialisasing, soft shadow (16 shadow feeler ray), Phong lighting, polygon skybox, bump mapping, procedural texture with perlin noise, sphere dielectric (glass refractive index) using Fresnel equation, quadratic light attenuation

**Scene 2b**: Antialisasing, soft shadow (16 shadow feeler ray), Blinn-Phong lighting, polygon skybox, procedural texture with perlin noise, camera on left side, sphere dielectric (glass refractive index) using Fresnel equation

**Scene 2b**: Antialisasing, soft shadow (16 shadow feeler ray), Phong lighting, polygon skybox, procedural texture with perlin noise, camera on left side, sphere dielectric (glass refractive index) using Schlick's approximation

***

### Description

The ray tracer is developed entirely in Objective-C as an iPad app.
The interface let the user manage some of the options available:
- change of scene to be rendered
- turn on/off antialiasing
- turn on/off softshadow
- choose the camera position between 6 predefined option
- Phong/Blinn-Phong lighting model

There are other option defined as constant in the file Constants.h that affected the behaviour of the ray tracer. In particular it is possible to set/change:
- the max number ray bounce (default 3 bounce)
- the number of shadow feeler ray (default 16)
- the light attenuation factors
- dieletric simulation (default off/false)
   * the equation used for fresnel factor (used only if dieletric simulation is on - default Fresnel equation).

This is a screenshot of the application interface.

![Application interface](https://raw.githubusercontent.com/chicio/Ray-tracing/master/Screenshots/application_interface_with_ipad.png)

The part of the image already calculated is shown to the user, so that it could have a feedback during rendering operation.
This is done using an asynchronous block submitted to a new quality of service class available in iOS 8 and above.

To speed up the entire process of ray tracing some part of the ray tracer are splitted across multiple threads.
Usually the tecnique used is to divide in n pieces the image to be rendered, one for every core of the cpu on which you will execute the ray tracing operation in a thread and then sum up the the various result. In this case I used a different approch: the heavy part of the computation is releated to the soft shadows calculation, so I use Grand Central Dispatch to execute each shadow feeler ray calculation in a dedicated asynchronous block. In this way I can output the image rows already calculated using the technique describe above (my rasterizer need continuos block of image data to generate the piece of the image).

Finally, most of the core implementation of the ray tracer are inspired by the course material and by studying/reading the book "Ray tracing from the ground up", Kevin Suffern 2007, used as main additional material to the course slides. See the list below for a complete reference to the main study documents.

***

### Documentation

All classes, methods and variables are documented with comments using sourcekit tags. Using XCode it is possible to access the documentation while reading the code using Alt + left mouse click.

![Documentation](https://raw.githubusercontent.com/chicio/Ray-tracing/master/Screenshots/documentation.png)

***

### References

Main references:
* Course slides
* ["Ray tracing from the ground up", Kevin Suffern 2007](http://www.raytracegroundup.com)
* [Ray tracing Tutorial by Codermind team](http://www.ics.uci.edu/~gopi/CS211B/RayTracing%20tutorial.pdf)
* [Ray Tracing: Graphics for the Masses](https://www.cs.unc.edu/~rademach/xroads-RT/RTarticle.html)

Other link to the documentation and code examples used during development are referenced inside every method comment using sourcekit tag @see (see "Documentation" section).


text:
//
//  CustomDatePicker.m
//  CustomInputTextField
//
//  Created by Syouta Nakagaki on 2016/07/25.
//  Copyright © 2016年 Syouta Nakagaki. All rights reserved.
//

#import "CustomDatePicker.h"

@implementation CustomDatePicker

#pragma mark Setter methods
- (void)setDatePickerMode:(UIDatePickerMode)datePickerMode {
    [super setDatePickerMode:datePickerMode];
    [self.delegate customDatePicker:self didChangeDatePickerMode:datePickerMode];
}

#pragma mark - Initializer
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

- (instancetype)init {
    return [self initWithFrame:CGRectZero];
}

#pragma mark Initializer (from xib)
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {

    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
#ifndef __itkNeuralNetworkObject_h
#define __itkNeuralNetworkObject_h

#include "itkDataObject.h"
#include "itkLayerBase.h"
#include "itkLearningFunctionBase.h"

namespace itk
{
namespace Statistics
{
template<class TMeasurementVector, class TTargetVector >
class NeuralNetworkObject : public DataObject
{
public:

  typedef NeuralNetworkObject      Self;
  typedef DataObject               Superclass;
  typedef SmartPointer<Self>       Pointer;
  typedef SmartPointer<const Self> ConstPointer;

  itkTypeMacro(NeuralNetworkObject, DataObject);

  typedef TMeasurementVector                        MeasurementVectorType;
  typedef typename MeasurementVectorType::ValueType ValueType;
  typedef Array<ValueType>                          NetworkOutputType;
  typedef TTargetVector                             TargetVectorType;

  typedef LayerBase<TMeasurementVector, TTargetVector> LayerInterfaceType;

  virtual NetworkOutputType GenerateOutput(TMeasurementVector samplevector)=0;

  virtual void BackwardPropagate(NetworkOutputType errors) = 0;
  virtual void UpdateWeights(ValueType) = 0;

protected:

  NeuralNetworkObject();
  virtual ~NeuralNetworkObject();

  /** Method to print the object. */
  virtual void PrintSelf( std::ostream& os, Indent indent ) const;

  ValueType m_LearningRate;

};

} // end namespace Statistics
} // end namespace itk

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

#endif


text:
#include "squid.h"

/* local constants */

/* these entity-headers must be ignored if a bogus server sends them in 304 */
static HttpHeaderMask Denied304HeadersMask;
static http_hdr_type Denied304HeadersArr[] =
{
    HDR_CONTENT_ENCODING, HDR_CONTENT_LANGUAGE, HDR_CONTENT_LENGTH,
    HDR_CONTENT_LOCATION, HDR_CONTENT_RANGE
};

/* local routines */
static void httpReplyInit(HttpReply * rep);
static void httpReplyClean(HttpReply * rep);
static void httpReplyDoDestroy(HttpReply * rep);
static void httpReplyHdrCacheInit(HttpReply * rep);
static void httpReplyHdrCacheClean(HttpReply * rep);
static int httpReplyParseStep(HttpReply * rep, const char *parse_start, int len);
static int httpReplyParseError(HttpReply * rep);
static time_t httpReplyHdrExpirationTime(const HttpReply * rep);

/* module initialization */
void
httpReplyInitModule(void)
{
    httpHeaderMaskInit(&Denied304HeadersMask, 0);
    httpHeaderCalcMask(&Denied304HeadersMask, Denied304HeadersArr, countof(Denied304HeadersArr));
}

HttpReply *
httpReplyCreate(void)
{
    HttpReply *rep = memAllocate(MEM_HTTP_REPLY);
    debug(58, 7) ("creating rep: %p\n", rep);
    httpReplyInit(rep);
    return rep;
}

static void
httpReplyInit(HttpReply * rep)
{
    assert(rep);
    rep->hdr_sz = 0;
    rep->pstate = psReadyToParseStartLine;
    httpBodyInit(&rep->body);
    httpHeaderInit(&rep->header, hoReply);
    httpReplyHdrCacheInit(rep);
    httpStatusLineInit(&rep->sline);
}

static void
httpReplyClean(HttpReply * rep)
{
    assert(rep);
    httpBodyClean(&rep->body);
    httpReplyHdrCacheClean(rep);
    httpHeaderClean(&rep->header);
    httpStatusLineClean(&rep->sline);
}

void
httpReplyDestroy(HttpReply * rep)
{
    assert(rep);
    debug(58, 7) ("destroying rep: %p\n", rep);
    httpReplyClean(rep);
    httpReplyDoDestroy(rep);
}

void
httpReplyReset(HttpReply * rep)
{
    httpReplyClean(rep);
    httpReplyInit(rep);
}

/* absorb: copy the contents of a new reply to the old one, destroy new one */
static void
httpReplyAbsorb(HttpReply * rep, HttpReply * new_rep)
{
    assert(rep && new_rep);
    httpReplyClean(rep);
    *rep = *new_rep;
    /* cannot use Clean() on new reply now! */
    httpReplyDoDestroy(new_rep);
}

/*
 * httpReplyParse takes character buffer of HTTP headers (buf),
 * which may not be NULL-terminated, and fills in an HttpReply
 * structure (rep).  The parameter 'end' specifies the offset to
 * the end of the reply headers.  The caller may know where the
 * end is, but is unable to NULL-terminate the buffer.  This function
 * returns true on success.
 */
int
httpReplyParse(HttpReply * rep, const char *buf, size_t end)
{
    /* The code called by httpReplyParseStep doesn't assume NUL-terminated stuff! */
    httpReplyReset(rep);
    return (httpReplyParseStep(rep, buf, end) == 1);
}

void
httpReplyPackInto(const HttpReply * rep, Packer * p)
{
    assert(rep);
    httpStatusLinePackInto(&rep->sline, p);
    httpHeaderPackInto(&rep->header, p);
    packerAppend(p, "\r\n", 2);
    httpBodyPackInto(&rep->body, p);
}

/* create memBuf, create mem-based packer,  pack, destroy packer, return MemBuf */
MemBuf
httpReplyPack(const HttpReply * rep)
{
    MemBuf mb;
    Packer p;
    assert(rep);

    memBufDefInit(&mb);
    packerToMemInit(&p, &mb);
    httpReplyPackInto(rep, &p);
    packerClean(&p);
    return mb;
}

/* swap: create swap-based packer, pack, destroy packer. Absorbs the reply */
void
httpReplySwapOut(HttpReply * rep, StoreEntry * e)
{
    Packer p;
    assert(rep && e);

    /* storeBuffer should have been done by the caller, but do it here just in case as things
     * break badly if not
     */
    storeBuffer(e);
    if (rep != e->mem_obj->reply) {
	httpReplyAbsorb(e->mem_obj->reply, rep);
	rep = e->mem_obj->reply;
    }
    packerToStoreInit(&p, e);
    httpReplyPackInto(e->mem_obj->reply, &p);
    packerClean(&p);
    rep->hdr_sz = e->mem_obj->inmem_hi - rep->body.mb.size;
}

#if UNUSED_CODE
MemBuf
httpPackedReply(http_status status, const char *ctype,
    squid_off_t clen, time_t lmt, time_t expires)
{
    HttpReply *rep = httpReplyCreate();
    MemBuf mb;
    httpReplySetHeaders(rep, status, ctype, NULL, clen, lmt, expires);
    mb = httpReplyPack(rep);
    httpReplyDestroy(rep);
    return mb;
}
#endif

MemBuf
httpPacked304Reply(const HttpReply * rep, int http11)
{
    static const http_hdr_type ImsEntries[] =
    {HDR_DATE, HDR_CONTENT_TYPE, HDR_EXPIRES, HDR_LAST_MODIFIED, HDR_ETAG, /* eof */ HDR_OTHER};
    int t;
    MemBuf mb;
    Packer p;
    HttpHeaderEntry *e;
    assert(rep);

    memBufDefInit(&mb);
    packerToMemInit(&p, &mb);
    memBufPrintf(&mb, "HTTP/1.%d 304 Not Modified\r\n", http11);
    for (t = 0; ImsEntries[t] != HDR_OTHER; ++t)
	if ((e = httpHeaderFindEntry(&rep->header, ImsEntries[t])))
	    httpHeaderEntryPackInto(e, &p);
    memBufAppend(&mb, "\r\n", 2);
    packerClean(&p);
    return mb;
}

void
httpReplySetHeaders(HttpReply * reply, http_status status, const char *reason,
    const char *ctype, squid_off_t clen, time_t lmt, time_t expires)
{
    HttpHeader *hdr;
    static const http_version_t ver =
    {1, 0};
    assert(reply);
    httpStatusLineSet(&reply->sline, ver, status, reason);
    hdr = &reply->header;
    httpHeaderPutStr(hdr, HDR_SERVER, visible_appname_string);
    httpHeaderPutTime(hdr, HDR_DATE, squid_curtime);
    if (ctype) {
	httpHeaderPutStr(hdr, HDR_CONTENT_TYPE, ctype);
	stringInit(&reply->content_type, ctype);
    } else
	reply->content_type = StringNull;
    if (clen >= 0)
	httpHeaderPutSize(hdr, HDR_CONTENT_LENGTH, clen);
    if (expires >= 0)
	httpHeaderPutTime(hdr, HDR_EXPIRES, expires);
    if (lmt > 0)		/* this used to be lmt != 0 @?@ */
	httpHeaderPutTime(hdr, HDR_LAST_MODIFIED, lmt);
    reply->date = squid_curtime;
    reply->content_length = clen;
    reply->expires = expires;
    reply->last_modified = lmt;
    reply->pstate = psParsed;
}

void
httpRedirectReply(HttpReply * reply, http_status status, const char *loc)
{
    HttpHeader *hdr;
    http_version_t ver;
    assert(reply);
    httpBuildVersion(&ver, 1, 1);
    httpStatusLineSet(&reply->sline, ver, status, httpStatusString(status));
    hdr = &reply->header;
    httpHeaderPutStr(hdr, HDR_SERVER, full_appname_string);
    httpHeaderPutTime(hdr, HDR_DATE, squid_curtime);
    httpHeaderPutSize(hdr, HDR_CONTENT_LENGTH, 0);
    httpHeaderPutStr(hdr, HDR_LOCATION, loc);
    reply->date = squid_curtime;
    reply->content_length = 0;
    reply->pstate = psParsed;
}

void
httpReplyUpdateOnNotModified(HttpReply * rep, HttpReply * freshRep)
{
    assert(rep && freshRep);
    /* clean cache */
    httpReplyHdrCacheClean(rep);
    /* update raw headers */
    httpHeaderDelById(&rep->header, HDR_AGE);
    httpHeaderUpdate(&rep->header, &freshRep->header,
	(const HttpHeaderMask *) &Denied304HeadersMask);
    /* init cache */
    httpReplyHdrCacheInit(rep);
}

/* internal routines */

/* internal function used by Destroy and Absorb */
static void
httpReplyDoDestroy(HttpReply * rep)
{
    memFree(rep, MEM_HTTP_REPLY);
}

static time_t
httpReplyHdrExpirationTime(const HttpReply * rep)
{
    /* The s-maxage and max-age directive takes priority over Expires */
    if (rep->cache_control) {
	if (rep->date >= 0) {
	    if (rep->cache_control->s_maxage >= 0)
		return rep->date + rep->cache_control->s_maxage;
	    if (rep->cache_control->max_age >= 0)
		return rep->date + rep->cache_control->max_age;
	} else {
	    /*
	     * Conservatively handle the case when we have a max-age
	     * header, but no Date for reference?
	     */
	    if (rep->cache_control->s_maxage >= 0)
		return squid_curtime;
	    if (rep->cache_control->max_age >= 0)
		return squid_curtime;
	}
    }
    if (Config.onoff.vary_ignore_expire &&
	httpHeaderHas(&rep->header, HDR_VARY)) {
	const time_t d = httpHeaderGetTime(&rep->header, HDR_DATE);
	const time_t e = httpHeaderGetTime(&rep->header, HDR_EXPIRES);
	if (d == e)
	    return -1;
    }
    if (httpHeaderHas(&rep->header, HDR_EXPIRES)) {
	const time_t e = httpHeaderGetTime(&rep->header, HDR_EXPIRES);
	/*
	 * HTTP/1.1 says that robust implementations should consider
	 * bad or malformed Expires header as equivalent to "expires
	 * immediately."
	 */
	return e < 0 ? squid_curtime : e;
    }
    return -1;
}

/* sync this routine when you update HttpReply struct */
static void
httpReplyHdrCacheInit(HttpReply * rep)
{
    const HttpHeader *hdr = &rep->header;
    const char *str;
    rep->content_length = httpHeaderGetSize(hdr, HDR_CONTENT_LENGTH);
    rep->date = httpHeaderGetTime(hdr, HDR_DATE);
    rep->last_modified = httpHeaderGetTime(hdr, HDR_LAST_MODIFIED);
    str = httpHeaderGetStr(hdr, HDR_CONTENT_TYPE);
    if (str)
	stringLimitInit(&rep->content_type, str, strcspn(str, ";\t "));
    else
	rep->content_type = StringNull;
    rep->cache_control = httpHeaderGetCc(hdr);
    rep->content_range = httpHeaderGetContRange(hdr);
    rep->keep_alive = httpMsgIsPersistent(rep->sline.version, &rep->header);
    /* be sure to set expires after date and cache-control */
    rep->expires = httpReplyHdrExpirationTime(rep);
}

HttpReply *
httpReplyClone(HttpReply * src)
{
    HttpReply *dst = httpReplyCreate();

    /* basic variables */
    dst->hdr_sz = src->hdr_sz;

    /* parser state */
    dst->pstate = src->pstate;
    /* status line */
    dst->sline = src->sline;
    /* header */
    httpHeaderAppend(&dst->header, &src->header);
    /* body, if applicable */
    if (dst->body.mb.buf != NULL)
	memBufAppend(&dst->body.mb, dst->body.mb.buf, dst->body.mb.size);

    /*
     * The next two are a bit .. special. I hate delving into the headers
     * when we've already -done- that, but I'll worry about doing it
     * faster later. Besides, there's too much other code to fix up.
     */
    httpReplyHdrCacheInit(dst);
#if 0
    dst->content_length = src->content_length;
    dst->date = src->date;
    dst->last_modified = src->last_modified;
    dst->expires = src->expires;
    dst->cache_control = httpHeaderGetCc(&dst->header);
    dst->content_range = httpHeaderGetContRange(&dst->header);
#endif

    return dst;
}

/* sync this routine when you update HttpReply struct */
static void
httpReplyHdrCacheClean(HttpReply * rep)
{
    stringClean(&rep->content_type);
    if (rep->cache_control)
	httpHdrCcDestroy(rep->cache_control);
    if (rep->content_range)
	httpHdrContRangeDestroy(rep->content_range);
}

/*
 * parses a 0-terminating buffer into HttpReply.
 * Returns:
 *      +1 -- success
 *       0 -- need more data (partial parse)
 *      -1 -- parse error
 */
static int
httpReplyParseStep(HttpReply * rep, const char *buf, int len)
{
    const char *parse_start = buf;
    const char *blk_start, *blk_end;
    int i;
    const char *re;
    assert(rep);
    assert(parse_start);
    assert(rep->pstate < psParsed);

    /* For now we'll assume we need to parse the whole lot */

    /* Find end of start line */
    re = memchr(buf, '\n', len);
    if (!re)
	return httpReplyParseError(rep);

    /* Skip \n */
    re++;
    i = re - buf;
    if (i >= len)
	return httpReplyParseError(rep);

    /* Pass that to the existing Squid status line parsing routine */
    if (!httpStatusLineParse(&rep->sline, buf, re - 1))
	return httpReplyParseError(rep);
    rep->pstate++;

    /* All good? Attempt to isolate headers */
    /* The block in question is between re and buf + len */
    parse_start = re;
    if (!httpMsgIsolateHeaders(&parse_start, len - i, &blk_start, &blk_end))
	return httpReplyParseError(rep);

    /* Isolated? parse headers */
    if (!httpHeaderParse(&rep->header, blk_start, blk_end))
	return httpReplyParseError(rep);

    /* Update rep */
    httpReplyHdrCacheInit(rep);
    /* the previous code had hdr_sz including the status line + headers and final \r\n */
    rep->hdr_sz = parse_start - buf;
    rep->pstate++;

    /* Done */
    return 1;
}

/* handy: resets and returns -1 */
static int
httpReplyParseError(HttpReply * rep)
{
    assert(rep);
    /* reset */
    httpReplyReset(rep);
    /* indicate an error */
    rep->sline.status = HTTP_INVALID_HEADER;
    return -1;
}

/*
 * Returns the body size of a HTTP response
 */
squid_off_t
httpReplyBodySize(method_t method, const HttpReply * reply)
{
    if (reply->sline.version.major < 1)
	return -1;
    else if (METHOD_HEAD == method)
	return 0;
    else if (reply->sline.status == HTTP_OK)
	(void) 0;		/* common case, continue */
    else if (reply->sline.status == HTTP_NO_CONTENT)
	return 0;
    else if (reply->sline.status == HTTP_NOT_MODIFIED)
	return 0;
    else if (reply->sline.status < HTTP_OK)
	return 0;
    return reply->content_length;
}


text:
namespace starboard {
namespace shared {
namespace starboard {
namespace audio_sink {
namespace {

class StubAudioSink : public SbAudioSinkPrivate {
 public:
  StubAudioSink(Type* type,
                int sampling_frequency_hz,
                SbAudioSinkUpdateSourceStatusFunc update_source_status_func,
                ConsumeFramesFunc consume_frames_func,
                void* context);
  ~StubAudioSink() override;

  bool IsType(Type* type) override { return type_ == type; }
  void SetPlaybackRate(double playback_rate) override { SB_NOTIMPLEMENTED(); }

  void SetVolume(double volume) override {}

 private:
  static void* ThreadEntryPoint(void* context);
  void AudioThreadFunc();

  Type* type_;
  SbAudioSinkUpdateSourceStatusFunc update_source_status_func_;
  ConsumeFramesFunc consume_frames_func_;
  void* context_;

  int sampling_frequency_hz_;

  SbThread audio_out_thread_;
  ::starboard::Mutex mutex_;

  bool destroying_;
};

StubAudioSink::StubAudioSink(
    Type* type,
    int sampling_frequency_hz,
    SbAudioSinkUpdateSourceStatusFunc update_source_status_func,
    ConsumeFramesFunc consume_frames_func,
    void* context)
    : type_(type),
      sampling_frequency_hz_(sampling_frequency_hz),
      update_source_status_func_(update_source_status_func),
      consume_frames_func_(consume_frames_func),
      context_(context),
      audio_out_thread_(kSbThreadInvalid),
      destroying_(false) {
  audio_out_thread_ =
      SbThreadCreate(0, kSbThreadPriorityRealTime, kSbThreadNoAffinity, true,
                     "stub_audio_out", &StubAudioSink::ThreadEntryPoint, this);
  SB_DCHECK(SbThreadIsValid(audio_out_thread_));
}

StubAudioSink::~StubAudioSink() {
  {
    ScopedLock lock(mutex_);
    destroying_ = true;
  }
  SbThreadJoin(audio_out_thread_, NULL);
}

// static
void* StubAudioSink::ThreadEntryPoint(void* context) {
  SB_DCHECK(context);
  StubAudioSink* sink = reinterpret_cast<StubAudioSink*>(context);
  sink->AudioThreadFunc();

  return NULL;
}

void StubAudioSink::AudioThreadFunc() {
  const int kMaxFramesToConsumePerRequest = 1024;

  for (;;) {
    {
      ScopedLock lock(mutex_);
      if (destroying_) {
        break;
      }
    }
    int frames_in_buffer, offset_in_frames;
    bool is_playing, is_eos_reached;
    update_source_status_func_(&frames_in_buffer, &offset_in_frames,
                               &is_playing, &is_eos_reached, context_);
    if (is_playing) {
      int frames_to_consume =
          std::min(kMaxFramesToConsumePerRequest, frames_in_buffer);

      SbThreadSleep(frames_to_consume * kSbTimeSecond / sampling_frequency_hz_);
      consume_frames_func_(frames_to_consume, SbTimeGetMonotonicNow(),
                           context_);
    } else {
      // Wait for five millisecond if we are paused.
      SbThreadSleep(kSbTimeMillisecond * 5);
    }
  }
}

}  // namespace

SbAudioSink StubAudioSinkType::Create(
    int channels,
    int sampling_frequency_hz,
    SbMediaAudioSampleType audio_sample_type,
    SbMediaAudioFrameStorageType audio_frame_storage_type,
    SbAudioSinkFrameBuffers frame_buffers,
    int frame_buffers_size_in_frames,
    SbAudioSinkUpdateSourceStatusFunc update_source_status_func,
    SbAudioSinkPrivate::ConsumeFramesFunc consume_frames_func,
    SbAudioSinkPrivate::ErrorFunc error_func,
    void* context) {
  return new StubAudioSink(this, sampling_frequency_hz,
                           update_source_status_func, consume_frames_func,
                           context);
}

}  // namespace audio_sink
}  // namespace starboard
}  // namespace shared
}  // namespace starboard


text:
"Registry for ToolkitWrapper objects"

__all__ = ("ToolkitRegistry",)

import inspect
import logging
from contextlib import contextmanager
from typing import Union

from openff.toolkit.utils.ambertools_wrapper import AmberToolsToolkitWrapper
from openff.toolkit.utils.base_wrapper import ToolkitWrapper
from openff.toolkit.utils.builtin_wrapper import BuiltInToolkitWrapper
from openff.toolkit.utils.exceptions import (
    InvalidToolkitError,
    LicenseError,
    ToolkitUnavailableException,
)
from openff.toolkit.utils.openeye_wrapper import OpenEyeToolkitWrapper
from openff.toolkit.utils.rdkit_wrapper import RDKitToolkitWrapper
from openff.toolkit.utils.utils import all_subclasses

logger = logging.getLogger(__name__)

class ToolkitRegistry:
    """
    Registry for ToolkitWrapper objects

    Examples
    --------

    Register toolkits in a specified order, skipping if unavailable

    >>> from openff.toolkit.utils.toolkits import ToolkitRegistry
    >>> toolkit_precedence = [OpenEyeToolkitWrapper, RDKitToolkitWrapper, AmberToolsToolkitWrapper]
    >>> toolkit_registry = ToolkitRegistry(toolkit_precedence)
    >>> toolkit_registry
    <ToolkitRegistry containing OpenEye Toolkit, The RDKit, AmberTools>

    Register all available toolkits (in the order OpenEye, RDKit, AmberTools, built-in)

    >>> toolkits = [OpenEyeToolkitWrapper, RDKitToolkitWrapper, AmberToolsToolkitWrapper, BuiltInToolkitWrapper]
    >>> toolkit_registry = ToolkitRegistry(toolkit_precedence=toolkits)
    >>> toolkit_registry
    <ToolkitRegistry containing OpenEye Toolkit, The RDKit, AmberTools, Built-in Toolkit>

    Retrieve the global singleton toolkit registry, which is created when this module is imported from all available
    toolkits:

    >>> from openff.toolkit.utils.toolkits import GLOBAL_TOOLKIT_REGISTRY as toolkit_registry
    >>> toolkit_registry
    <ToolkitRegistry containing OpenEye Toolkit, The RDKit, AmberTools, Built-in Toolkit>

    Note that this will contain different ToolkitWrapper objects based on what toolkits
    are currently installed.

    .. warning :: This API is experimental and subject to change.
    """

    def __init__(
        self,
        toolkit_precedence=None,
        exception_if_unavailable=True,
        _register_imported_toolkit_wrappers=False,
    ):
        """
        Create an empty toolkit registry.

        Parameters
        ----------
        toolkit_precedence : list, optional, default=None
            List of toolkit wrapper classes, in order of desired precedence when performing molecule operations. If
            None, no toolkits will be registered.

        exception_if_unavailable : bool, optional, default=True
            If True, an exception will be raised if the toolkit is unavailable

        _register_imported_toolkit_wrappers : bool, optional, default=False
            If True, will attempt to register all imported ToolkitWrapper subclasses that can be
            found in the order of toolkit_precedence, if specified. If toolkit_precedence is not
            specified, the default order is [OpenEyeToolkitWrapper, RDKitToolkitWrapper,
            AmberToolsToolkitWrapper, BuiltInToolkitWrapper].

        """
        self._toolkits = list()

        toolkits_to_register = list()

        if _register_imported_toolkit_wrappers:
            if toolkit_precedence is None:
                toolkit_precedence = [
                    OpenEyeToolkitWrapper,
                    RDKitToolkitWrapper,
                    AmberToolsToolkitWrapper,
                    BuiltInToolkitWrapper,
                ]
            all_importable_toolkit_wrappers = all_subclasses(ToolkitWrapper)
            for toolkit in toolkit_precedence:
                if toolkit in all_importable_toolkit_wrappers:
                    toolkits_to_register.append(toolkit)
        else:
            if toolkit_precedence is not None:
                toolkits_to_register = toolkit_precedence

        if toolkits_to_register:
            for toolkit in toolkits_to_register:
                self.register_toolkit(
                    toolkit, exception_if_unavailable=exception_if_unavailable
                )

    @property
    def registered_toolkits(self):
        """
        List registered toolkits.

        .. warning :: This API is experimental and subject to change.

        .. todo :: Should this return a generator? Deep copies? Classes? Toolkit names?

        Returns
        -------
        toolkits : iterable of toolkit objects
        """
        return list(self._toolkits)

    @property
    def registered_toolkit_versions(self):
        """
        Return a dict containing the version of each registered toolkit.

        .. warning :: This API is experimental and subject to change.

        Returns
        -------
        toolkit_versions : dict[str, str]
            A dictionary mapping names and versions of wrapped toolkits

        """
        return dict(
            (tk.toolkit_name, tk.toolkit_version) for tk in self.registered_toolkits
        )

    def register_toolkit(self, toolkit_wrapper, exception_if_unavailable=True):
        """
        Register the provided toolkit wrapper class, instantiating an object of it.

        .. warning :: This API is experimental and subject to change.

        .. todo ::

           This method should raise an exception if the toolkit is unavailable, unless an optional argument
           is specified that silently avoids registration of toolkits that are unavailable.

        Parameters
        ----------
        toolkit_wrapper : instance or subclass of ToolkitWrapper
            The toolkit wrapper to register or its class.
        exception_if_unavailable : bool, optional, default=True
            If True, an exception will be raised if the toolkit is unavailable

        """
        # Instantiate class if class, or just add if already instantiated.
        if isinstance(toolkit_wrapper, type):
            try:
                toolkit_wrapper = toolkit_wrapper()

            # This exception can be raised by OpenEyeToolkitWrapper
            except LicenseError as license_exception:
                if exception_if_unavailable:
                    raise ToolkitUnavailableException(license_exception.msg)
                else:
                    logger.warning(license_exception)
                return
            except ToolkitUnavailableException:
                msg = "Unable to load toolkit '{}'. ".format(
                    toolkit_wrapper._toolkit_name
                )
                if exception_if_unavailable:
                    raise ToolkitUnavailableException(msg)
                return

        # Add toolkit to the registry.
        self._toolkits.append(toolkit_wrapper)

    def deregister_toolkit(self, toolkit_wrapper):
        """
        Remove a ToolkitWrapper from the list of toolkits in this ToolkitRegistry

        .. warning :: This API is experimental and subject to change.

        Parameters
        ----------
        toolkit_wrapper : instance or subclass of ToolkitWrapper
            The toolkit wrapper to remove from the registry

        Raises
        ------
        InvalidToolkitError
            If toolkit_wrapper is not a ToolkitWrapper or subclass
        ToolkitUnavailableException
            If toolkit_wrapper is not found in the registry
        """
        # If passed a class, instantiate it
        if inspect.isclass(toolkit_wrapper):
            toolkit_wrapper = toolkit_wrapper()

        if not isinstance(toolkit_wrapper, ToolkitWrapper):
            msg = (
                f"Argument {toolkit_wrapper} must an ToolkitWrapper "
                f"or subclass of it. Found type {type(toolkit_wrapper)}."
            )
            raise InvalidToolkitError(msg)

        toolkits_to_remove = []

        for toolkit in self._toolkits:
            if type(toolkit) == type(toolkit_wrapper):
                toolkits_to_remove.append(toolkit)

        if not toolkits_to_remove:
            msg = (
                f"Did not find {toolkit_wrapper} in registry. "
                f"Currently registered toolkits are {self._toolkits}"
            )
            raise ToolkitUnavailableException(msg)

        for toolkit_to_remove in toolkits_to_remove:
            self._toolkits.remove(toolkit_to_remove)

    def add_toolkit(self, toolkit_wrapper):
        """
        Append a ToolkitWrapper onto the list of toolkits in this ToolkitRegistry

        .. warning :: This API is experimental and subject to change.

        Parameters
        ----------
        toolkit_wrapper : openff.toolkit.utils.ToolkitWrapper
            The ToolkitWrapper object to add to the list of registered toolkits

        Raises
        ------
        InvalidToolkitError
            If toolkit_wrapper is not a ToolkitWrapper or subclass
        """
        if not isinstance(toolkit_wrapper, ToolkitWrapper):
            msg = "Something other than a ToolkitWrapper object was passed to ToolkitRegistry.add_toolkit()\n"
            msg += "Given object {} of type {}".format(
                toolkit_wrapper, type(toolkit_wrapper)
            )
            raise InvalidToolkitError(msg)
        self._toolkits.append(toolkit_wrapper)

    # TODO: Can we automatically resolve calls to methods that are not explicitly defined using some Python magic?

    def resolve(self, method_name):
        """
        Resolve the requested method name by checking all registered toolkits in
        order of precedence for one that provides the requested method.

        Parameters
        ----------
        method_name : str
            The name of the method to resolve

        Returns
        -------
        method
            The method of the first registered toolkit that provides the requested method name

        Raises
        ------
        NotImplementedError if the requested method cannot be found among the registered toolkits

        Examples
        --------

        Create a molecule, and call the toolkit ``to_smiles()`` method directly

        >>> from openff.toolkit import Molecule
        >>> molecule = Molecule.from_smiles('Cc1ccccc1')
        >>> toolkit_registry = ToolkitRegistry([OpenEyeToolkitWrapper, RDKitToolkitWrapper, AmberToolsToolkitWrapper])
        >>> method = toolkit_registry.resolve('to_smiles')
        >>> smiles = method(molecule)

        .. todo :: Is there a better way to figure out which toolkits implement given methods by introspection?

        """
        for toolkit in self._toolkits:
            if hasattr(toolkit, method_name):
                method = getattr(toolkit, method_name)
                return method

        # No toolkit was found to provide the requested capability
        # TODO: Can we help developers by providing a check for typos in expected method names?
        msg = 'No registered toolkits can provide the capability "{}".\n'.format(
            method_name
        )
        msg += "Available toolkits are: {}\n".format(self.registered_toolkits)
        raise NotImplementedError(msg)

    # TODO: Can we instead register available methods directly with `ToolkitRegistry`,
    # so we can just use `ToolkitRegistry.method()`?
    def call(self, method_name, *args, raise_exception_types=None, **kwargs):
        """
        Execute the requested method by attempting to use all registered toolkits in order of precedence.

        ``*args`` and ``**kwargs`` are passed to the desired method, and return values of the method are returned

        This is a convenient shorthand for ``toolkit_registry.resolve_method(method_name)(*args, **kwargs)``

        Parameters
        ----------
        method_name : str
            The name of the method to execute
        raise_exception_types : list of Exception subclasses, default=None
            A list of exception-derived types to catch and raise immediately. If None, this will be set to [Exception],
            which will raise an error immediately if the first ToolkitWrapper in the registry fails. To try each
            ToolkitWrapper that provides a suitably-named method, set this to the empty list ([]). If all
            ToolkitWrappers run without raising any exceptions in this list, a single ValueError will be raised
            containing the each ToolkitWrapper that was tried and the exception it raised.

        Raises
        ------
        NotImplementedError if the requested method cannot be found among the registered toolkits

        ValueError if no exceptions in the raise_exception_types list were raised by ToolkitWrappers, and
        all ToolkitWrappers in the ToolkitRegistry were tried.

        Other forms of exceptions are possible if raise_exception_types is specified.
        These are defined by the ToolkitWrapper method being called.

        Examples
        --------

        Create a molecule, and call the toolkit ``to_smiles()`` method directly

        >>> from openff.toolkit import Molecule
        >>> molecule = Molecule.from_smiles('Cc1ccccc1')
        >>> toolkit_registry = ToolkitRegistry([OpenEyeToolkitWrapper, RDKitToolkitWrapper])
        >>> smiles = toolkit_registry.call('to_smiles', molecule)

        """
        if raise_exception_types is None:
            raise_exception_types = [Exception]

        errors = list()
        for toolkit in self._toolkits:
            if hasattr(toolkit, method_name):
                method = getattr(toolkit, method_name)
                try:
                    return method(*args, **kwargs)
                except Exception as e:
                    for exception_type in raise_exception_types:
                        if isinstance(e, exception_type):
                            raise e
                    errors.append((toolkit, e))

        # No toolkit was found to provide the requested capability
        # TODO: Can we help developers by providing a check for typos in expected method names?
        msg = (
            f'No registered toolkits can provide the capability "{method_name}" '
            f'for args "{args}" and kwargs "{kwargs}"\n'
        )

        msg += "Available toolkits are: {}\n".format(self.registered_toolkits)
        # Append information about toolkits that implemented the method, but could not handle the provided parameters
        for toolkit, error in errors:
            msg += " {} {} : {}\n".format(toolkit, type(error), error)
        raise ValueError(msg)

    def __repr__(self):
        return f"<ToolkitRegistry containing {', '.join([tk.toolkit_name for tk in self._toolkits])}>"

# Coped from https://github.com/openforcefield/openff-fragmenter/blob/4a290b866a8ed43eabcbd3231c62b01f0c6d7df6
# /openff/fragmenter/utils.py#L97-L123
@contextmanager
def _toolkit_registry_manager(toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper]):
    from openff.toolkit.utils.toolkits import GLOBAL_TOOLKIT_REGISTRY

    if isinstance(toolkit_registry, ToolkitRegistry):
        context_toolkits = toolkit_registry.registered_toolkits
    elif isinstance(toolkit_registry, ToolkitWrapper):
        context_toolkits = [toolkit_registry]
    else:
        raise NotImplementedError(
            "Only ``ToolkitRegistry`` and ``ToolkitWrapper`` are supported."
        )

    original_toolkits = GLOBAL_TOOLKIT_REGISTRY.registered_toolkits

    for toolkit in original_toolkits:
        GLOBAL_TOOLKIT_REGISTRY.deregister_toolkit(toolkit)

    for toolkit in context_toolkits:
        GLOBAL_TOOLKIT_REGISTRY.register_toolkit(toolkit)

    try:
        yield
    finally:
        for toolkit in context_toolkits:
            GLOBAL_TOOLKIT_REGISTRY.deregister_toolkit(toolkit)
        for toolkit in original_toolkits:
            GLOBAL_TOOLKIT_REGISTRY.register_toolkit(toolkit)


text:
default['graphite']['carbon']['aggregator']['line_receiver_interface'] = "0.0.0.0"
default['graphite']['carbon']['aggregator']['line_receiver_port'] = 2023
default['graphite']['carbon']['aggregator']['pickle_receiver_interface'] = "0.0.0.0"
default['graphite']['carbon']['aggregator']['pickle_receiver_port'] = 2024
default['graphite']['carbon']['aggregator']['destinations'] = []
default['graphite']['carbon']['aggregator']['replication_factor'] = 1
default['graphite']['carbon']['aggregator']['max_queue_size'] = 10000
default['graphite']['carbon']['aggregator']['use_flow_control'] = "True"
default['graphite']['carbon']['aggregator']['max_datapoints_per_message'] = 500
default['graphite']['carbon']['aggregator']['max_aggregation_intervals'] = 5

default['graphite']['storage_aggregation'] = [
	{
		'name' => 'min',
		'pattern' => '\.lower$',
		'xFilesFactor' => '0.1',
		'aggregationMethod' => 'min'
	},
	{
		'name' => 'max',
		'pattern' => '\.upper$',
		'xFilesFactor' => '0.1',
		'aggregationMethod' => 'max'
	},
	{
		'name' => 'sum',
		'pattern' => '\.sum$',
		'xFilesFactor' => '0',
		'aggregationMethod' => 'sum'
	},
	{
		'name' => 'count',
		'pattern' => '^stats_counts.*',
		'xFilesFactor' => '0',
		'aggregationMethod' => 'sum'
	},
	{
		'name' => 'default_average',
		'pattern' => '.*',
		'xFilesFactor' => '0.3',
		'aggregationMethod' => 'average'
	}
]

default['graphite']['aggregation_rules'] = []


text:
<?php defined('BX_DOL') or die('hack attempt');

bx_import('BxBaseModProfileGridModeration');

class BxOrgsGridModeration extends BxBaseModProfileGridModeration
{
    public function __construct ($aOptions, $oTemplate = false)
    {
    	$this->MODULE = 'bx_organizations';
        parent::__construct ($aOptions, $oTemplate);
    }
}

/** @} */


text:
using std::numeric_limits;
using std::string;
using std::stringstream;
using std::endl;

namespace fr {

LinearNode::LinearNode() :
 bounds(),
 parent(-1),
 right(-1) {
    leaf = numeric_limits<uint64_t>::max();
    index = numeric_limits<size_t>::max();
    axis = numeric_limits<uint64_t>::max();
}

string ToString(const LinearNode& node, const string& indent) {
    stringstream stream;
    string pad = indent + "| ";
    stream << "LinearNode {" << endl <<
     indent << "| bounds = " << ToString(node.bounds, pad) << endl <<
     indent << "| leaf = " << node.leaf << endl <<
     indent << "| index = " << node.index << endl <<
     indent << "| parent = " << node.parent << endl <<
     indent << "| right = " << node.right << endl <<
     indent << "| axis = " << node.axis << endl <<
     indent << "}";
    return stream.str();
}

} // namespace fr


text:
title: "Announcements and July Matches"
layout: article
categories: Announcements
---

Big thanks to the club members who participated and helped with the Cedar Valley Multigun match. It was a great match and it certainly wouldn't have been as fun if we hadn't had so much help.

A reminder that if you want to become an IDPA/club safety officer you can contact Daniel Leaberry <leaberry@gmail.com>. The course is Saturday July 11th. More details are [here](http://www.udpl.net/announcements/idpa-safety-officer-training/)

## Rifle/Pistol July 18th

If you're intimidated by 3 Gun the rifle/pistol match is a great chance to test out the concept. It's also a popular match to shoot with a .22lr gun or pistol caliber carbine. Remember there is no steel ammo allowed for safety reasons. If a magnet sticks to the bullet (not the case) you won't be able to shoot that ammo.

[Registration](https://clubs.practiscore.com/udpl-2015-july-pistol-carbine-match/register) is on Practiscore.

## IDPA July 25th

The IDPA match will include the classifier as part of the match. Please bring at least 90 rounds for the classifier. [Register here](https://clubs.practiscore.com/udpl-idpa-july-2015/register)

## Funshoot July 1st - Missing magazine

The results have been [posted](http://www.udpl.net/files/results/2015-07-01_Funshoot.pdf).

Please check your range bag to see if you have an extra 9mm Wilson Combat magazine. RDan Phillips is missing one and would love to get it back. You can email him at <rdanph45@gmail.com>