text:
import createStore from "..";
import * as notification from "../../infra/notification";
import { dispatch } from "../utils";
import { actionCreators, initialState, reducer } from "../settings";

function getState(store): typeof initialState {
    return store.getState().settings;
}

jest.mock("../../infra/notification", () => ({
    permission: () => true,
    requestPermission: () => true,
}));

it("turns notification on", () => {
    expect(initialState.notificationOn).toBe(null);
    const state = reducer(initialState, actionCreators.setNotificationState(true));
    expect(state.notificationOn).toBe(true);
});

it("sets alarm volume", () => {
    expect(initialState.alarmVolume).not.toBe(0);
    const state = reducer(initialState, actionCreators.setAlarmVolume(0.75));
    expect(state.alarmVolume).toBe(0.75);
});

it("checks notification permission", async () => {
    expect.assertions(3);

    const store = createStore();
    const spy = jest.spyOn(notification, "permission");

    expect(initialState.notificationOn).toBe(null);
    await dispatch(store, actionCreators.checkNotificationPermission());
    expect(spy).toHaveBeenCalled();
    expect(getState(store).notificationOn).toBe(true);
});

it("requests notification permission", async () => {
    expect.assertions(3);

    const store = createStore();
    const spy = jest.spyOn(notification, "requestPermission");

    expect(initialState.notificationOn).toBe(null);
    await dispatch(store, actionCreators.requestNotificationPermission());
    expect(spy).toHaveBeenCalled();
    expect(getState(store).notificationOn).toBe(true);
});


text:
"""Parse metadata from FITS files on local disk.

Parsers extract metadata from FITS files and format them into standard
representation for more convenient storage and querying.  Each header-and-data
unit (HDU) of a FITS file is translated into a Python dictionary in a
standardized way.  These dictionaries are stored as individual documents in a
data store like MongoDB, PostgreSQL 9.4+, or some other solution supporting
documents.

"""

class Parser ( object ) :
    """Parser interface."""

    def __call__( self, path ) :
        """Extract metadata from a FITS file on local disk.

        Args:
            path (str): Path to FITS file.

        Returns:
            List[Dict]: List of extracted metadata dictionaries, one per HDU.

        """

        raise NotImplementedError

redpajama_set_name: RedPajamaGithub


text:
#include "util_hack.h"
#include "cuddInt.h"

/*---------------------------------------------------------------------------*/
/* Constant declarations                                                     */
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
/* Stucture declarations                                                     */
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
/* Type declarations                                                         */
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
/* Variable declarations                                                     */
/*---------------------------------------------------------------------------*/

#ifndef lint
static char rcsid[] DD_UNUSED = "$Id: cuddExact.c,v 1.1.1.1 2003/02/24 22:23:52 wjiang Exp $";
#endif

#ifdef DD_STATS
static int ddTotalShuffles;
#endif

/*---------------------------------------------------------------------------*/
/* Macro declarations                                                        */
/*---------------------------------------------------------------------------*/

/**AutomaticStart*************************************************************/

/*---------------------------------------------------------------------------*/
/* Static function prototypes                                                */
/*---------------------------------------------------------------------------*/

static int getMaxBinomial ARGS((int n));
static int gcd ARGS((int x, int y));
static DdHalfWord ** getMatrix ARGS((int rows, int cols));
static void freeMatrix ARGS((DdHalfWord **matrix));
static int getLevelKeys ARGS((DdManager *table, int l));
static int ddShuffle ARGS((DdManager *table, DdHalfWord *permutation, int lower, int upper));
static int ddSiftUp ARGS((DdManager *table, int x, int xLow));
static int updateUB ARGS((DdManager *table, int oldBound, DdHalfWord *bestOrder, int lower, int upper));
static int ddCountRoots ARGS((DdManager *table, int lower, int upper));
static void ddClearGlobal ARGS((DdManager *table, int lower, int maxlevel));
static int computeLB ARGS((DdManager *table, DdHalfWord *order, int roots, int cost, int lower, int upper, int level));
static int updateEntry ARGS((DdManager *table, DdHalfWord *order, int level, int cost, DdHalfWord **orders, int *costs, int subsets, char *mask, int lower, int upper));
static void pushDown ARGS((DdHalfWord *order, int j, int level));
static DdHalfWord * initSymmInfo ARGS((DdManager *table, int lower, int upper));
static int checkSymmInfo ARGS((DdManager *table, DdHalfWord *symmInfo, int index, int level));

/**AutomaticEnd***************************************************************/

/*---------------------------------------------------------------------------*/
/* Definition of exported functions                                          */
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
/* Definition of internal functions                                          */
/*---------------------------------------------------------------------------*/

/**Function********************************************************************

  Synopsis    [Exact variable ordering algorithm.]

  Description [Exact variable ordering algorithm. Finds an optimum
  order for the variables between lower and upper.  Returns 1 if
  successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
int
cuddExact(
  DdManager * table,
  int  lower,
  int  upper)
{
    int k, i, j;
    int maxBinomial, oldSubsets, newSubsets;
    int subsetCost;
    int size;			/* number of variables to be reordered */
    int unused, nvars, level, result;
    int upperBound, lowerBound, cost;
    int roots;
    char *mask = NULL;
    DdHalfWord  *symmInfo = NULL;
    DdHalfWord **newOrder = NULL;
    DdHalfWord **oldOrder = NULL;
    int *newCost = NULL;
    int *oldCost = NULL;
    DdHalfWord **tmpOrder;
    int *tmpCost;
    DdHalfWord *bestOrder = NULL;
    DdHalfWord *order;
#ifdef DD_STATS
    int  ddTotalSubsets;
#endif

    /* Restrict the range to be reordered by excluding unused variables
    ** at the two ends. */
    while (table->subtables[lower].keys == 1 &&
	   table->vars[table->invperm[lower]]->ref == 1 &&
	   lower < upper)
	lower++;
    while (table->subtables[upper].keys == 1 &&
	   table->vars[table->invperm[upper]]->ref == 1 &&
	   lower < upper)
	upper--;
    if (lower == upper) return(1); /* trivial problem */

    /* Apply symmetric sifting to get a good upper bound and to extract
    ** symmetry information. */
    result = cuddSymmSiftingConv(table,lower,upper);
    if (result == 0) goto cuddExactOutOfMem;

#ifdef DD_STATS
    (void) fprintf(table->out,"\n");
    ddTotalShuffles = 0;
    ddTotalSubsets = 0;
#endif

    /* Initialization. */
    nvars = table->size;
    size = upper - lower + 1;
    /* Count unused variable among those to be reordered.  This is only
    ** used to compute maxBinomial. */
    unused = 0;
    for (i = lower + 1; i < upper; i++) {
	if (table->subtables[i].keys == 1 &&
	    table->vars[table->invperm[i]]->ref == 1)
	    unused++;
    }

    /* Find the maximum number of subsets we may have to store. */
    maxBinomial = getMaxBinomial(size - unused);
    if (maxBinomial == -1) goto cuddExactOutOfMem;

    newOrder = getMatrix(maxBinomial, size);
    if (newOrder == NULL) goto cuddExactOutOfMem;

    newCost = ALLOC(int, maxBinomial);
    if (newCost == NULL) goto cuddExactOutOfMem;

    oldOrder = getMatrix(maxBinomial, size);
    if (oldOrder == NULL) goto cuddExactOutOfMem;

    oldCost = ALLOC(int, maxBinomial);
    if (oldCost == NULL) goto cuddExactOutOfMem;

    bestOrder = ALLOC(DdHalfWord, size);
    if (bestOrder == NULL) goto cuddExactOutOfMem;

    mask = ALLOC(char, nvars);
    if (mask == NULL) goto cuddExactOutOfMem;

    symmInfo = initSymmInfo(table, lower, upper);
    if (symmInfo == NULL) goto cuddExactOutOfMem;

    roots = ddCountRoots(table, lower, upper);

    /* Initialize the old order matrix for the empty subset and the best
    ** order to the current order. The cost for the empty subset includes
    ** the cost of the levels between upper and the constants. These levels
    ** are not going to change. Hence, we count them only once.
    */
    oldSubsets = 1;
    for (i = 0; i < size; i++) {
	oldOrder[0][i] = bestOrder[i] = (DdHalfWord) table->invperm[i+lower];
    }
    subsetCost = table->constants.keys;
    for (i = upper + 1; i < nvars; i++)
	subsetCost += getLevelKeys(table,i);
    oldCost[0] = subsetCost;
    /* The upper bound is initialized to the current size of the BDDs. */
    upperBound = table->keys - table->isolated;

    /* Now consider subsets of increasing size. */
    for (k = 1; k <= size; k++) {
#if DD_STATS
	(void) fprintf(table->out,"Processing subsets of size %d\n", k);
	fflush(table->out);
#endif
	newSubsets = 0;
	level = size - k;		/* offset of first bottom variable */

	for (i = 0; i < oldSubsets; i++) { /* for each subset of size k-1 */
	    order = oldOrder[i];
	    cost = oldCost[i];
	    lowerBound = computeLB(table, order, roots, cost, lower, upper,
				   level);
	    if (lowerBound >= upperBound)
		continue;
	    /* Impose new order. */
	    result = ddShuffle(table, order, lower, upper);
	    if (result == 0) goto cuddExactOutOfMem;
	    upperBound = updateUB(table,upperBound,bestOrder,lower,upper);
	    /* For each top bottom variable. */
	    for (j = level; j >= 0; j--) {
		/* Skip unused variables. */
		if (table->subtables[j+lower-1].keys == 1 &&
		    table->vars[table->invperm[j+lower-1]]->ref == 1) continue;
		/* Find cost under this order. */
		subsetCost = cost + getLevelKeys(table, lower + level);
		newSubsets = updateEntry(table, order, level, subsetCost,
					 newOrder, newCost, newSubsets, mask,
					 lower, upper);
		if (j == 0)
		    break;
		if (checkSymmInfo(table, symmInfo, order[j-1], level) == 0)
		    continue;
		pushDown(order,j-1,level);
		/* Impose new order. */
		result = ddShuffle(table, order, lower, upper);
		if (result == 0) goto cuddExactOutOfMem;
		upperBound = updateUB(table,upperBound,bestOrder,lower,upper);
	    } /* for each bottom variable */
	} /* for each subset of size k */

	/* New orders become old orders in preparation for next iteration. */
	tmpOrder = oldOrder; tmpCost = oldCost;
	oldOrder = newOrder; oldCost = newCost;
	newOrder = tmpOrder; newCost = tmpCost;
#ifdef DD_STATS
	ddTotalSubsets += newSubsets;
#endif
	oldSubsets = newSubsets;
    }
    result = ddShuffle(table, bestOrder, lower, upper);
    if (result == 0) goto cuddExactOutOfMem;
#ifdef DD_STATS
#ifdef DD_VERBOSE
    (void) fprintf(table->out,"\n");
#endif
    (void) fprintf(table->out,"#:S_EXACT   %8d: total subsets\n",
		   ddTotalSubsets);
    (void) fprintf(table->out,"#:H_EXACT   %8d: total shuffles",
		   ddTotalShuffles);
#endif

    freeMatrix(newOrder);
    freeMatrix(oldOrder);
    FREE(bestOrder);
    FREE(oldCost);
    FREE(newCost);
    FREE(symmInfo);
    FREE(mask);
    return(1);

cuddExactOutOfMem:

    if (newOrder != NULL) freeMatrix(newOrder);
    if (oldOrder != NULL) freeMatrix(oldOrder);
    if (bestOrder != NULL) FREE(bestOrder);
    if (oldCost != NULL) FREE(oldCost);
    if (newCost != NULL) FREE(newCost);
    if (symmInfo != NULL) FREE(symmInfo);
    if (mask != NULL) FREE(mask);
    table->errorCode = CUDD_MEMORY_OUT;
    return(0);

} /* end of cuddExact */

/**Function********************************************************************

  Synopsis    [Returns the maximum value of (n choose k) for a given n.]

  Description [Computes the maximum value of (n choose k) for a given
  n.  The maximum value occurs for k = n/2 when n is even, or k =
  (n-1)/2 when n is odd.  The algorithm used in this procedure is
  quite inefficient, but it avoids intermediate overflow problems.
  Returns the computed value if successful; -1 otherwise.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
getMaxBinomial(
  int  n)
{
    int *numerator;
    int i, j, k, y, g, result;

    k = (n & ~1) >> 1;

    numerator = ALLOC(int,k);
    if (numerator == NULL) return(-1);

    for (i = 0; i < k; i++)
	numerator[i] = n - i;

    for (i = k; i > 1; i--) {
	y = i;
	for (j = 0; j < k; j++) {
	    if (numerator[j] == 1) continue;
	    g = gcd(numerator[j], y);
	    if (g != 1) {
		numerator[j] /= g;
		if (y == g) break;
		y /= g;
	    }
	}
    }

    result = 1;
    for (i = 0; i < k; i++)
	result *= numerator[i];

    FREE(numerator);
    return(result);

}  /* end of getMaxBinomial */

/**Function********************************************************************

  Synopsis    [Returns the gcd of two integers.]

  Description [Returns the gcd of two integers. Uses the binary GCD
  algorithm described in Cormen, Leiserson, and Rivest.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
gcd(
  int  x,
  int  y)
{
    int a;
    int b;
    int lsbMask;

    /* GCD(n,0) = n. */
    if (x == 0) return(y);
    if (y == 0) return(x);

    a = x; b = y; lsbMask = 1;

    /* Here both a and b are != 0. The iteration maintains this invariant.
    ** Hence, we only need to check for when they become equal.
    */
    while (a != b) {
	if (a & lsbMask) {
	    if (b & lsbMask) {	/* both odd */
		if (a < b) {
		    b = (b - a) >> 1;
		} else {
		    a = (a - b) >> 1;
		}
	    } else {		/* a odd, b even */
		b >>= 1;
	    }
	} else {
	    if (b & lsbMask) {	/* a even, b odd */
		a >>= 1;
	    } else {		/* both even */
		lsbMask <<= 1;
	    }
	}
    }

    return(a);

} /* end of gcd */

/**Function********************************************************************

  Synopsis    [Allocates a two-dimensional matrix of ints.]

  Description [Allocates a two-dimensional matrix of ints.
  Returns the pointer to the matrix if successful; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [freeMatrix]

******************************************************************************/
static DdHalfWord **
getMatrix(
  int  rows /* number of rows */,
  int  cols /* number of columns */)
{
    DdHalfWord **matrix;
    int i;

    if (cols*rows == 0) return(NULL);
    matrix = ALLOC(DdHalfWord *, rows);
    if (matrix == NULL) return(NULL);
    matrix[0] = ALLOC(DdHalfWord, cols*rows);
    if (matrix[0] == NULL) return(NULL);
    for (i = 1; i < rows; i++) {
	matrix[i] = matrix[i-1] + cols;
    }
    return(matrix);

} /* end of getMatrix */

/**Function********************************************************************

  Synopsis    [Frees a two-dimensional matrix allocated by getMatrix.]

  Description []

  SideEffects [None]

  SeeAlso     [getMatrix]

******************************************************************************/
static void
freeMatrix(
  DdHalfWord ** matrix)
{
    FREE(matrix[0]);
    FREE(matrix);
    return;

} /* end of freeMatrix */

/**Function********************************************************************

  Synopsis    [Returns the number of nodes at one level of a unique table.]

  Description [Returns the number of nodes at one level of a unique table.
  The projection function, if isolated, is not counted.]

  SideEffects [None]

  SeeAlso []

******************************************************************************/
static int
getLevelKeys(
  DdManager * table,
  int  l)
{
    int isolated;
    int x;        /* x is an index */

    x = table->invperm[l];
    isolated = table->vars[x]->ref == 1;

    return(table->subtables[l].keys - isolated);

} /* end of getLevelKeys */

/**Function********************************************************************

  Synopsis    [Reorders variables according to a given permutation.]

  Description [Reorders variables according to a given permutation.
  The i-th permutation array contains the index of the variable that
  should be brought to the i-th level. ddShuffle assumes that no
  dead nodes are present and that the interaction matrix is properly
  initialized.  The reordering is achieved by a series of upward sifts.
  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso []

******************************************************************************/
static int
ddShuffle(
  DdManager * table,
  DdHalfWord * permutation,
  int  lower,
  int  upper)
{
    DdHalfWord	index;
    int		level;
    int		position;
    int		numvars;
    int		result;
#ifdef DD_STATS
    long	localTime;
    int		initialSize;
#ifdef DD_VERBOSE
    int		finalSize;
#endif
    int		previousSize;
#endif

#ifdef DD_STATS
    localTime = util_cpu_time();
    initialSize = table->keys - table->isolated;
#endif

    numvars = table->size;

#if 0
    (void) fprintf(table->out,"%d:", ddTotalShuffles);
    for (level = 0; level < numvars; level++) {
	(void) fprintf(table->out," %d", table->invperm[level]);
    }
    (void) fprintf(table->out,"\n");
#endif

    for (level = 0; level <= upper - lower; level++) {
	index = permutation[level];
	position = table->perm[index];
#ifdef DD_STATS
	previousSize = table->keys - table->isolated;
#endif
	result = ddSiftUp(table,position,level+lower);
	if (!result) return(0);
    }

#ifdef DD_STATS
    ddTotalShuffles++;
#ifdef DD_VERBOSE
    finalSize = table->keys - table->isolated;
    if (finalSize < initialSize) {
	(void) fprintf(table->out,"-");
    } else if (finalSize > initialSize) {
	(void) fprintf(table->out,"+");
    } else {
	(void) fprintf(table->out,"=");
    }
    if ((ddTotalShuffles & 63) == 0) (void) fprintf(table->out,"\n");
    fflush(table->out);
#endif
#endif

    return(1);

} /* end of ddShuffle */

/**Function********************************************************************

  Synopsis    [Moves one variable up.]

  Description [Takes a variable from position x and sifts it up to
  position xLow;  xLow should be less than or equal to x.
  Returns 1 if successful; 0 otherwise]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
ddSiftUp(
  DdManager * table,
  int  x,
  int  xLow)
{
    int        y;
    int        size;

    y = cuddNextLow(table,x);
    while (y >= xLow) {
	size = cuddSwapInPlace(table,y,x);
	if (size == 0) {
	    return(0);
	}
	x = y;
	y = cuddNextLow(table,x);
    }
    return(1);

} /* end of ddSiftUp */

/**Function********************************************************************

  Synopsis    [Updates the upper bound and saves the best order seen so far.]

  Description [Updates the upper bound and saves the best order seen so far.
  Returns the current value of the upper bound.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
updateUB(
  DdManager * table,
  int  oldBound,
  DdHalfWord * bestOrder,
  int  lower,
  int  upper)
{
    int i;
    int newBound = table->keys - table->isolated;

    if (newBound < oldBound) {
#ifdef DD_STATS
	(void) fprintf(table->out,"New upper bound = %d\n", newBound);
	fflush(table->out);
#endif
	for (i = lower; i <= upper; i++)
	    bestOrder[i-lower] = (DdHalfWord) table->invperm[i];
	return(newBound);
    } else {
	return(oldBound);
    }

} /* end of updateUB */

/**Function********************************************************************

  Synopsis    [Counts the number of roots.]

  Description [Counts the number of roots at the levels between lower and
  upper.  The computation is based on breadth-first search.
  A node is a root if it is not reachable from any previously visited node.
  (All the nodes at level lower are therefore considered roots.)
  The visited flag uses the LSB of the next pointer.  Returns the root
  count. The roots that are constant nodes are always ignored.]

  SideEffects [None]

  SeeAlso     [ddClearGlobal]

******************************************************************************/
static int
ddCountRoots(
  DdManager * table,
  int  lower,
  int  upper)
{
    int i,j;
    DdNode *f;
    DdNodePtr *nodelist;
    DdNode *sentinel = &(table->sentinel);
    int slots;
    int roots = 0;
    int maxlevel = lower;

    for (i = lower; i <= upper; i++) {
	nodelist = table->subtables[i].nodelist;
	slots = table->subtables[i].slots;
	for (j = 0; j < slots; j++) {
	    f = nodelist[j];
	    while (f != sentinel) {
		/* A node is a root of the DAG if it cannot be
		** reached by nodes above it. If a node was never
		** reached during the previous depth-first searches,
		** then it is a root, and we start a new depth-first
		** search from it.
		*/
		if (!Cudd_IsComplement(f->next)) {
		    if (f != table->vars[f->index]) {
			roots++;
		    }
		}
		if (!Cudd_IsConstant(cuddT(f))) {
		    cuddT(f)->next = Cudd_Complement(cuddT(f)->next);
		    if (table->perm[cuddT(f)->index] > maxlevel)
			maxlevel = table->perm[cuddT(f)->index];
		}
		if (!Cudd_IsConstant(cuddE(f))) {
		    Cudd_Regular(cuddE(f))->next =
			Cudd_Complement(Cudd_Regular(cuddE(f))->next);
		    if (table->perm[Cudd_Regular(cuddE(f))->index] > maxlevel)
			maxlevel = table->perm[Cudd_Regular(cuddE(f))->index];
		}
		f = Cudd_Regular(f->next);
	    }
	}
    }
    ddClearGlobal(table, lower, maxlevel);

    return(roots);

} /* end of ddCountRoots */

/**Function********************************************************************

  Synopsis    [Scans the DD and clears the LSB of the next pointers.]

  Description [Scans the DD and clears the LSB of the next pointers.
  The LSB of the next pointers are used as markers to tell whether a
  node was reached. Once the roots are counted, these flags are
  reset.]

  SideEffects [None]

  SeeAlso     [ddCountRoots]

******************************************************************************/
static void
ddClearGlobal(
  DdManager * table,
  int  lower,
  int  maxlevel)
{
    int i,j;
    DdNode *f;
    DdNodePtr *nodelist;
    DdNode *sentinel = &(table->sentinel);
    int slots;

    for (i = lower; i <= maxlevel; i++) {
	nodelist = table->subtables[i].nodelist;
	slots = table->subtables[i].slots;
	for (j = 0; j < slots; j++) {
	    f = nodelist[j];
	    while (f != sentinel) {
		f->next = Cudd_Regular(f->next);
		f = f->next;
	    }
	}
    }

} /* end of ddClearGlobal */

/**Function********************************************************************

  Synopsis    [Computes a lower bound on the size of a BDD.]

  Description [Computes a lower bound on the size of a BDD from the
  following factors:
  <ul>
  <li> size of the lower part of it;
  <li> size of the part of the upper part not subjected to reordering;
  <li> number of roots in the part of the BDD subjected to reordering;
  <li> variable in the support of the roots in the upper part of the
       BDD subjected to reordering.
  <ul/>]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
computeLB(
  DdManager * table		/* manager */,
  DdHalfWord * order		/* optimal order for the subset */,
  int  roots			/* roots between lower and upper */,
  int  cost			/* minimum cost for the subset */,
  int  lower			/* lower level to be reordered */,
  int  upper			/* upper level to be reordered */,
  int  level			/* offset for the current top bottom var */
  )
{
    int i;
    int lb = cost;
    int lb1 = 0;
    int lb2;
    int support;
    DdHalfWord ref;

    /* The levels not involved in reordering are not going to change.
    ** Add their sizes to the lower bound.
    */
    for (i = 0; i < lower; i++) {
	lb += getLevelKeys(table,i);
    }
    /* If a variable is in the support, then there is going
    ** to be at least one node labeled by that variable.
    */
    for (i = lower; i <= lower+level; i++) {
	support = table->subtables[i].keys > 1 ||
	    table->vars[order[i-lower]]->ref > 1;
	lb1 += support;
    }

    /* Estimate the number of nodes required to connect the roots to
    ** the nodes in the bottom part. */
    if (lower+level+1 < table->size) {
	if (lower+level < upper)
	    ref = table->vars[order[level+1]]->ref;
	else
	    ref = table->vars[table->invperm[upper+1]]->ref;
	lb2 = table->subtables[lower+level+1].keys -
	    (ref > (DdHalfWord) 1) - roots;
    } else {
	lb2 = 0;
    }

    lb += lb1 > lb2 ? lb1 : lb2;

    return(lb);

} /* end of computeLB */

/**Function********************************************************************

  Synopsis    [Updates entry for a subset.]

  Description [Updates entry for a subset. Finds the subset, if it exists.
  If the new order for the subset has lower cost, or if the subset did not
  exist, it stores the new order and cost. Returns the number of subsets
  currently in the table.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
updateEntry(
  DdManager * table,
  DdHalfWord * order,
  int  level,
  int  cost,
  DdHalfWord ** orders,
  int * costs,
  int  subsets,
  char * mask,
  int  lower,
  int  upper)
{
    int i, j;
    int size = upper - lower + 1;

    /* Build a mask that says what variables are in this subset. */
    for (i = lower; i <= upper; i++)
	mask[table->invperm[i]] = 0;
    for (i = level; i < size; i++)
	mask[order[i]] = 1;

    /* Check each subset until a match is found or all subsets are examined. */
    for (i = 0; i < subsets; i++) {
	DdHalfWord *subset = orders[i];
	for (j = level; j < size; j++) {
	    if (mask[subset[j]] == 0)
		break;
	}
	if (j == size)		/* no mismatches: success */
	    break;
    }
    if (i == subsets || cost < costs[i]) {		/* add or replace */
	for (j = 0; j < size; j++)
	    orders[i][j] = order[j];
	costs[i] = cost;
	subsets += (i == subsets);
    }
    return(subsets);

} /* end of updateEntry */

/**Function********************************************************************

  Synopsis    [Pushes a variable in the order down to position "level."]

  Description []

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static void
pushDown(
  DdHalfWord * order,
  int  j,
  int  level)
{
    int i;
    DdHalfWord tmp;

    tmp = order[j];
    for (i = j; i < level; i++) {
	order[i] = order[i+1];
    }
    order[level] = tmp;
    return;

} /* end of pushDown */

/**Function********************************************************************

  Synopsis    [Gathers symmetry information.]

  Description [Translates the symmetry information stored in the next
  field of each subtable from level to indices. This procedure is called
  immediately after symmetric sifting, so that the next fields are correct.
  By translating this informaton in terms of indices, we make it independent
  of subsequent reorderings. The format used is that of the next fields:
  a circular list where each variable points to the next variable in the
  same symmetry group. Only the entries between lower and upper are
  considered.  The procedure returns a pointer to an array
  holding the symmetry information if successful; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [checkSymmInfo]

******************************************************************************/
static DdHalfWord *
initSymmInfo(
  DdManager * table,
  int  lower,
  int  upper)
{
    int level, index, next, nextindex;
    DdHalfWord *symmInfo;

    symmInfo =  ALLOC(DdHalfWord, table->size);
    if (symmInfo == NULL) return(NULL);

    for (level = lower; level <= upper; level++) {
	index = table->invperm[level];
	next =  table->subtables[level].next;
	nextindex = table->invperm[next];
	symmInfo[index] = nextindex;
    }
    return(symmInfo);

} /* end of initSymmInfo */

/**Function********************************************************************

  Synopsis    [Check symmetry condition.]

  Description [Returns 1 if a variable is the one with the highest index
  among those belonging to a symmetry group that are in the top part of
  the BDD.  The top part is given by level.]

  SideEffects [None]

  SeeAlso     [initSymmInfo]

******************************************************************************/
static int
checkSymmInfo(
  DdManager * table,
  DdHalfWord * symmInfo,
  int  index,
  int  level)
{
    int i;

    i = symmInfo[index];
    while (i != index) {
	if (index < i && table->perm[i] <= level)
	    return(0);
	i = symmInfo[i];
    }
    return(1);

} /* end of checkSymmInfo */


text:
package com.hass.ali.doctorsapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

public class NewAppoinment extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_appointment_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getIntent().getSerializableExtra("MyClass");

    }

    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

}


text:
#include <proxygen/lib/http/session/TransportFilter.h>

using namespace apache::thrift::async;
using namespace apache::thrift::transport;
using namespace folly;

namespace proxygen {

// TAsyncTransport::ReadCallback methods
void PassThroughTransportFilter::getReadBuffer(void** bufReturn,
                                               size_t* lenReturn) {
  callback_->getReadBuffer(bufReturn, lenReturn);
}

void PassThroughTransportFilter::readDataAvailable(size_t len) noexcept {
  callback_->readDataAvailable(len);
}

void PassThroughTransportFilter::readEOF() noexcept {
  callback_->readEOF();
  destroy();
}

void PassThroughTransportFilter::readError(
    const TTransportException& ex) noexcept {
  callback_->readError(ex);
  destroy();
}

// TAsyncTransport methods

void PassThroughTransportFilter::setReadCallback(
    TAsyncTransport::ReadCallback* callback) {
  // Important! The filter must call setCallbackInternal in its base class and
  // it must not forward the call.
  setCallbackInternal(callback);
}

TAsyncTransport::ReadCallback*
PassThroughTransportFilter::getReadCallback() const {
  return call_->getReadCallback();
}

void PassThroughTransportFilter::write(
    TAsyncTransport::WriteCallback* callback,
    const void* buf, size_t bytes, WriteFlags flags) {
  call_->write(callback, buf, bytes, flags);
}

void PassThroughTransportFilter::writev(
    TAsyncTransport::WriteCallback* callback, const iovec* vec, size_t count,
    WriteFlags flags) {
  call_->writev(callback, vec, count, flags);
}

void PassThroughTransportFilter::writeChain(
    TAsyncTransport::WriteCallback* callback,
    std::unique_ptr<folly::IOBuf>&& iob, WriteFlags flags) {
  call_->writeChain(callback, std::move(iob), flags);
}

void PassThroughTransportFilter::close() {
  call_->close();
  // wait for readEOF() to call destroy()
}

void PassThroughTransportFilter::closeNow() {
  call_->closeNow();
  // wait for readEOF() to call destroy()
}

void PassThroughTransportFilter::closeWithReset() {
  call_->closeWithReset();
  // wait for readEOF() to call destroy()
}

void PassThroughTransportFilter::shutdownWrite() {
  call_->shutdownWrite();
}

void PassThroughTransportFilter::shutdownWriteNow() {
  call_->shutdownWriteNow();
}

bool PassThroughTransportFilter::good() const {
  return call_->good();
}

bool PassThroughTransportFilter::readable() const {
  return call_->readable();
}

bool PassThroughTransportFilter::connecting() const {
  return call_->connecting();
}

bool PassThroughTransportFilter::error() const {
  return call_->error();
}

void PassThroughTransportFilter::attachEventBase(EventBase* eventBase) {
  call_->attachEventBase(eventBase);
}

void PassThroughTransportFilter::detachEventBase() {
  call_->detachEventBase();
}

bool PassThroughTransportFilter::isDetachable() const {
  return call_->isDetachable();
}

EventBase* PassThroughTransportFilter::getEventBase() const {
  return call_->getEventBase();
}

void PassThroughTransportFilter::setSendTimeout(uint32_t milliseconds) {
  call_->setSendTimeout(milliseconds);
}

uint32_t PassThroughTransportFilter::getSendTimeout() const {
  return call_->getSendTimeout();
}

void PassThroughTransportFilter::getLocalAddress(
    folly::SocketAddress* address) const {
  call_->getLocalAddress(address);
}

void PassThroughTransportFilter::getPeerAddress(
    folly::SocketAddress* address) const {
  call_->getPeerAddress(address);
}

void PassThroughTransportFilter::setEorTracking(bool track) {
  call_->setEorTracking(track);
}

size_t PassThroughTransportFilter::getAppBytesWritten() const {
  return call_->getAppBytesWritten();
}
size_t PassThroughTransportFilter::getRawBytesWritten() const {
  return call_->getRawBytesWritten();
}
size_t PassThroughTransportFilter::getAppBytesReceived() const {
  return call_->getAppBytesReceived();
}
size_t PassThroughTransportFilter::getRawBytesReceived() const {
  //new PassThroughTransportFilter();
  return call_->getRawBytesReceived();
}

}


text:
'use strict';

module.exports = function bcround(val, precision) {
  //  discuss at: http://locutus.io/php/bcround/
  // original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
  //   example 1: bcround(1, 2)
  //   returns 1: '1.00'

  var _bc = require('../_helpers/_bc');
  var libbcmath = _bc();

  var temp, result, digit;
  var rightOperand;

  // create number
  temp = libbcmath.bc_init_num();
  temp = libbcmath.php_str2num(val.toString());

  // check if any rounding needs
  if (precision >= temp.n_scale) {
    // nothing to round, just add the zeros.
    while (temp.n_scale < precision) {
      temp.n_value[temp.n_len + temp.n_scale] = 0;
      temp.n_scale++;
    }
    return temp.toString();
  }

  // get the digit we are checking (1 after the precision)
  // loop through digits after the precision marker
  digit = temp.n_value[temp.n_len + precision];

  rightOperand = libbcmath.bc_init_num();
  rightOperand = libbcmath.bc_new_num(1, precision);

  if (digit >= 5) {
    // round away from zero by adding 1 (or -1) at the "precision"..
    // ie 1.44999 @ 3dp = (1.44999 + 0.001).toString().substr(0,5)
    rightOperand.n_value[rightOperand.n_len + rightOperand.n_scale - 1] = 1;
    if (temp.n_sign === libbcmath.MINUS) {
      // round down
      rightOperand.n_sign = libbcmath.MINUS;
    }
    result = libbcmath.bc_add(temp, rightOperand, precision);
  } else {
    // leave-as-is.. just truncate it.
    result = temp;
  }

  if (result.n_scale > precision) {
    result.n_scale = precision;
  }

  return result.toString();
};
//# sourceMappingURL=bcround.js.map


text:
CHANGELOG
=========

3.0.2 (2022-10-31)
------------------

* Updated Jackson and `maxmind-db` dependencies.

3.0.1 (2022-03-29)
------------------

* Updated Jackson dependencies to address CVE-2020-36518. Pull request by
  slunker. GitHub #306.
* Minor doc updates.

3.0.0 (2022-01-24)
------------------

* Java 11 or greater is now required.
* Apache HttpClient has been replaced with `java.net.http.HttpClient`.
* The `close()` method on `WebServiceClient` is now deprecated. It
  no longer does anything.
* On `WebServiceClient.Builder`:
  * `connectTimeout(int)` has been deprecated in favor of
    `connectTimeout(Duration)`.
  * `readTimeout(int)` has been deprecated in favor of
    `requestTimeout(Duration)`.
  * `proxy(Proxy)` has been deprecated in favor of `proxy(ProxySelector)`.
* On `HttpException` and `InvalidRequestException`, `getUrl()` has been
  deprecated in favor of `getUri()`. Constructors that took a `URL` have
  been replaced with the equivalent taking a `URI`.
* Deprecated constructors on model and trait classes were removed.
* Model data types were updated to better reflect database data types. In
  particular:
  * `getGeoNameId()` on `City`, `Continent`, `Country`, `RepresentedCountry`,
    and `Subdivision` now returns a `Long` rather than an `Integer`.
  * `getAutonomousSystemNumber()` on `AsnResponse` and `Traits` now returns
    a `Long` rather than an `Integer`.

2.16.1 (2021-11-18)
-------------------

* Added `JsonProperty` annotations to `getMobileCountryCode()` and
  `getMobileNetworkCode()` so that it is possible to serialize the
  object as JSON and then deserialize without losing data.

2.16.0 (2021-11-18)
-------------------

* Support for mobile country code (MCC) and mobile network codes (MNC) was
  added for the GeoIP2 ISP and Enterprise databases as well as the GeoIP2
  City and Insights web services. `getMobileCountryCode()` and
  `getMobileNetworkCode()` were added to `com.maxmind.geoip2.model.IspResponse`
  for the GeoIP2 ISP database and `com.maxmind.geoip2.record.Traits` for the
  Enterprise database and the GeoIP2 City and Insights web services. We expect
  this data to be available by late January, 2022.
* Deprecated model constructors that exist for backwards compatibility.
  These constructors are not generally used by users of this library
  directly except perhaps when mocking the reader in tests.

2.15.0 (2020-10-14)
-------------------

* No changes since 2.15.0-rc1.

2.15.0-rc1 (2020-09-29)
-----------------------

* The HTTP client now allows up to 20 connections to be active at once.
  Previously the limit was 2.
* Update `maxmind-db` dependency to a new version that no longer uses
  Jackson. This improves database lookup performance.
* The `isResidentialProxy()` method was added to
  `com.maxmind.geoip2.model.AnonymousIpResponse` and
  `com.maxmind.geoip2.record.Traits` for use with the Anonymous IP database
  and GeoIP2 Precision insights.

2.14.0 (2020-06-15)
-------------------

* Update `maxmind-db` dependency to reduce locking when being used from
  multiple threads and to improve the exceptions thrown on an invalid
  database.
* Update Jackson dependencies.

2.13.1 (2020-03-03)
-------------------

* Update `maxmind-db` dependency to fix handling of long strings in the
  database. Reported by Dongmin Yu. GitHub #181.
* Update Jackson dependencies.

2.13.0 (2019-12-18)
-------------------

* IMPORTANT: Java 8 is now required. If you need Java 7 support, please
  continue using 2.12.0.
* `DatabaseReader` now provides the methods that return an `Optional` rather
  than throwing an exception when the record is not found in the database. These
  methods are prefixed with "try". Closes #28. Pull request by Luke Butters.
  GitHub #147.
* `getNetwork()` methods have been added to the various response models. These
  return a `com.maxmind.db.Network` object representing the largest network
  where all the fields besides the IP address are the same.
* Updated documentation of anonymizer methods `isAnonymousVpn()` and
  `isHostingProvider()` to be more descriptive.
* The `DatabaseReader` methods `city()` and `country()` can now be called on
  the Enterprise database and the `country()` method can be called on City
  databases. Request by Gergely Boromissza. GitHub #132.
* New `getStaticIpScore()` and `getUserCount()` methods were added to
  `com.maxmind.geoip2.record.Traits` for use with GeoIP2 Precision Insights.
  They represent a measure of how static or dynamic an IP address is, and an
  estimate of the number of users sharing a given address or network,
  respectively.

2.12.0 (2018-04-11)
-------------------

* Rename `userId` to `accountId` in various places and support the future error
  codes `ACCOUNT_ID_REQUIRED` and `ACCOUNT_ID_UNKNOWN`.

2.11.0 (2018-01-19)
------------------

* The web service client now correctly handles a proxy of `Proxy.NO_PROXY`.
* The `isInEuropeanUnion()` method was added to
  `com.maxmind.geoip2.record.Country`. This returns `true` if the country
  is a member state of the European Union.

2.10.0 (2017-10-27)
-------------------

* The following new anonymizer methods were added to
 `com.maxmind.geoip2.record.Traits` for use with GeoIP2 Precision Insights:
 `isAnonymous()`, `isAnonymousVpn()`, `isHostingProvider()`, `isPublicProxy()`,
  and `isTorExitNode()`.

2.9.0 (2017-05-08)
------------------

* Added support for GeoLite2 ASN database.

2.8.1 (2017-02-22)
------------------

* Update `maxmind-db` dependency to fix `jackson-databind` version range
  issue. Closes GitHub #77.
* Update most other dependencies.

2.8.0 (2016-09-15)
------------------

* All changes included in 2.8.0-rc1.
* Updated documentation to clarify what the accuracy radius refers to.

2.8.0-rc1 (2016-06-20)
----------------------

* IMPORTANT: Java 7 is now required. If you need Java 6 support, please
  continue using 2.7.0 or earlier.
* This library no longer uses Google HTTP Client. It now directly uses
  Apache HttpClient. Closes #40, #66.
* `WebServiceClient` now implements `Closeable`. A pool of connections will be
  kept alive to be used across requests. To ensure all connections are closed
  when the object goes out of scope, call `close()` or use the
  try-with-resource statement as appropriate.
* Setting of a proxy for the `WebServiceClient` is now supported by the
  `proxy(Proxy)` builder method.
* Updated documentation to reflect that the accuracy radius is now included
  in City.
* Updated dependencies.

2.7.0 (2016-04-15)
------------------

* Added support for the GeoIP2 Enterprise database.

2.6.0 (2016-01-13)
------------------

* This release was updated to 1.2.0 of the MaxMind DB reader, which includes
  faster caching with fewer allocations.
* The IP addresses in the database models are now injected via Jackson rather
  than being added to the `JsonNode` before deserialization. Pull requests by
  Viktor Szathmáry. GitHub #56.

2.5.0 (2016-01-04)
------------------

* The database reader now supports pluggable caching of the decoded data. By
  default, no caching is performed. Please see the `README.md` file or the API
  docs for information on how to enable caching. Pull requests by Viktor
  Szathmáry. GitHub #55.

2.4.0 (2015-12-21)
------------------

* Jackson now uses the constructors on model classes when mapping JSON and
  database records to them rather than overriding the access modifiers on
  them. Pull request by Martijn van Groningen. GitHub #51 & #52.
* The format of the output of the `toString()` methods in the models has
  changed to better represent the values returned by the databases and web
  services. `toString()` should be only used for debugging and diagnostics.
  Do not try to parse it. If you want the contents of the model as a machine-
  readable string, use `toJson()`.
* This release depends on version 1.0.1 of the MaxMind DB reader, which
  includes several performance enhancements from by Viktor Szathmáry.

2.3.1 (2015-07-07)
------------------

* No code changes in this release
* Fix for version number in pom.xml example in README.md
* Slight documentation improvement referring to MaxMind-DB-Reader-java

2.3.0 (2015-06-29)
------------------

* Add support for the `average_income` and `population_density` fields.
* The `isAnonymousProxy()` and `isSatelliteProvider()` methods on
  `com.maxmind.geoip2.record.Traits` have been deprecated. Please use our
  [GeoIP2 Anonymous IP database](https://www.maxmind.com/en/geoip2-anonymous-
  ip-database) to determine whether an IP address is used by an anonymizing
  service.

2.2.0 (2015-04-24)
------------------

* A `DatabaseProvider` interface has been added to facilitate mocking of
  `DatabaseReader`. Pull request by Yonatan Most. GitHub #34.
* A `getLeastSpecificSubdivision()` method has been added to the
  `CityResponse` and `InsightsResponse` model classes. This returns the
  least specific subdivision for the location, e.g., England for Oxford,
  GB. Pull request by Daniel Kaneider. GitHub #35.
* The `InsightsResponse` and `Location` classes are no longer declared final.
* `AbstractResponse` is now declared `abstract`.

2.1.0 (2014-11-06)
------------------

* Added support for the GeoIP2 Anonymous IP database. The `DatabaseReader`
  class now has an `anonymousIp()` method which returns an
  `AnonymousIpResponse` object.

2.0.0 (2014-09-29)
------------------

* First production release.

0.10.0 (2014-09-23)
-------------------

* The deprecated `cityIspOrg()` and `omni()` methods have been removed from
  `DatabaseReader` and `WebServiceClient`.
* The lookup methods on `DatabaseReader` now throw an
  `UnsupportedOperationException` if the incorrect method is used for the
  database.
* `DatabaseReader` now provides the metadata for the database through the
  `getDatabase()` method.
* All of our dependencies were updated to the latest available version.

0.9.0 (2014-09-02)
------------------

* The `timeout` setter on `WebServiceClient.Builder` was renamed to
  `connectTimeout` and a `readTimeout` setter was added. The former timeout
  sets the timeout to establish a connection and the latter sets the timeout
  for reading from an established connection.

0.8.1 (2014-08-27)
------------------

* Updated to depend on the latest version of `com.maxmind.db` and
  `com.fasterxml.jackson.core`.

0.8.0 (2014-07-22)
------------------

* The web service client API has been updated for the v2.1 release of the web
  service. In particular, the `cityIspOrg` and `omni` methods on
  `WebServiceClient` have been deprecated. The `city` method now provides all
  of the data formerly provided by `cityIspOrg`, and the `omni` method has
  been replaced by the `insights` method.
* Support was added for the GeoIP2 Connection Type, Domain, and ISP databases.

0.7.2 (2014-06-02)
------------------

* Updated to version 0.3.3 of `maxmind-db`, which fixes a potential resource
  leak when used with a thread pool.
* Updated Google HTTP Client dependency.
* The Maven build was updated to include a zip file with all dependencies.

0.7.1 (2014-04-02)
------------------

* Added `toJson` method to response objects.
* Fixed a potential issue when using the `WebServiceClient` in multi-threaded
  applications.
* Updated documentation.

0.7.0 (2013-11-05)
------------------

* Renamed `getSubdivisionsList` to `getSubdivisions` on `AbstractNamedRecord`.
* An `InputStream` constructor was added to the `DatabaseReader.Builder`
  class. This reads the stream into memory as if it was using the
  `FileMode.MEMORY` mode. Patch by Matthew Daniel.
* The source code is now attached during packaging. Patch by Matthew Daniel.

0.6.0 (2013-10-23)
------------------

* IMPORTANT API CHANGE: The `DatabaseReader` class now uses a builder to
  construct the object. The class constructor on `DatabaseReader` is no longer
  public.
* Renamed the `languages` method on the `WebServiceClient.Builder` to
  `locales`.

0.5.0 (2013-10-17)
------------------

* Reorganized the response and record classes. The response classes end
  with `Response`. The record classes no longer end in `Record`.

0.4.1 (2013-08-16)
------------------

* Set the user-agent header to include API information.
* Updated documentation.
* Removed unused dependency from Maven POM.

0.4.0 (2013-07-08)
------------------

* Removed class hierarchy among web-service endpoint models.
* Refactored database-reader API to more closely match the web-service API.
  Created a Java interface for the two classes.

0.3.0 (2013-06-27)
------------------

* Reorganized the classes. `Client` was renamed `WebServiceClient` and moved
  to `com.maxmind.geoip2`. Record classes now have a suffix of "Record".
  The product classes (e.g., Omni) were renamed to their product name with
  no "Lookup" suffix.
* Additional specific exceptions were added to replace the general
  `WebServiceException`.
* A `DatabaseReader` class was added to the distribution. This reads GeoIP2
  databases and returns similar product object to `WebServiceClient`.

0.2.0 (2013-06-13)
------------------

* Replaced the public constructor on `Client` with a `Builder` class.

0.1.1 (2013-06-10)
------------------

* First official beta release.
* Documentation updates and corrections.
* Changed license to Apache License, Version 2.0.

0.1.0 (2013-05-21)
------------------

* Initial release


text:
{% extends "layout.html" %}

{% block page_title %}Connexion{% endblock %}

{% block content %}

Identification

    <form action="/login" method="POST">
        {{ form.hidden_tag() }}
        Identifiant :
        {{ form.email() }}
        Mot de passe :
        {{ form.password() }}

            {{ form.submit(class='btn btn-primary', value='Se connecter') }}

    </form>

{% endblock %}


text: export { default } from './DirectChat';


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      First Order Logic Day 2 · Notes

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

          Notes

Class notes for Nate Harada

      Home
      About
      Blog

          EECS492

          EECS598

          EECS584

          EECS545

          EECS586

          EECS583

© 2015. All rights reserved.

First Order Logic Day 2

  09 Oct 2014

The Move to First Order Logic

We want to move away from propositional logic. Propositional logic is good because it's unambiguous but too specific - we want to allow variables in the logic.

In first order logic we have objects (rooms, dogs, etc) and relations. Relations test a property of one or more objects, and with no arguments these are equivalent to propositional logic.

Relations - properties that are links between variables
Function - input a tuple, output a value

First order logic is the same as propositional logic with variables. Obviously first order logic is more complicated, but it's in fact much more so. There are new variables in FOL called qualifier variables:

 - Says "for all", and is equivalent to a big conjunction.

 - Says "there exists", equivalent to a big disjunction.

We introduce restrictions to reduce complication:

Unique-names assumption - Two names cannot be the same object

Closed-world assumption - Any sentences unknown to be true are false

Domain closure - There are no more domain objects than the ones specified

These assumptions allow us to more concisely specify logic.

Quantifiers

We'll use quantifiers using an ASK/TELL interface. We can tell explicit facts or we can tell via variables. We can ask for statements, or we can ask for variables, aka  Person(x)  {x/Robert} and {x\John}.

Inference

Universal instantiation lets us infer any sentence by substituting a ground term for the variable. Aka:

The same thing applies for . Basically we reduce a higher order function by partially applying an argument.

Related Posts

            Classic Optimization
            11 Nov 2015

            Pin Paper
            14 Oct 2015

            Paper Reviews 1 and 2
            12 Oct 2015


text:
from django.conf.urls import patterns, url

from . import views

urlpatterns = patterns('',
    url(r'^$',
        views.ProjectListView.as_view(),
        name='zipfelchappe_project_list'),
    url(r'^project/(?P<slug>[\w-]+)/$',
        views.ProjectDetailView.as_view(),
        name='zipfelchappe_project_detail'),
    url(r'^project/(?P<slug>[\w-]+)/update/(?P<pk>\d+)/$',
        views.UpdateDetailView.as_view(),
        name='zipfelchappe_update_detail'),
    url(r'^category/(?P<slug>[\w-]+)/',
        views.ProjectCategoryListView.as_view(),
        name='zipfelchappe_project_category_list'),
    url(r'^back/(?P<slug>[\w-]+)/$',
        views.project_back_form,
        name='zipfelchappe_project_back_form'),

    url(r'^backer/authenticate/$',
        views.backer_authenticate,
        name='zipfelchappe_backer_authenticate'),
    url(r'^backer/login/$',
        views.BackerLoginView.as_view(),
        name='zipfelchappe_backer_login'),
    url(r'^backer/register/$',
        views.BackerRegisterView.as_view(),
        name='zipfelchappe_backer_register'),

    url(r'^pledge/thankyou/$',
        views.pledge_thankyou,
        name='zipfelchappe_pledge_thankyou'),
    url(r'^pledge/cancel/$',
        views.pledge_cancel,
        name='zipfelchappe_pledge_cancel'),
    url(r'^pledge/lost/$',
        views.PledgeLostView.as_view(),
        name='zipfelchappe_pledge_lost'),
)


text:
        // MESSAGE AHRS PACKING
package com.MAVLink.ardupilotmega;
import com.MAVLink.MAVLinkPacket;
import com.MAVLink.Messages.MAVLinkMessage;
import com.MAVLink.Messages.MAVLinkPayload;
        //import android.util.Log;

        /**
        * Status of DCM attitude estimator
        */
        public class msg_ahrs extends MAVLinkMessage{

        public static final int MAVLINK_MSG_ID_AHRS = 163;
        public static final int MAVLINK_MSG_LENGTH = 28;
        private static final long serialVersionUID = MAVLINK_MSG_ID_AHRS;

         	/**
        * X gyro drift estimate rad/s
        */
        public float omegaIx;
         	/**
        * Y gyro drift estimate rad/s
        */
        public float omegaIy;
         	/**
        * Z gyro drift estimate rad/s
        */
        public float omegaIz;
         	/**
        * average accel_weight
        */
        public float accel_weight;
         	/**
        * average renormalisation value
        */
        public float renorm_val;
         	/**
        * average error_roll_pitch value
        */
        public float error_rp;
         	/**
        * average error_yaw value
        */
        public float error_yaw;

        /**
        * Generates the payload for a mavlink message for a message of this type
        * @return
        */
        public MAVLinkPacket pack(){
		MAVLinkPacket packet = new MAVLinkPacket();
		packet.len = MAVLINK_MSG_LENGTH;
		packet.sysid = 255;
		packet.compid = 190;
		packet.msgid = MAVLINK_MSG_ID_AHRS;
        		packet.payload.putFloat(omegaIx);
        		packet.payload.putFloat(omegaIy);
        		packet.payload.putFloat(omegaIz);
        		packet.payload.putFloat(accel_weight);
        		packet.payload.putFloat(renorm_val);
        		packet.payload.putFloat(error_rp);
        		packet.payload.putFloat(error_yaw);

		return packet;
        }

        /**
        * Decode a ahrs message into this class fields
        *
        * @param payload The message to decode
        */
        public void unpack(MAVLinkPayload payload) {
        payload.resetIndex();
        	    this.omegaIx = payload.getFloat();
        	    this.omegaIy = payload.getFloat();
        	    this.omegaIz = payload.getFloat();
        	    this.accel_weight = payload.getFloat();
        	    this.renorm_val = payload.getFloat();
        	    this.error_rp = payload.getFloat();
        	    this.error_yaw = payload.getFloat();

        }

        /**
        * Constructor for a new message, just initializes the msgid
        */
        public msg_ahrs(){
    	msgid = MAVLINK_MSG_ID_AHRS;
        }

        /**
        * Constructor for a new message, initializes the message with the payload
        * from a mavlink packet
        *
        */
        public msg_ahrs(MAVLinkPacket mavLinkPacket){
        this.sysid = mavLinkPacket.sysid;
        this.compid = mavLinkPacket.compid;
        this.msgid = MAVLINK_MSG_ID_AHRS;
        unpack(mavLinkPacket.payload);
        //Log.d("MAVLink", "AHRS");
        //Log.d("MAVLINK_MSG_ID_AHRS", toString());
        }

        /**
        * Returns a string with the MSG name and data
        */
        public String toString(){
    	return "MAVLINK_MSG_ID_AHRS -"+" omegaIx:"+omegaIx+" omegaIy:"+omegaIy+" omegaIz:"+omegaIz+" accel_weight:"+accel_weight+" renorm_val:"+renorm_val+" error_rp:"+error_rp+" error_yaw:"+error_yaw+"";
        }
        }


text:
<?php
require_once 'password.php';

class USER
{
	private $db;

	function __construct($DB_con)
	{
		$this->db = $DB_con;
	}

	public function register($umail,$upass)
	{
		try
		{
			$new_password = password_hash($upass, PASSWORD_DEFAULT);

			$stmt = $this->db->prepare("INSERT INTO profile (name,email,password,picture,big_picture,avatar)
		                                               VALUES(:uname,:umail, :upass, 'img/profile/pics/placeholder.png', 'img/profile/pics/placeholder.png', 'img/profile/avatars/placeholder.png')");

			$stmt->bindparam(":uname", explode('@', $umail)[0]);
			$stmt->bindparam(":umail", $umail);
			$stmt->bindparam(":upass", $new_password);

			$stmt->execute();

			return $stmt;
		}
		catch(PDOException $e)
		{
			echo $e->getMessage();
		}
	}

	public function login($umail,$upass)
	{
		try
		{
			$stmt = $this->db->prepare("SELECT id, password FROM profile WHERE email=:umail LIMIT 1");
			$stmt->execute(array(':umail'=>$umail));
			$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
			if($stmt->rowCount() > 0)
			{
				if(password_verify($upass, $userRow['password']))
				{
					$_SESSION['user_session'] = $userRow['id'];
					return true;
				}
				else
				{
					return false;
				}
			}
		}
		catch(PDOException $e)
		{
			echo $e->getMessage();
		}
	}

	public function is_loggedin()
	{
		if(isset($_SESSION['user_session']))
		{
			return true;
		}
	}

	public function redirect($url)
	{
		header("Location: $url");
	}

	public function logout()
	{
		session_destroy();
		unset($_SESSION['user_session']);
		return true;
	}
}
?>


text:
package net.jr.jrc.ast;

import net.jr.jrc.ast.visitor.AstVisitor;
import net.jr.jrc.types.Type;
import net.jr.jrc.types.VoidType;

public class AstReturn extends AstNode {

  private AstNode value;

  public AstReturn(AstNode value) {
    this.value = value;
  }

  public AstNode getValue() {
    return value;
  }

  public void setValue(AstNode value) {
    this.value = value;
  }

  @Override
  public AstNode getModified(AstVisitor<AstNode> v) {
    if (value != null) {
      setValue(getValue().getModified(v));
    }
    return v.visitReturn(this);
  }

  @Override
  public Type getType() {
    return value == null ? VoidType.TYPE : value.getType();
  }

  @Override
  public <T> T getVisited(AstVisitor<T> v) {
    return v.visitReturn(this);
  }
}


text:
module Moped
  module Instrumentable

    # Provides logging instrumentation for compatibility with active support
    # notifications.
    #
    # @since 2.0.0
    class Log

      class << self

        # Instrument the log payload.
        #
        # @example Instrument the log payload.
        #   Log.instrument("moped.ops", {})
        #
        # @param [ String ] name The name of the logging type.
        # @param [ Hash ] payload The log payload.
        #
        # @return [ Object ] The result of the yield.
        #
        # @since 2.0.0
        def instrument(name, payload = {})
          started = Time.new
          begin
            yield if block_given?
          rescue Exception => e
            payload[:exception] = [ e.class.name, e.message ]
            raise e
          ensure
            runtime = ("%.4fms" % (1000 * (Time.now.to_f - started.to_f)))
            if name == TOPIC
              Moped::Logging.log_operations(payload[:prefix], payload[:ops], runtime)
            else
              Moped::Logging.debug(payload[:prefix], payload.reject { |k,v| k == :prefix }, runtime)
            end
          end
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
	   default-lazy-init="true">
	<bean id="solrService" class="com.ansteel.solr.core.service.SolrServiceImpl">
		<property name="urlPath" value="${solr.urlPath}" />
	</bean>

</beans>


text:
package org.springframework.security;

/**
 * Represents the interface of a secured object.
 *
 * @author Ben Alex
 */
public interface ITargetObject {
	// ~ Methods
	// ========================================================================================================

	Integer computeHashCode(String input);

	int countLength(String input);

	String makeLowerCase(String input);

	String makeUpperCase(String input);

	String publicMakeLowerCase(String input);
}


text:
package com.yahoo.athenz.zts.cert.impl.crypki;

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.ALWAYS)
public class KeyMeta {

    public KeyMeta(String identifier) {
        this.identifier = identifier;
    }

    private String identifier;

    public String getIdentifier() {
        return identifier;
    }

    public void setIdentifier(String identifier) {
        this.identifier = identifier;
    }

}


text:
using System;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;

class Program : Base
{
  [ClousotRegressionTest]
  [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: x", PrimaryILOffset = 8, MethodILOffset = 14)]
  static void Main(string[] args)
  {
    Program p = new Program();

    // this line should generate a contract violation warning
    // since InnerFoo requires true.
    p.myInner.InnerFoo(false);

  }

  [ClousotRegressionTest]
  [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: x", PrimaryILOffset = 8, MethodILOffset = 9)]
  static void Main2(string[] args)
  {
    Program p = new Program();

    p.BaseFoo(false);
  }

  [ClousotRegressionTest]
  [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: x (inner gotta have x)", PrimaryILOffset = 12, MethodILOffset = 14)]
  static void Main3(string[] args)
  {
    Program p = new Program();

    // this line should generate a contract violation warning
    // since InnerFoo requires true.
    p.myInner.InnerFoo2(false);

  }

  [ClousotRegressionTest]
  [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"requires is false: x (base gotta have x)", PrimaryILOffset = 12, MethodILOffset = 9)]
  static void Main4(string[] args)
  {
    Program p = new Program();

    p.BaseFoo2(false);
  }

  [ClousotRegressionTest]
  [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "invariant unproven: data > 0", PrimaryILOffset = 16, MethodILOffset = 8)]
  [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "invariant unproven: data < 10 (upper bound)", PrimaryILOffset = 42, MethodILOffset = 8)]
  public void UpdateData(int value)
  {
    this.data = value;
  }

  [ClousotRegressionTest]
  [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"ensures is false: Contract.Result<int>() > 0", PrimaryILOffset = 15, MethodILOffset = 6)]
  public override int Bar()
  {
    return 0;
  }

  [ClousotRegressionTest]
  [RegressionOutcome(Outcome = ProofOutcome.False, Message = @"ensures is false: Contract.Result<int>() > 0 (result positive)", PrimaryILOffset = 19, MethodILOffset = 6)]
  public override int Bar2()
  {
    return 0;
  }

  public class Inner2 : Inner
  {
    /// <summary>
    /// Looks correct
    /// </summary>
    /// <returns></returns>
    [ClousotRegressionTest]
    [RegressionOutcome(Outcome = ProofOutcome.False, Message = "ensures is false: Contract.Result<int>() > 0", PrimaryILOffset = 15, MethodILOffset = 6)]
    public override int InnerBar()
    {
      return 0;
    }

    [ClousotRegressionTest]
    [RegressionOutcome(Outcome = ProofOutcome.False, Message = "ensures is false: Contract.Result<int>() > 0 (result positive)", PrimaryILOffset = 19, MethodILOffset = 6)]
    public override int InnerBar2()
    {
      return 0;
    }

    [ClousotRegressionTest]
    [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "invariant unproven: InnerData > 0", PrimaryILOffset = 16, MethodILOffset = 8)]
    public void BadInnerInv(int x)
    {
      this.InnerData = x;
    }

  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="128dp">

    <ImageView
        android:id="@+id/notification_image"
        android:layout_width="@dimen/notification_big_view_height"
        android:layout_height="@dimen/notification_big_view_height"
        android:scaleType="fitStart"/>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent">

        <include
            layout="@layout/view_notification_title_part"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0">

            <ImageButton
                android:layout_width="@dimen/notification_button_height"
                android:layout_height="@dimen/notification_button_height"
                android:layout_gravity="start"
                android:src="@android:drawable/ic_media_previous"/>

            <ImageButton
                android:layout_width="@dimen/notification_button_height"
                android:layout_height="@dimen/notification_button_height"
                android:layout_gravity="end"
                android:src="@android:drawable/ic_media_next"/>

        </FrameLayout>

    </LinearLayout>

</LinearLayout>


text:
exports.DateUtil = require('../src/date-util.js').DateUtil;

// ----- Exports from test/src/string-util.js -----
exports.StringUtil = require('../src/string-util.js').StringUtil;


text:
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

import { ContentState, EditorState, convertToRaw } from 'draft-js';
import React, { useState } from 'react';

import { Editor } from 'react-draft-wysiwyg';
import Label from './Label';
import { OnChange } from 'react-final-form-listeners';
import PropTypes from 'prop-types';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import sanitizeHtml from 'sanitize-html';

const createEditorState = value => {
  return EditorState.createWithContent(
    ContentState.createFromBlockArray(htmlToDraft(value))
  );
};

export default function HtmlEditor(props) {
  const getInputValue = newEditorState => {
    const textLength = newEditorState.getCurrentContent().getPlainText().length;
    return textLength === 0
      ? ''
      : draftToHtml(convertToRaw(newEditorState.getCurrentContent()));
  };
  const invalid = !!props.meta.error;
  const [editorState, setEditorState] = useState(
    createEditorState(props.input.value)
  );

  return (
    <div className={`form-group row`}>
      <OnChange name={props.input.name}>
        {value => {
          if (getInputValue(editorState) !== value) {
            setEditorState(createEditorState(value || ''));
          }
        }}
      </OnChange>

        <Editor
          editorState={editorState}
          spellCheck
          stripPastedStyles
          onEditorStateChange={newEditorState => {
            setEditorState(newEditorState);
            props.input.onChange(getInputValue(newEditorState));
          }}
          placeholder={
            props.placeholder &&
            sanitizeHtml(props.placeholder, {
              allowedTags: [],
              allowedAttributes: {}
            })
          }
          toolbar={{
            options: ['inline', 'list', 'history', 'link'],
            inline: {
              options: [
                'bold',
                'italic',
                'underline',
                'strikethrough',
                'superscript',
                'subscript'
              ]
            }
          }}
          wrapperClassName={invalid ? ' is-invalid' : ''}
          wrapperId={`service_${props.input.name}`}
        />
        {invalid &&
{props.meta.error}
}

  );
}

HtmlEditor.propTypes = {
  input: PropTypes.object.isRequired,
  meta: PropTypes.object.isRequired,
  placeholder: PropTypes.string,
  label: PropTypes.string,
  required: PropTypes.bool
};


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactDom = require('react-dom');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var Portal = function (_React$Component) {
  (0, _inherits3['default'])(Portal, _React$Component);

  function Portal() {
    (0, _classCallCheck3['default'])(this, Portal);
    return (0, _possibleConstructorReturn3['default'])(this, (Portal.__proto__ || Object.getPrototypeOf(Portal)).apply(this, arguments));
  }

  (0, _createClass3['default'])(Portal, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.createContainer();
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.removeContainer();
    }
  }, {
    key: 'createContainer',
    value: function createContainer() {
      this._container = this.props.getContainer();
      this.forceUpdate();
    }
  }, {
    key: 'removeContainer',
    value: function removeContainer() {
      if (this._container) {
        this._container.parentNode.removeChild(this._container);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      if (this._container) {
        return (0, _reactDom.createPortal)(this.props.children, this._container);
      }
      return null;
    }
  }]);
  return Portal;
}(_react2['default'].Component);

Portal.propTypes = {
  getContainer: _propTypes2['default'].func.isRequired,
  children: _propTypes2['default'].node.isRequired
};
exports['default'] = Portal;
module.exports = exports['default'];


text:
package calculators;

import consumer.Consumer;

/**
 * Created by fedinskiy on 10.02.17.
 */
public abstract class BasicCalculator implements Runnable{
    private final int[] values;

    private Consumer consumer;

    public BasicCalculator(Consumer consumer,int[] toCalc) {
        this.consumer=consumer;
        values=toCalc;

    }
    protected abstract Consumer getLocker();

    protected abstract void setLocker(Consumer consumer);

    protected abstract int getPower();

    public abstract void toConsumer(Consumer consumer, int i);

    @Override
    public void run() {
        for(int i:this.values){
            while (true) {
                if (consumer != this.getLocker()) {
                    this.setLocker(consumer);
                    break;
                }
            }
            this.toConsumer(consumer, (int) Math.pow(i,this.getPower()));
            this.setLocker(null);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace OAuth2_UserIdentity.Models
{
    public class UserStateValue
    {
        public int UserStateValueID { get; set; }
        public string userObjId { get; set; }
        public string stateGuid { get; set; }
    }
}


text:
#ifndef _QmitkIOUtil__h_
#define _QmitkIOUtil__h_

#include "MitkQtWidgetsExports.h"

// std
#include <string>

// mitk includes
#include <mitkBaseData.h>
#include <mitkCommon.h>
#include <mitkDataNode.h>
#include <mitkFileWriterWithInformation.h>
#include <mitkIOUtil.h>
#include <mitkImage.h>
#include <mitkPointSet.h>
#include <mitkSurface.h>

// Qt
#include <QList>
#include <QPair>
#include <QScopedPointer>
#include <QString>

class QWidget;
class QString;
class QStringList;

namespace mitk
{
  class DataStorage;
  class MimeType;
  struct IFileReader;
}

/**
 * @brief QmitkIOUtil Provides static helper methods to open and save files with Qt dialogs.
 */
class MITKQTWIDGETS_EXPORT QmitkIOUtil : public mitk::IOUtil
{
public:
  class MITKQTWIDGETS_EXPORT SaveFilter
  {
  public:
    static mitk::MimeType ALL_MIMETYPE();

    SaveFilter(const SaveFilter &other);

    SaveFilter(const SaveInfo &saveInfo);

    SaveFilter &operator=(const SaveFilter &other);

    std::vector<mitk::MimeType> GetMimeTypes() const;
    QString GetFilterForMimeType(const std::string &mimeType) const;
    mitk::MimeType GetMimeTypeForFilter(const QString &filter) const;
    QString GetDefaultFilter() const;
    QString GetDefaultExtension() const;
    mitk::MimeType GetDefaultMimeType() const;
    QString ToString() const;
    int Size() const;
    bool IsEmpty() const;

    bool ContainsMimeType(const std::string &mimeType);

  private:
    struct Impl;
    QScopedPointer<Impl> d;
  };

  /**
   * @brief GetFilterString
   * @return
   */
  static QString GetFileOpenFilterString();

  /**
   * @brief Loads the specified files
   *
   * This methods tries to load all specified files and pop-ups dialog boxes if further
   * user input is required (e.g. ambiguous mime-types or reader options).
   *
   * If the provided DataStorage is not nullptr, some files will be added to it automatically,
   * dependeing on the IFileReader used.
   *
   * @param files A list of files to load.
   * @param ds An optional data storage passed to IFileReader instances
   * @return A list of BaseData instances which have not already been added to the data storage.
   */
  static QList<mitk::BaseData::Pointer> Load(const QStringList &paths, QWidget *parent = nullptr);

  static mitk::DataStorage::SetOfObjects::Pointer Load(const QStringList &paths,
                                                       mitk::DataStorage &storage,
                                                       QWidget *parent = nullptr);

  static QList<mitk::BaseData::Pointer> Load(const QString &path, QWidget *parent = nullptr);

  static mitk::DataStorage::SetOfObjects::Pointer Load(const QString &path,
                                                       mitk::DataStorage &storage,
                                                       QWidget *parent = nullptr);

  using mitk::IOUtil::Load;

  static QString Save(const mitk::BaseData *data,
                      const QString &defaultBaseName,
                      const QString &defaultPath = QString(),
                      QWidget *parent = nullptr,
                      bool setPathProperty = false);

  /**
   * @brief Save a list of BaseData objects using a "File Save Dialog".
   *
   * For each element in the \c data vector, the following algorithm is
   * used to find a IFileWriter instance for writing the BaseData object.
   *
   * First, the user is prompted to select file names for each BaseData object. This
   * is equivalent to choosing a specific mime-type, either by selecting a filter
   * in the save dialog or by explicitly providing a file name extension:
   *

   *
Get a list of registered IFileWriter objects for the current BaseData object.
   *     If no writers are found, a message box displays a warning and
   *     the process starts from the beginning for the next BaseData object.

   *
A QFileDialog for prompting the user to select a file name is opened.
   *     The mime-type associated with each IFileWriter object is used to create
   *     a filter for file name extensions.
   *     The best IFileWriter (see FileWriterSelector) for the current BaseData object
   *     defines the default file name suffix via its associated mime-type. If the
   *     file name is empty (the user cancelled the dialog), the remaining
   *     BaseData objects are skipped.
   *
The file name is matched against valid mime-types. The first mime-type
   *     which accepts the file name is associated with the current BaseData object.
   *     If no mime-type accepts the supplied file name and the file already
   *     exists, the process starts from the beginning with the next BaseData object.
   *     Otherwise, if the selected filter is the special "all" filter and the
   *     file name does not contain periods (which may or may not mark the start of
   *     a file extension), the current BaseData object is associated with the
   *     default mime-type. If the selected filter is not the special "all" filter,
   *     the mime-type for this filter is associated with the current BaseData object.
   *     The default extension of the associated mime-type is then appended to the
   *     supplied file name.
   *
The selected/derived file name and associated mime-type is stored in a list
   *     and the process starts from the beginning for the next BaseData object.

   *

   *
   * In the second phase, each BaseData object is saved to disk using the specified
   * file name and mime-type, according to the following procedure:
   *

   *
If multiple IFileWriter objects are compatible with the current base data
   *     object or if the single compatible IFileWriter provides configuration
   *     options, a dialog window containing a list of IFileWriter objects and
   *     configurable options is displayed. If the dialog is cancelled by the user,
   *     neither the current nor the remaining base data objects are saved to disk.
   *     If the user previously in this phase enabled the "remember options" checkbox
   *     of the dialog, then the dialog is not shown for base data objects with the
   *     same data type and associated mime-type if the file writer instance reports
   *     a higher or equal confidence level for the current base data object.

   *
The selected writer (either the only available one or the user selected one)
   *     is used to write the base data object to disk. On failure, an error is
   *     reported and the second phase continues with the next base data object.

   *

   *
   * @param data
   * @param defaultBaseNames
   * @param defaultPath
   * @param parent
   * @return
   */
  static QStringList Save(const std::vector<const mitk::BaseData *> &data,
                          const QStringList &defaultBaseNames,
                          const QString &defaultPath = QString(),
                          QWidget *parent = nullptr,
                          bool setPathProperty = false);

  using mitk::IOUtil::Save;

  /**
   * @brief SaveBaseDataWithDialog Convenience method to save any data with a Qt dialog.
   * @param data BaseData holding the data you wish to save.
   * @param fileName The file name where to save the data (including path and extension).
   * @param parent An optional QWidget as parent. If no parent is supplied, the QFileDialog can occur anywhere on the
   * screen.
   * @deprecatedSince{2014_10} Use Save() instead.
   */
  DEPRECATED(static void SaveBaseDataWithDialog(mitk::BaseData *data, std::string fileName, QWidget *parent = nullptr));

  /**
   * @brief SaveSurfaceWithDialog Convenience method to save a surface with a Qt dialog.
   * @param surface The surface to save.
   * @param fileName The file name where to save the data (including path and extension).
   * @param parent An optional QWidget as parent. If no parent is supplied, the QFileDialog can occur anywhere on the
   * screen.
   * @deprecatedSince{2014_10} Use Save() instead.
   */
  DEPRECATED(static void SaveSurfaceWithDialog(mitk::Surface::Pointer surface,
                                               std::string fileName = "",
                                               QWidget *parent = nullptr));

  /**
   * @brief SaveImageWithDialog Convenience method to save an image with a Qt dialog.
   * @param image The image to save.
   * @param fileName The file name where to save the data (including path and extension).
   * @param parent An optional QWidget as parent. If no parent is supplied, the QFileDialog can occur anywhere on the
   * screen.
   * @deprecatedSince{2014_10} Use Save() instead.
   */
  DEPRECATED(static void SaveImageWithDialog(mitk::Image::Pointer image,
                                             std::string fileName = "",
                                             QWidget *parent = nullptr));

  /**
   * @brief SavePointSetWithDialog Convenience method to save a pointset with a Qt dialog.
   * @param pointset The pointset to save.
   * @param fileName The file name where to save the data (including path and extension).
   * @param parent An optional QWidget as parent. If no parent is supplied, the QFileDialog can occur anywhere on the
   * screen.
   * @deprecatedSince{2014_10} Use Save() instead.
   */
  DEPRECATED(static void SavePointSetWithDialog(mitk::PointSet::Pointer pointset,
                                                std::string fileName = "",
                                                QWidget *parent = nullptr));

private:
  struct Impl;
};

#endif // _QmitkIOUtil__h_


text: default['rvm']['vagrant']['system_chef_solo'] = "/opt/ruby/bin/chef-solo"


text:
#include <openthread/config.h>
#include <openthread-core-config.h>
#include <openthread/platform/misc.h>
#include <openthread/platform/platform.h>

#include <device/nrf.h>

#include "platform-nrf5.h"

#if SOFTDEVICE_PRESENT
#include "softdevice.h"
#endif

static uint32_t sResetReason;

__WEAK void nrf5CryptoInit(void)
{
    // This function is defined as weak so it could be overridden with external implementation.
}

__WEAK void nrf5CryptoDeinit(void)
{
    // This function is defined as weak so it could be overridden with external implementation.
}

void nrf5MiscInit(void)
{
#if SOFTDEVICE_PRESENT
    sd_power_reset_reason_get(&sResetReason);
    sd_power_reset_reason_clr(0xFFFFFFFF);
#else
    sResetReason = NRF_POWER->RESETREAS;
    NRF_POWER->RESETREAS = 0xFFFFFFFF;
#endif // SOFTDEVICE_PRESENT
}

void nrf5MiscDeinit(void)
{
    // Intentionally empty.
}

void otPlatReset(otInstance *aInstance)
{
    (void)aInstance;

    PlatformDeinit();

    NVIC_SystemReset();
}

otPlatResetReason otPlatGetResetReason(otInstance *aInstance)
{
    (void)aInstance;
    otPlatResetReason reason;

    if (sResetReason & POWER_RESETREAS_RESETPIN_Msk)
    {
        reason = OT_PLAT_RESET_REASON_EXTERNAL;
    }
    else if (sResetReason & POWER_RESETREAS_DOG_Msk)
    {
        reason = OT_PLAT_RESET_REASON_WATCHDOG;
    }
    else if (sResetReason & POWER_RESETREAS_SREQ_Msk)
    {
        reason = OT_PLAT_RESET_REASON_SOFTWARE;
    }
    else if (sResetReason & POWER_RESETREAS_LOCKUP_Msk)
    {
        reason = OT_PLAT_RESET_REASON_FAULT;
    }
    else if ((sResetReason & POWER_RESETREAS_OFF_Msk)    ||
             (sResetReason & POWER_RESETREAS_LPCOMP_Msk) ||
             (sResetReason & POWER_RESETREAS_DIF_Msk)    ||
             (sResetReason & POWER_RESETREAS_NFC_Msk)    ||
             (sResetReason & POWER_RESETREAS_VBUS_Msk))
    {
        reason = OT_PLAT_RESET_REASON_OTHER;
    }
    else
    {
        reason = OT_PLAT_RESET_REASON_POWER_ON;
    }

    return reason;
}

void otPlatWakeHost(void)
{
    // TODO: implement an operation to wake the host from sleep state.
}


text:
layout: post
date:	2008-06-13 05:39:00
title:  What do I use when I want more copies....?
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
Rarely does one find things that are tailor-made for oneself...but here's a xerox centre on Kanakapura Road...

Sorry, Xerox Company, that has become a generic term and you should be proud of that rather than go to great expense and legal wrangles to avoid the word "xerox" being used this way!


text:
require 'rails_helper'

RSpec.describe "tutorials/edit", type: :view do
  before(:each) do
    @tutorial = assign(:tutorial, Tutorial.create!())
  end

  it "renders the edit tutorial form" do
    render

    assert_select "form[action=?][method=?]", tutorial_path(@tutorial), "post" do
    end
  end
end


text:
// Code generated by client-gen. DO NOT EDIT.

package v1beta1

import (
	"context"
	"time"

	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rest "k8s.io/client-go/rest"
	v1beta1 "k8s.io/ingress-gce/pkg/apis/ingparams/v1beta1"
	scheme "k8s.io/ingress-gce/pkg/ingparams/client/clientset/versioned/scheme"
)

// GCPIngressParamsGetter has a method to return a GCPIngressParamsInterface.
// A group's client should implement this interface.
type GCPIngressParamsGetter interface {
	GCPIngressParams() GCPIngressParamsInterface
}

// GCPIngressParamsInterface has methods to work with GCPIngressParams resources.
type GCPIngressParamsInterface interface {
	Create(ctx context.Context, gCPIngressParams *v1beta1.GCPIngressParams, opts v1.CreateOptions) (*v1beta1.GCPIngressParams, error)
	Update(ctx context.Context, gCPIngressParams *v1beta1.GCPIngressParams, opts v1.UpdateOptions) (*v1beta1.GCPIngressParams, error)
	Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
	DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error
	Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.GCPIngressParams, error)
	List(ctx context.Context, opts v1.ListOptions) (*v1beta1.GCPIngressParamsList, error)
	Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)
	Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.GCPIngressParams, err error)
	GCPIngressParamsExpansion
}

// gCPIngressParams implements GCPIngressParamsInterface
type gCPIngressParams struct {
	client rest.Interface
}

// newGCPIngressParams returns a GCPIngressParams
func newGCPIngressParams(c *NetworkingV1beta1Client) *gCPIngressParams {
	return &gCPIngressParams{
		client: c.RESTClient(),
	}
}

// Get takes name of the gCPIngressParams, and returns the corresponding gCPIngressParams object, and an error if there is any.
func (c *gCPIngressParams) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.GCPIngressParams, err error) {
	result = &v1beta1.GCPIngressParams{}
	err = c.client.Get().
		Resource("gcpingressparams").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do(ctx).
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of GCPIngressParams that match those selectors.
func (c *gCPIngressParams) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.GCPIngressParamsList, err error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	result = &v1beta1.GCPIngressParamsList{}
	err = c.client.Get().
		Resource("gcpingressparams").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Do(ctx).
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested gCPIngressParams.
func (c *gCPIngressParams) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
	var timeout time.Duration
	if opts.TimeoutSeconds != nil {
		timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
	}
	opts.Watch = true
	return c.client.Get().
		Resource("gcpingressparams").
		VersionedParams(&opts, scheme.ParameterCodec).
		Timeout(timeout).
		Watch(ctx)
}

// Create takes the representation of a gCPIngressParams and creates it.  Returns the server's representation of the gCPIngressParams, and an error, if there is any.
func (c *gCPIngressParams) Create(ctx context.Context, gCPIngressParams *v1beta1.GCPIngressParams, opts v1.CreateOptions) (result *v1beta1.GCPIngressParams, err error) {
	result = &v1beta1.GCPIngressParams{}
	err = c.client.Post().
		Resource("gcpingressparams").
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(gCPIngressParams).
		Do(ctx).
		Into(result)
	return
}

// Update takes the representation of a gCPIngressParams and updates it. Returns the server's representation of the gCPIngressParams, and an error, if there is any.
func (c *gCPIngressParams) Update(ctx context.Context, gCPIngressParams *v1beta1.GCPIngressParams, opts v1.UpdateOptions) (result *v1beta1.GCPIngressParams, err error) {
	result = &v1beta1.GCPIngressParams{}
	err = c.client.Put().
		Resource("gcpingressparams").
		Name(gCPIngressParams.Name).
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(gCPIngressParams).
		Do(ctx).
		Into(result)
	return
}

// Delete takes name of the gCPIngressParams and deletes it. Returns an error if one occurs.
func (c *gCPIngressParams) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
	return c.client.Delete().
		Resource("gcpingressparams").
		Name(name).
		Body(&opts).
		Do(ctx).
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *gCPIngressParams) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
	var timeout time.Duration
	if listOpts.TimeoutSeconds != nil {
		timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
	}
	return c.client.Delete().
		Resource("gcpingressparams").
		VersionedParams(&listOpts, scheme.ParameterCodec).
		Timeout(timeout).
		Body(&opts).
		Do(ctx).
		Error()
}

// Patch applies the patch and returns the patched gCPIngressParams.
func (c *gCPIngressParams) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.GCPIngressParams, err error) {
	result = &v1beta1.GCPIngressParams{}
	err = c.client.Patch(pt).
		Resource("gcpingressparams").
		Name(name).
		SubResource(subresources...).
		VersionedParams(&opts, scheme.ParameterCodec).
		Body(data).
		Do(ctx).
		Into(result)
	return
}