text:
module MPS.Math.FactoringCFRAC where

import MPS.Math.RedBlackTree
import MPS.Math.MergeSort
import MPS.Math.Primes
import MPS.Math.NumberTheoryFundamentals (splitWith, extendedEuclid, intSqrt, legendreSymbol)
import MPS.Math.ContinuedFraction (convergentsForSqrt)

-- FACTORING (LARGE PRIMES)

-- The algorithm is as follows:

-- 1. Find some numbers b s.t b*b mod n is small (or sometimes small and negative)
-- (Fermat's method would be to try numbers around intSqrt (k*n) for small k)
-- The continued fraction method uses the fact that continued fractions can provide good rational approximations to sqrt (k*n)

-- 2. For each b we have found, reduce b*b mod n to a factor base of small primes
-- (eg b1 -> p1^2*p2, b2 -> p3*p4^2, b3 -> p2*p3 etc)

-- (now we regard these reductions as vectors over F2, eg p2^2*p3 = (0,2,1,0,0,...) )
-- 3. Perform gaussian elimination on the vectors over the factor base, until we have a product of even powers of small primes
-- (eg b1*b2*b3 -> p1^2 * p2^2 * p3^2 * p4^2)

-- 4. Then we have x, a product of bis, and y, a product of pis, s.t x^2 = y^2 (mod n) - we are hoping, x /= +/- y (mod n)
-- (for example, we have (b1*b2*b3)^2 = (p1*p2*p3*p4)^2 )
-- Then we have x^2 - y^2 = 0 (mod n), so (x+y)(x-y) = kn.
-- What we're hoping is that either gcd (x+y,n) or gcd (x-y,n) will give us a factor
-- (It's not guaranteed, as we may find x+y = n, x-y = k, for example)

-- CONTINUED FRACTION CANDIDATES
-- We use the continued fraction expansion of sqrt kn to find numbers x s.t. x^2 `mod` n is small ( o(sqrt n) )

-- returns the least absolute residue, ie using a small negative number rather than a large positive number where possible
lmod x n = let x' = x `mod` n in if x' + x' < n then x' else x' - n

cfracCandidates k n = [(b `mod` n, (b*b) `lmod` n) | (_,(b,c)) <- convergentsForSqrt (k*n)]
-- b/c is an approximation to sqrt kn
-- hence we expect b*b - k*n*c*c == b*b `lmod` n to be small

-- REDUCTION TO FACTOR BASE

reduceToFactorBase :: [Integer] -> Integer -> (Integer, [(Integer,Int)])
-- the factor base should be a list of small primes
reduceToFactorBase fbase m
	| m > 0  = doReduceToFactorBase fbase m []
	| m < 0  = doReduceToFactorBase fbase (-m) [(-1,1)]
	where
		doReduceToFactorBase ps 1 factors = (1, factors)
		doReduceToFactorBase [] m factors = (m, factors)
		doReduceToFactorBase (p:ps) m factors =
			let (s, m') = m `splitWith` p
			in
				if (s>0)
				then doReduceToFactorBase ps m' ((p,s):factors)
				else doReduceToFactorBase ps m factors

-- This value is actually for MPQS (from Landquis)
-- However, brief experimentation shows it is good for CFRAC too
optimalFactorBase n = fromInteger (round (exp (sqrt (log n' * log (log n'))) ** (sqrt 2 / 4))) :: Int
	where n' = fromInteger n

factorBase k n = take b [p | p <- primesTo10000 ++ filter isPrime [10001,10003..], legendreSymbol (k*n) p `elem` [0,1]]
	where b = optimalFactorBase n

-- CONSTRUCTING OUR TABLE OF FACTORS

-- What we need to do now is take the cfracCandidates, reduce them to a factor base
-- until the number of candidates we have exceeds the number of factors we're using from the factor base
-- at that point we can expect to have linear dependencies between entries in the table

constructFactorTable k n =
	let
		fbase = factorBase k n
		candidates = [(b,factors) | (b,b2) <- cfracCandidates k n, (unfactored,factors) <- [reduceToFactorBase fbase b2], unfactored == 1]
	in doConstructFactorTable [] rbempty candidates
	where
		doConstructFactorTable table factors (entry@(b,ps):entries) =
			if length table > rbcount factors
			then reverse table -- !! reverse is temporary to help debugging
			else
				let factors' = foldl rbinsert factors (map fst ps)
				in doConstructFactorTable (entry:table) factors' entries
-- rather than counting the factors, we could just use the size of the factor base as our stopping point
-- test to see if it makes a significant difference

-- Cohen p479 says that k must be square-free, and kn = 0 or 1 (mod 4)
-- reverse order of last two clauses for slight speed improvement
allFactorTables n = [constructFactorTable k n | k <- [1..], isSquareFree k, k * n `mod` 4 `elem` [0,1] ]

-- GAUSSIAN ELIMINATION

-- We now regard [(b,[(p,a)])] as a sparse matrix over F2 (where p is the column index, and a `mod` 2 is the value)

-- For Gaussian elimination, we should choose the column having the least non-zero entries, and pivot on one of the rows having a non-zero entry in that column
-- We approximate this by pivoting on rows having the largest prime factor first
-- !! We could almost certainly do better by implementing this in a more sophisticated way

-- Calculate the weights of the columns (ie the number of non-zero entries)
columnWeights t = doAnalyzeFactorTable rbempty t
	where
		doAnalyzeFactorTable factors [] = rbtolist factors
		doAnalyzeFactorTable factors ((b,ps):rows) =
			let factors' = foldl (\rb (p,a) -> if even a then rb else rb `rbaddupdate` (p,1)) factors ps
			in doAnalyzeFactorTable factors' rows

-- Remove columns of weight 1, and the rows in which those columns have non-zero coefficients
-- (In other words, if there is a p, such that only one row contains (p,a) with a odd, then remove that row)
removeWeight1s ftable = doRemoveSingletons1 rbempty ftable
	where
		doRemoveSingletons1 factors ((b,ps):rows) =
			let factors' = foldl (doupdate b) factors ps
			in doRemoveSingletons1 factors' rows
		doRemoveSingletons1 factors [] = doRemoveSingletons2 factors
		doupdate b rb (p,a)
			| even a = rb
			| otherwise = case rb `rblookup` p of
				Nothing -> rb `rbupdate` (p,Just b)           -- this prime hasn't been seen before
				Just (Just b') -> rb `rbupdate` (p,Nothing)   -- this prime has been seen only once before
				Just Nothing -> rb                            -- this prime has been seen more than once already
		doRemoveSingletons2 factors =
			let singletonrows = filter (/= Nothing) (rbvalues factors)
			in filter (\(b,ps) -> Just b `notElem` singletonrows) ftable

addRow n (b,ps) (b',ps') = (b*b' `mod` n, multps ps ps')
	where
		multps as [] = as
		multps [] bs = bs
		multps ((p1,a1):ps) ((p2,a2):qs)
			| p1 > p2 = (p1,a1) : multps ps ((p2,a2):qs)
			| p1 == p2 = (p1,a1+a2) : multps ps qs
			| p1 < p2 = (p2,a2) : multps ((p1,a1):ps) qs

orderRows rows = map snd (mergeSort' (>) (map (\(b,ps) -> (largestPrime ps ,(b,ps)) ) rows))
	where
		largestPrime [] = 100000000 -- ie we want this row ordered before any other, as it is already reduced
		largestPrime ((p,a):pas) = if odd a then p else largestPrime pas

gaussElim _ [] = []
gaussElim n ((b,ps):rows) =
	if all (\(p,a) -> even a) ps
	then (b,ps) : gaussElim n rows
	else
		let (p,_) = head (filter (\(p,a) -> odd a) ps)  -- ie the last prime with odd exponent
		in gaussElim n (map (\row@(_,qs) -> if qs `hasOddPower` p then addRow n row (b,ps) else row) rows)
	where
		hasOddPower ((q,a):qs) p
			| q > p  = hasOddPower qs p
			| q == p = odd a
			| otherwise = False
		hasOddPower [] _ = False

-- FINDING A FACTOR
-- putting it all together, to use the results of Gaussian elimination to find a factor

-- find a factor once we have a (b,ps) with all exponents even
findFactorFromPair n (b,ps) =
	let y = product [p ^ (a `div` 2) | (p,a) <- ps] `mod` n
	in gcd n (b+y)

factorSplits n = map (findFactorFromPair n) (concat (map ( (gaussElim n) . orderRows . removeWeight1s) (allFactorTables n)))

findFactorCFRAC n = let n' = intSqrt n in if n == n' * n' then n' else findFactorCFRAC' n
-- we perform this test because the continued fraction code doesn't work if n is a perfect square

findFactorCFRAC' n = head [d | d <- factorSplits n, d /= 1, d /= n]

-- LARGE PRIME VARIATION

-- At the moment, if our b^2 `mod` n doesn't factor completely over our factor base, we throw it away
-- In the large prime variation, then if the unfactored part is a prime, we don't throw it away
-- What we do instead is store it in a separate large prime table
-- (Suppose b^2 `mod` n = ps * q, where q is the large prime - then we store (q, (b,ps)) in our rbtree)
-- If we ever get a collision, ie (q,(b,ps)) is already in the table, and we try to add (q,(b',ps'))
-- then we take both out of the table, and combine them to get an entry for the main table
-- b^2 = ps * q, and b'^2 = ps' * q,
-- so (b*b'/q)^2 = ps * ps' (mod n)
-- (we can calculate 1/q using extended Euclid)

constructFactorTableLP k n =
	let
		fbase = factorBase k n
		candidates = [(unfactored,(b,factors)) | (b,b2) <- cfracCandidates k n, (unfactored,factors) <- [reduceToFactorBase fbase b2] ]
	in doConstructFactorTable [] rbempty rbempty candidates
	where
		doConstructFactorTable table factors lptable (entry@(unfactored,(b,ps)):entries)
			| unfactored == 1 =
				if length table > rbcount factors
				then reverse table -- !! reverse is temporary to help debugging
				else
					let factors' = foldl rbinsert factors (map fst ps)
					in doConstructFactorTable ((b,ps):table) factors' lptable entries
			| isPrime unfactored = case lptable `rblookup` unfactored of
				Nothing ->
					let lptable' = lptable `rbupdate` (unfactored,[(b,ps)])
					in doConstructFactorTable table factors lptable' entries
				Just bps ->
					let
						lptable' = lptable `rbupdate` (unfactored,(b,ps):bps)
						tableadditions = map (lpentryfrom n unfactored (b,ps)) bps
						table' = tableadditions ++ table
					in doConstructFactorTable table' factors lptable' entries
			| otherwise = doConstructFactorTable table factors lptable entries
-- !! we don't check for duplicates when adding tableadditions - perhaps we should

lpentryfrom n q (b1,ps1) (b2,ps2) =
	let (u,v,d) = extendedEuclid n q  -- so un + vq = 1, so v is inverse of q mod n
	in
		if d == 1
		then
			let (b',ps') = addRow n (b1,ps1) (b2,ps2)
			in (b' * v `mod` n, ps')
		else error ("lpentryfrom: found factorization early: " ++ show d)

allFactorTablesLP n = [constructFactorTableLP k n | k <- [1..], isSquareFree k, k * n `mod` 4 `elem` [0,1] ]

factorSplitsLP n = map (findFactorFromPair n) (concat (map ( (gaussElim n) . orderRows . removeWeight1s) (allFactorTablesLP n)))

findFactorLP n = head [d | d <- factorSplitsLP n, d /= 1, d /= n]


text:
Native libsass plugin adding (file) digest functions

## Building

You need to have [libsass][1] already [compiled][2] or [installed][3] as a
shared library (inclusive header files). It is then compiled via `cmake`. See
this example to compile it on windows via [MinGW][4] Compiler Suite:

```cmd
git clone https://github.com/sass/libsass.git
mingw32-make -C libsass BUILD=shared CC=gcc -j5
git clone https://github.com/mgreter/libsass-digest.git
cd libsass-digest && mkdir build && cd build
cmake -G "MinGW Makefiles" .. -DLIBSASS_DIR="..\..\libsass"
mingw32-make CC=gcc -j5 && dir digest.dll
```

You may define `LIBSASS_INCLUDE_DIR` and `LIBSASS_LIBRARY_DIR` separately!

## API

The following functions are available when you import the digest plugin.

#### String digest functions
- `md5($x)` - Returns the MD5 digest for $x.
- `crc16($x)` - Returns a CRC16 checksum for $x.
- `crc32($x)` - Returns a CRC32 checksum for $x.
- `base64($x)` - Returns the Base64 text of $x.

#### File digest functions
- `md5f($x)` - Returns the MD5 digest for file $x.
- `crc16f($x)` - Returns a CRC16 checksum for file $x.
- `crc32f($x)` - Returns a CRC32 checksum for file $x.
- `base64f($x)` - Returns the Base64 text of file $x.

## Copyright

� 2017 [Marcel Greter][5]

[1]: https://github.com/sass/libsass
[2]: https://github.com/sass/libsass/wiki/Building-Libsass
[3]: http://libsass.ocbnet.ch/installer/
[4]: http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win32/Personal%20Builds/mingw-builds/
[5]: https://github.com/mgreter

redpajama_set_name: RedPajamaGithub


text:
var _ = require('underscore');
var Department = Parse.Object.extend('Department');

exports.index = function(req, res) {
	var query = new Parse.Query(Department);

	query.descending('createdAt');
	query.find().then(function(results) {
		res.render('departments/all', {departments: results});
	}, function() {
		res.render(500, 'Failed to load departments');
	});
};

exports.new = function(req, res) {
	var Faculty = Parse.Object.extend('Faculty');

	var facultyQuery = new Parse.Query(Faculty);
	facultyQuery.descending('createdAt');
	facultyQuery.find()
		.then(function(results) {
			console.log('departments: ' + results);
			res.render('departments/create', {
				faculties: results
			});
		}, function() {
			res.render('departments/create', {
				faculties: []
			});
		});
};

exports.create = function(req, res) {
	var department = new Department();

	// var Faculty = Parse.Object.extend('Faculty');
	// TODO retreive Faculty object with specified name

	department.save(_.pick(req.body, 'name', 'number', 'email', 'hod', 'faculty'))
		.then(function() {
			res.redirect('/departments');
		});
};

exports.indexJSON = function(req, res) {
	var query = new Parse.Qeury(Department);

	query.descending('createdAt');
	query.find().then(function(results) {
		res.json(results);
	});

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.surmon.pattern.editor2d.components;

import java.awt.AlphaComposite;
import static java.awt.AlphaComposite.getInstance;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.Collection;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputAdapter;
import org.opencv.core.MatOfPoint;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.surmon.pattern.api.ImageStack;
import org.surmon.pattern.api.Particle;
import org.surmon.pattern.api.ParticleCreator;
import org.surmon.pattern.api.PatternImage;
import org.surmon.pattern.api.utils.ImageConverter;
import org.surmon.pattern.editor2d.pick.RoiPicker;
import org.surmon.pattern.editor2d.render.RendererSet;
import org.surmon.pattern.editor2d.zoom.Zoom;
import org.surmon.pattern.editor2d.zoom.ZoomListener;
import org.surmon.pattern.visualization.api.ParticleRenderer;

/**
 * Contains panel with image representation.
 *
 * @author palasjiri
 */
public class ImageContainer extends JScrollPane implements ZoomListener, ImageStack.Listener {

    private final Zoom zoom;
    private final ImagePanel imagePanel;

    public ImageContainer(PatternImage image, Zoom zoom) {
        this.zoom = zoom;
        imagePanel = new ImagePanel(image);
        setViewportView(imagePanel);
    }

    @Override
    protected void processMouseWheelEvent(MouseWheelEvent e) {
        if (e.isControlDown()) {
            if (e.getWheelRotation() > 0) {
                zoom.out(e.getPoint());
            } else {
                zoom.in(e.getPoint());
            }
        } else {
            super.processMouseWheelEvent(e);
        }
    }

    @Override
    public void zoomChanged(Zoom zoom) {
        imagePanel.setScale(zoom.getRatio());
        getViewport().setViewPosition(zoom.getZoomedAt());
    }

    public void refresh() {
        imagePanel.repaint();
    }

    @Override
    public void onImageStackChanged(ImageStack stack) {
        imagePanel.setData(stack.getSelectedImage());
        refresh();
    }

    /**
     * Displays the image in a panel. Displays currently selected image in
     * Pattern Data. Main user interaction with image and particles is performed
     * here.
     *
     * @author palasjiri
     */
    private class ImagePanel extends JPanel implements KeyListener {

        private static final double epsilon = 5;
        private static final double minCircle = 0.5;
        static final double crossEpsilon = 5;

        private boolean pickingWithRoi = false;
        private boolean addingParticle = false;

        private PatternImage data;
        private BufferedImage image;

        private AffineTransform at;
        private double scale = 1.0;
        private Point addingSrcPoint;
        private Point addingDstPoint;

        private RoiPicker roi = null;
        private final AlphaComposite roiAc = getInstance(AlphaComposite.SRC_OVER, 0.25f);
        private final BasicStroke roiStroke = new BasicStroke(1.0f);

        private ParticleCreator particleCreator;
        private final RendererSet particleRenderers;

        public ImagePanel(PatternImage data) {
            setSize(data.getWidth(), data.getHeight());
            setBackground(Color.WHITE);
            this.data = data;
            image = ImageConverter.toBufferedImage(data.getPixels());

            initTransform();

            particleRenderers = new RendererSet();
            Collection<? extends ParticleRenderer> renderes = Lookup.getDefault().lookupAll(ParticleRenderer.class);
            for (ParticleRenderer particleRenderer : renderes) {
                particleRenderers.registerRenderer(particleRenderer);
            }

            addMouseListener(mAdapter);
            addMouseMotionListener(mAdapter);
            addKeyListener(this);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;

            //g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2.drawRenderedImage(image, at);

            // draw new particle newly beeing added
            if (addingSrcPoint != null && addingParticle) {
                g2.setColor(Color.GREEN);
                drawSimpleCross(g2, addingSrcPoint.x, addingSrcPoint.y);
                if (addingDstPoint != null) {
                    double r = addingDstPoint.distance(addingSrcPoint.x, addingSrcPoint.y);
                    r = scale * r;
                    drawCenteredCircle(g2, addingSrcPoint.x, addingSrcPoint.y, (int) Math.round(r));
                }
            }

            drawParticles(g2);
            drawROI(g2);
            drawMappingBorders(g2);

            g2.dispose();
        }

        /**
         * Draws region of interest. Semitransparent rectangle with border.
         *
         * @param g2
         */
        private void drawROI(Graphics2D g2) {
            if (pickingWithRoi && roi != null) {
                Rectangle2D r = roi.getBounds2D();
                g2.setPaint(Color.BLUE);
                g2.draw(r);
                g2.setComposite(roiAc);
                g2.setColor(Color.BLUE);
                g2.fill(r);
                g2.setComposite(AlphaComposite.SrcOver);
            }
        }

        /**
         * Draws simple cross (+) at location x,y.
         *
         *
         * @param g Graphics2D
         * @param x x-coord
         * @param y y-coord
         * @Deprecated
         */
        private void drawSimpleCross(Graphics2D g, double x, double y) {
            g.draw(new Line2D.Double(x, y - scale * crossEpsilon, x, y + scale * crossEpsilon));
            g.draw(new Line2D.Double(x - scale * crossEpsilon, y, x + scale * crossEpsilon, y));
        }

        /**
         * Draws circle at location x, y with radius r
         *
         *
         * @param g Graphics2D
         * @param x x-coordinate
         * @param y y-coordinate
         * @param r radius
         * @Deprecated
         */
        private void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
            x = x - r;
            y = y - r;
            g.drawOval(x, y, r * 2, r * 2);
        }

        /**
         * Initializes affine transformation from image size and zoom scale.
         */
        private void initTransform() {
            int w = getWidth();
            int h = getHeight();

            int imageWidth = data.getWidth();
            int imageHeight = data.getHeight();

            double x = (w - scale * imageWidth) / 2;
            double y = (h - scale * imageHeight) / 2;
            at = AffineTransform.getTranslateInstance(x, y);
            at.scale(scale, scale);
        }

        /**
         * Draws particles from image data into window.
         *
         * @param g2
         */
        private void drawParticles(Graphics2D g2) {
            AffineTransform saveAt = g2.getTransform();
            g2.transform(at);
            for (Particle p : data.getParticles()) {
                ParticleRenderer renderer = particleRenderers.findRenderer(p);
                if (renderer != null) {
                    renderer.draw(g2, p);
                } else {
                    throw new IllegalStateException("No renderer found for particle: " + p.getClass().getName());
                }
            }
            g2.setTransform(saveAt);
        }

        private void drawMappingBorders(Graphics2D g2) {
            AffineTransform saveAt = g2.getTransform();
            g2.transform(at);
            int[] xs;
            int[] ys;
            for (MatOfPoint border : data.getMappingBorders()) {
                int length = border.rows();
                xs = new int[length];
                ys = new int[length];
                for (int i = 0; i < length; i++) {
                    xs[i] = (int) border.get(i, 0)[0];
                    ys[i] = (int) border.get(i, 0)[1];
                }
                Polygon poly = new Polygon(xs, ys, length);
                g2.setColor(Color.magenta);
                g2.drawPolygon(poly);
            }
            g2.setTransform(saveAt);
        }

        /**
         * For the scroll pane.
         *
         * @return
         */
        @Override
        public Dimension getPreferredSize() {
            int w = (int) (scale * data.getWidth());
            int h = (int) (scale * data.getHeight());
            return new Dimension(w, h);
        }

        public void setScale(double s) {
            scale = s;
            initTransform();
            revalidate();
            repaint();
        }

        public void setData(PatternImage data) {
            this.data = data;
            long t = System.currentTimeMillis();
            image = ImageConverter.toBufferedImage(data.getPixels());
            System.out.println("Image load time " + (System.currentTimeMillis() - t));
            repaint();
        }

        /**
         * Checks if point lyies in the image.
         *
         * @param point
         * @return
         */
        boolean isInRange(Point2D point) {
            boolean flag = point.getX() >= 0;
            flag &= point.getY() >= 0;
            flag &= point.getX() <= data.getWidth();
            flag &= point.getY() <= data.getHeight();

            return flag;
        }

        /**
         * Implemetnts piking with mouse click. Particle is picked with single
         * click of mouse left button if some particle center is in neigbourhood
         * of clicked point. Neigbourhood is determined by mouse click and
         * epsilon.
         *
         * @param clickedPoint
         * @param epsilon neigbourhood size
         * @param shift true if is shift down, false otherwise
         */
        private void pickWithClick(Point clickedPoint, double epsilon, boolean shift) {
            Point2D back = toImageSpace(clickedPoint);

            Particle clicked = null;

            for (Particle c : data.getParticles()) {
                boolean flag = true;
                double[] pos = c.getPosition().toArray();
                flag &= back.getX() + epsilon >= pos[0] && back.getX() - epsilon <= pos[0];
                flag &= back.getY() + epsilon >= pos[1] && back.getY() - epsilon <= pos[1];

                if (flag) {
                    clicked = c;
                    System.out.println("Picked:" + pos[0] + " " + pos[1] + " with " + back + "clicked at" + clickedPoint);
                    break;
                }
            }

            if (clicked == null) {
                return;
            }

            if (!shift) {
                for (Particle c : data.getParticles()) {
                    if (c != clicked) {
                        c.setPicked(false);
                    } else {
                        c.setPicked(true);
                    }
                }
            } else {
                //swap the click
                clicked.setPicked(!clicked.isPicked());
            }

            repaint();
        }

        /**
         * Implements picking logic. If shift is pressed while picking with roi
         * then selected particles are added to previously selected. If alt is
         * pressed while picking with roi then particles within the roi are
         * removed from selection. If no modificator (alt, shift) is pressed
         * then all previously selected data are unselected and data within the
         * roi becomes new selection.
         *
         * @param roi region of interest
         * @param shift shift pressed
         * @param alt alt pressed
         */
        private void pickWithRoi(RoiPicker roi, boolean shift, boolean alt) {

            if (!shift && !alt) {
                for (Particle particle : data.getParticles()) {
                    particle.setPicked(false);
                }
            }

            try {
                List<Particle> inROI = roi.inside(data.getParticles(), at.createInverse());
                for (Particle particle : inROI) {
                    if (alt) {
                        particle.setPicked(false);
                    } else {
                        particle.setPicked(true);
                    }
                }
            } catch (NoninvertibleTransformException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

        /**
         * Transformes window point to image space.
         *
         * @param point
         * @return
         */
        private Point2D toImageSpace(Point point) {
            AffineTransform inverseAt = null;
            try {
                inverseAt = at.createInverse();
                return inverseAt.transform(
                        new Point2D.Double(point.x, point.y),
                        new Point2D.Double());
            } catch (NoninvertibleTransformException ex) {
                return null;
            }
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                // cancel picking or particle adding
                cancel();
            } else if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                // delete particles
                // TODO: User confirmation?
                data.deleteSelected();
                repaint();
            }
        }

        /**
         * Cancels mouse interaction.
         */
        private void cancel() {
            addingParticle = false;
            pickingWithRoi = false;
            repaint();
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }

        /**
         * Mouse adapter for ImagePanel. Handles mouse user interaction.
         */
        private final MouseInputAdapter mAdapter = new MouseInputAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                setFocusable(true); // allow panel listen to key events
                requestFocusInWindow();

                if (SwingUtilities.isLeftMouseButton(e)) {
                    pickWithClick(e.getPoint(), epsilon, e.isShiftDown());
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {

                setFocusable(true); // allow panel listen to key events
                requestFocusInWindow();

                if (SwingUtilities.isRightMouseButton(e)) {
                    addingSrcPoint = e.getPoint();
                    addingParticle = true;
                    repaint();
                } else if (SwingUtilities.isLeftMouseButton(e)) {
                    pickingWithRoi = true;
                    roi = new RoiPicker(e.getPoint());
                    repaint();
                }
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                if (addingParticle) {
                    addingDstPoint = e.getPoint();
                    repaint();
                }

                if (pickingWithRoi) {
                    roi.update(e.getPoint());
                    repaint();
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (addingParticle && addingDstPoint != null) {
                    double r = addingDstPoint.distance(addingSrcPoint.x, addingSrcPoint.y);
                    if (r >= scale * minCircle) {
                        Point2D point = toImageSpace(addingSrcPoint);
                        Particle newParticle = particleCreator.createParticle(
                                data.getDetectionCount(),
                                point.getX(), point.getY(), r);
                        data.addParticle(newParticle);
                    }
                    addingDstPoint = null;
                }

                if (pickingWithRoi && roi != null) {
                    pickWithRoi(roi, e.isShiftDown(), e.isAltDown());
                }

                pickingWithRoi = false;
                addingParticle = false;
                addingSrcPoint = null;
                roi = null;
                repaint();
            }

        };
    }
}


text:
const cheerio = require('cheerio')

function replaceAll(string, find, replace){
  return string.replace(new RegExp(find, 'g'), replace)
}

module.exports = (html) => {
  let food, foodName
  const data = {}
  const $ = cheerio.load(html)
  const $dataTable = $('table')
  if ($dataTable.length ) {
     const rows = $dataTable.find('tr')
     rows.each((index, row)=>{
       const columns = $(row).find('td')
       // GI rows have a numeric second column
       const firstColumn = $(columns[0]).text()
       const secondColumn = $(columns[1]).text()
       if (!isNaN(parseInt(secondColumn, 10))) {
         // remove asterisk and trim food text
         foodName = firstColumn.replace(/\*/g, '').trim()
         if (foodName){
           food = {
             'id' : 'optimalfoods-'+foodName.trim().replace(/\s+/g, '-').toLowerCase(),
             'name' : foodName.trim(),
             'gi' : secondColumn
           }
           if (!data[food.id]){
             data[food.id] = food
           }
         }
       }
     })
  }
  return data
}


text:
using System;
using System.Collections.Generic;
using Apache.NMS;
using Positron.Services.Mensageria.Interfaces.Factory;
using Positron.Services.Mensageria.Interfaces.Observer;
using Positron.Services.Mensageria.Model.Positions;

namespace Positron.Services.Mensageria.Observer
{
    class PositionHandler : IObservable<Position>, IPositionHandler
    {
        private readonly IPositionFactory _positionFactory;
        private readonly List<IObserver<Position>> _observers;

        public PositionHandler(IPositionFactory positionFactory)
        {
            this._observers = new List<IObserver<Position>>();
            this._positionFactory = positionFactory;
        }

        public IDisposable Subscribe(IObserver<Position> observer)
        {
            // Check whether observer is already registered. If not, add it
            if (!this._observers.Contains(observer))
            {
                this._observers.Add(observer);
            }
            return new Unsubscriber<Position>(this._observers, observer);
        }

        public void NewPosition(IMessage message)
        {
            var posicao = _positionFactory.Obter(message);
            this.Notify(posicao);
        }

        private void Notify(Position posicao)
        {
            foreach (var observer in _observers)
            {
                observer.OnNext(posicao);
            }
        }

    }
}


text:
module Dapp
  module Kube
    module Dapp
      module Command
        module Dismiss
          def kube_dismiss
            lock_helm_release do
              kube_check_helm!
              kube_check_helm_release!
              log_process("Delete release #{kube_release_name}") do
                shellout! "helm delete #{kube_release_name} --purge"
                kubernetes.delete_namespace!(kube_namespace) if options[:with_namespace]
              end
            end
          end

          def kube_check_helm_release!
            pr = shellout("helm list | grep #{kube_release_name}")
            raise ::Dapp::Error::Command, code: :helm_release_not_exist, data: { name: kube_release_name } if pr.status == 1 || pr.stdout.empty?
          end
        end
      end
    end
  end
end


text:
package fr.insee.rmes.config;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class DDIItemRepositoryImplCondition implements Condition {

	private String ddiItemRepositoryImpl;

	private static final Logger logger = LogManager.getLogger(DDIItemRepositoryImplCondition.class);

	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

		try {
			Properties props = getEnvironmentProperties();
			ddiItemRepositoryImpl = props.getProperty("fr.insee.rmes.search.DDIItemRepository.impl");
		} catch (IOException e) {
			logger.debug("context",e);
		}
		return ddiItemRepositoryImpl.equals("DDIItemRepositoryImpl");
	}

	private Properties getEnvironmentProperties() throws IOException {
		Properties props = new Properties();
		String env = System.getProperty("fr.insee.rmes.env");
		if (null == env) {
			env = "dv";
		}
		String propsPath = String.format("env/%s/ddi-access-services.properties", env);
		props.load(getClass().getClassLoader().getResourceAsStream(propsPath));
		File f = new File(
				String.format("%s/webapps/%s", System.getProperty("catalina.base"), "ddi-access-services.properties"));
		if (f.exists() && !f.isDirectory()) {
			try (FileReader r = new FileReader(f)){
				props.load(r);
			}
		}
		File f2 = new File(
				String.format("%s/webapps/%s", System.getProperty("catalina.base"), "ddi-access-services.properties"));
		if (f2.exists() && !f2.isDirectory()) {
			try(FileReader r2 = new FileReader(f2)){
				props.load(r2);
			}
		}
		return props;
	}

}


text:
package xun.test;

import gprom.gui.DBConnection;

import java.sql.ResultSet;
import java.sql.SQLException;

public class test {

	public static void main(String[] args) throws SQLException {
		// TODO Auto-generated method stub
		ResultSet sets= DBConnection.getData();
		System.out.println(sets.getRow());
		while(sets.next()){
//			System.out.println(sets.g)
			System.out.println(sets.getString(sets.findColumn("DBUSERNAME")));
		}

	}

}


text:
layout: post
title: 'HW Checker: R, AppScripts, & Google Forms'
tags: [R, googleformr, appscripts]
---

![](/images/appscripts_r.png)

googleformr

For the past few months I've been toying with the idea of using googleformr to empower data science-oriented instructors to use data science in their workflow. In this 2-part series of posts, I'll show how to AppScripts and R to turn Google Forms into a homework checker.

I was encouraged along this path by Martin Hawksey's post  on AppScripts and R as well as by his direct help in considering some email triggering options with AppScripts.

## Toy example

The most basic example I thought worth sharing was an app that had the following:

- some security (in the form of a password),
- an email to direct feedback to and to confirm student identity, and
- a place to push homework submissions to.

With these 3 inputs you can pretty much insure that only your students can use this form, so that keeps out spam and the such.

#### Password

Google Forms provides some rather nifty data validation tools that are specific to each data type. I used short answer for my password data type, and I leverage the data validation as password validation. In the toy example below, I just used `aaa` as the required password. You can add these elements to a form item by clicking on the triple dot settings option at bottom right of item space.

![](/images/hwchecker_pwd_regex.png)

While this password validation will work if you are directly inputing answers by hand into the web form directly, it won't work with googleformr because googleformr bypasses the form elements and posts directly to the input node in the form. Still it is going to be helpful in keeping out people who aren't your students, austensibly the only ones with the password. But to be extra careful, you may want to create your own homework function that has password validation directly, as seen below.

    homework_submit <- function(pwd=NULL, email=NULL, answer){
      try(if(is.null(pwd)) stop("Please enter a password."))
      if(pwd!="aaa") stop("That is not the correct password.")
      ....
    }

I don't wrap the password test in `try` because when it errors it gives the password condition in the error message.

#### Email

I suppose I could have done some fancy email validation in Google Forms, but if I really wanted that, I'd just create a function for submitting homework that gave me more control over email validation at the source. If you'd like to do that, the email validator would look like so:

    is_email <- function(x) {
      grepl("([_+a-z0-9-]+(\\.[_+a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,14}))"
        , x, ignore.case = TRUE)
    }

You could also make it have special school email flavors by changing the `school` suboption to whatever your school email is after `@` sign.

    is_school_email <- function(x, school=NULL) {
      if (is.null(school)){
        is_email(x)
      } else {
        grepl(paste0("([_+a-z0-9-]+(\\.[_+a-z0-9-]+)*@",school,")")
                , x, ignore.case = TRUE)
      }
    }

So the end product could look like this:

    homework_submit <- function(pwd=NULL, email=NULL, answer){
      try(if(is.null(pwd)) stop("Please use class password."))
      if(pwd!="aaa") stop("That is not the correct password.")
      try(if(!is_email(email)) stop("Please use real email address."))
      ....
    }

But the other reason I don't do this is that I want students to give me a specific email that I can associate with their identity for recordkeeping and grading. This would need to be collected independently from this form.

In the back end of Google Forms, I have an AppScript that handles email identity checking. If the email is one that my student has registered with me, then it proceeds with checking the value of #1 against my tests. If it isn't, it automatically emails the student, informing her that she'll need to resubmit the homework and reminding them to use the email address they've registered with me.

After you've created your form to collect the homework answers you want from your students, you can use **googleformr** to build your function to allow students to programmatically submit their answers directly to your google form. This code chunk below serves as a template.

    library(googleformr)
    url <- "your_google_form_url"

Using the `get_form_str` function you can confirm that the structure of the form is the structure of the input entry nodes you get back from googleformr.

    get_form_str(url)

        	Order your post content
    	according to the Questions on Form
         entry.qs  entry.ids
    [1,] "pwd *"   "entry.1089329191"
    [2,] "Email *" "entry.2028747629"
    [3,] "#1 *"    "entry.1639114256"

Once you are satisfied, you can create the function hwchecker with `googleformr::gformr` handling all the linking and function construction. The resulting function will expect a vector of inputs in the same order as `get_form_str` displayed.

    hwchecker <- gformr(url, custom_reply="HW being checked!")
    hwchecker(c("aaa","not a real email@some_email_provider.com","yes"))

My last post explored the details of posting multiple answers to a google form with googleformr. The main thing I re-emphasize here is that functions created with gformr expect a vector of answers as long as and in the same order as the form entries.

#### Answer #1

In this one example, I've simply put `yes` as an answer, the correct answer in this case. However, I've shown in my previous post on googleformr that you can put almost anything into a  form item of the data type short answer, including a dataframe. And the chosen form of feedback I offer in this toy example is that if the student posts an answer other than `yes`, namely `no`, then they're told their answer is `too low` in the spirit of `TRUE=1` and `FALSE=0`.

The possibility of feedback is as flexible as the person developing the app is at writing tests. Even though AppScripts is an extension of JavaScript, the loop and conditional logic structures they use are quite familiar to R developers with any experience.

#### Make your hwsubmit function

So now, your custom `hwsubmit` function has password protection, email validation, and a direct link to your google form. We can even throw in a verification that they didn't forget to include their answers.

Now to create `hwsubmit`, simply create all the prereqs above and then change the `NULL` values on the suboptions `pswd` and `school` in the function below to set the password and school-email specific parameters for your needs. It will return a function that has all the parameters set.

    hwsubmit <- function(pswd = NULL,school=NULL){
      try(if(is.null) stop("Assign the school email suffix."))

      function(pwd=NULL, email=NULL , answer=NULL, school=NULL){
        # error handling
        try(if(is.null(pwd)) stop("Please use class password."))
        if(pwd!=pswd) stop("That is not the correct password.")
        if(!is_school_email(email,school)) stop("Please use school email."))
        try(if(is.null(answer)) stop("Don't forget to include your answers."))

        if (!is.null(pwd) & pwd==pswd &
            is_school_email(email,school) & !is.null(answer)){
          hwchecker(c(pwd, email,answer))
        } else {
          message("Check your inputs to homework_submit")
        }
      }
    }

When this function is saved into a package and distributed to your students, they will be able to submit their homework as easily as

    hwsubmit(pwd    = "aaa"
           , email  = "not a real email@some_email_provider.com"
           , answer = "yes")

Notice that with `hwsubmit`, each part has its own parameter for checking, and then is concantenated into a vector inside `hwchecker`. Of course, if you have multiple answers to submit, you will need to put them in order and wrap them up in `c()` as a vector.

## Wrap Up and Pt.2

In the next post, I'll detail some of the AppScript choices that I made, which are easily extensible. I personally found using AppScripts to be an interesting opportunity to do some practical javascript work without having to build all the website stuff.

Some of the options related to setting event triggers do take some thought, but there are good examples to follow -- hopefully, mine included.

Using AppScripts, the possibilities of how to use Google Apps to do some many tasks is quite impressive. All the more so because it is free.

Tweetgoogleformr


text:
.. _tutorial-dbcon:

Step 3: Database Connections
----------------------------

We have created a function for establishing a database connection with
`connect_db`, but by itself, that's not particularly useful.  Creating and
closing database connections all the time is very inefficient, so we want
to keep it around for longer.  Because database connections encapsulate a
transaction, we also need to make sure that only one request at the time
uses the connection. How can we elegantly do that with Flask?

This is where the application context comes into play, so let's start
there.

Flask provides us with two contexts: the application context and the
request context.  For the time being, all you have to know is that there
are special variables that use these.  For instance, the
:data:`~flask.request` variable is the request object associated with
the current request, whereas :data:`~flask.g` is a general purpose
variable associated with the current application context.  We will go into
the details of this a bit later.

For the time being, all you have to know is that you can store information
safely on the :data:`~flask.g` object.

So when do you put it on there?  To do that you can make a helper
function.  The first time the function is called, it will create a database
connection for the current context, and successive calls will return the
already established connection::

    def get_db():
        """Opens a new database connection if there is none yet for the
        current application context.
        """
        if not hasattr(g, 'sqlite_db'):
            g.sqlite_db = connect_db()
        return g.sqlite_db

So now we know how to connect, but how do we properly disconnect?  For
that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`
decorator.  It's executed every time the application context tears down::

    @app.teardown_appcontext
    def close_db(error):
        """Closes the database again at the end of the request."""
        if hasattr(g, 'sqlite_db'):
            g.sqlite_db.close()

Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called
every time the app context tears down.  What does this mean?
Essentially, the app context is created before the request comes in and is
destroyed (torn down) whenever the request finishes.  A teardown can
happen because of two reasons: either everything went well (the error
parameter will be ``None``) or an exception happened, in which case the error
is passed to the teardown function.

Curious about what these contexts mean?  Have a look at the
:ref:`app-context` documentation to learn more.

Continue to :ref:`tutorial-dbinit`.

.. hint:: Where do I put this code?

   If you've been following along in this tutorial, you might be wondering
   where to put the code from this step and the next.  A logical place is to
   group these module-level functions together, and put your new
   ``get_db`` and ``close_db`` functions below your existing
   ``connect_db`` function (following the tutorial line-by-line).

   If you need a moment to find your bearings, take a look at how the `example
   source`_ is organized.  In Flask, you can put all of your application code
   into a single Python module.  You don't have to, and if your app :ref:`grows
   larger <larger-applications>`, it's a good idea not to.

.. _example source:
   https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/


text:
DROP TABLE IF EXISTS pcd_fix;
CREATE TABLE pcd_fix AS
	SELECT old_pcd, new_pcd, distance_meters, distance_degrees
	FROM

		(SELECT pcd AS old_pcd, geom
		FROM ons_pd
		WHERE doterm IS NOT NULL
		LIMIT 1000) AS a,

		LATERAL (SELECT pcd AS new_pcd, ST_Distance_Sphere(a.geom, geom) AS distance_meters, ST_Distance(a.geom, geom) AS distance_degrees
		FROM ons_pd
		WHERE
			doterm IS NULL AND
			-- Note that the ST_DWithin condition below is fundamental to run
			-- the query in an acceptable time. The 0.2 degrees below was
			-- determined experimentally using the first 10,000 retired
			-- postcodes as a sample. The query could successfully find a
			-- match for each of the 10,000.
			-- A smaller radius, e.g. 0.1, fails on 0.3% of the sample.
			-- The longest distance found thus far is about 0.151 degrees
			-- (~6 miles).
			ST_DWithin(a.geom, geom, 0.2)
		ORDER BY distance_meters ASC
		LIMIT 1) AS b;


text:
#pragma once
#include <aws/cognito-idp/CognitoIdentityProvider_EXPORTS.h>
#include <aws/cognito-idp/CognitoIdentityProviderRequest.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/cognito-idp/model/AttributeType.h>
#include <utility>

namespace Aws
{
namespace CognitoIdentityProvider
{
namespace Model
{

  /**
   *
Represents the request to update user attributes.

See Also:

   * AWS
   * API Reference

   */
  class AWS_COGNITOIDENTITYPROVIDER_API UpdateUserAttributesRequest : public CognitoIdentityProviderRequest
  {
  public:
    UpdateUserAttributesRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateUserAttributes"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
An array of name-value pairs representing user attributes.

For custom
     * attributes, you must prepend the custom: prefix to the attribute
     * name.

If you have set an attribute to require verification before Amazon
     * Cognito updates its value, this request doesn't immediately update the value of
     * that attribute. After your user receives and responds to a verification message
     * to verify the new value, Amazon Cognito updates the attribute value. Your user
     * can sign in and receive messages with the original attribute value until they
     * verify the new value.

     */
    inline const Aws::Vector<AttributeType>& GetUserAttributes() const{ return m_userAttributes; }

    /**
     *
An array of name-value pairs representing user attributes.

For custom
     * attributes, you must prepend the custom: prefix to the attribute
     * name.

If you have set an attribute to require verification before Amazon
     * Cognito updates its value, this request doesn't immediately update the value of
     * that attribute. After your user receives and responds to a verification message
     * to verify the new value, Amazon Cognito updates the attribute value. Your user
     * can sign in and receive messages with the original attribute value until they
     * verify the new value.

     */
    inline bool UserAttributesHasBeenSet() const { return m_userAttributesHasBeenSet; }

    /**
     *
An array of name-value pairs representing user attributes.

For custom
     * attributes, you must prepend the custom: prefix to the attribute
     * name.

If you have set an attribute to require verification before Amazon
     * Cognito updates its value, this request doesn't immediately update the value of
     * that attribute. After your user receives and responds to a verification message
     * to verify the new value, Amazon Cognito updates the attribute value. Your user
     * can sign in and receive messages with the original attribute value until they
     * verify the new value.

     */
    inline void SetUserAttributes(const Aws::Vector<AttributeType>& value) { m_userAttributesHasBeenSet = true; m_userAttributes = value; }

    /**
     *
An array of name-value pairs representing user attributes.

For custom
     * attributes, you must prepend the custom: prefix to the attribute
     * name.

If you have set an attribute to require verification before Amazon
     * Cognito updates its value, this request doesn't immediately update the value of
     * that attribute. After your user receives and responds to a verification message
     * to verify the new value, Amazon Cognito updates the attribute value. Your user
     * can sign in and receive messages with the original attribute value until they
     * verify the new value.

     */
    inline void SetUserAttributes(Aws::Vector<AttributeType>&& value) { m_userAttributesHasBeenSet = true; m_userAttributes = std::move(value); }

    /**
     *
An array of name-value pairs representing user attributes.

For custom
     * attributes, you must prepend the custom: prefix to the attribute
     * name.

If you have set an attribute to require verification before Amazon
     * Cognito updates its value, this request doesn't immediately update the value of
     * that attribute. After your user receives and responds to a verification message
     * to verify the new value, Amazon Cognito updates the attribute value. Your user
     * can sign in and receive messages with the original attribute value until they
     * verify the new value.

     */
    inline UpdateUserAttributesRequest& WithUserAttributes(const Aws::Vector<AttributeType>& value) { SetUserAttributes(value); return *this;}

    /**
     *
An array of name-value pairs representing user attributes.

For custom
     * attributes, you must prepend the custom: prefix to the attribute
     * name.

If you have set an attribute to require verification before Amazon
     * Cognito updates its value, this request doesn't immediately update the value of
     * that attribute. After your user receives and responds to a verification message
     * to verify the new value, Amazon Cognito updates the attribute value. Your user
     * can sign in and receive messages with the original attribute value until they
     * verify the new value.

     */
    inline UpdateUserAttributesRequest& WithUserAttributes(Aws::Vector<AttributeType>&& value) { SetUserAttributes(std::move(value)); return *this;}

    /**
     *
An array of name-value pairs representing user attributes.

For custom
     * attributes, you must prepend the custom: prefix to the attribute
     * name.

If you have set an attribute to require verification before Amazon
     * Cognito updates its value, this request doesn't immediately update the value of
     * that attribute. After your user receives and responds to a verification message
     * to verify the new value, Amazon Cognito updates the attribute value. Your user
     * can sign in and receive messages with the original attribute value until they
     * verify the new value.

     */
    inline UpdateUserAttributesRequest& AddUserAttributes(const AttributeType& value) { m_userAttributesHasBeenSet = true; m_userAttributes.push_back(value); return *this; }

    /**
     *
An array of name-value pairs representing user attributes.

For custom
     * attributes, you must prepend the custom: prefix to the attribute
     * name.

If you have set an attribute to require verification before Amazon
     * Cognito updates its value, this request doesn't immediately update the value of
     * that attribute. After your user receives and responds to a verification message
     * to verify the new value, Amazon Cognito updates the attribute value. Your user
     * can sign in and receive messages with the original attribute value until they
     * verify the new value.

     */
    inline UpdateUserAttributesRequest& AddUserAttributes(AttributeType&& value) { m_userAttributesHasBeenSet = true; m_userAttributes.push_back(std::move(value)); return *this; }

    /**
     *
A valid access token that Amazon Cognito issued to the user whose user
     * attributes you want to update.

     */
    inline const Aws::String& GetAccessToken() const{ return m_accessToken; }

    /**
     *
A valid access token that Amazon Cognito issued to the user whose user
     * attributes you want to update.

     */
    inline bool AccessTokenHasBeenSet() const { return m_accessTokenHasBeenSet; }

    /**
     *
A valid access token that Amazon Cognito issued to the user whose user
     * attributes you want to update.

     */
    inline void SetAccessToken(const Aws::String& value) { m_accessTokenHasBeenSet = true; m_accessToken = value; }

    /**
     *
A valid access token that Amazon Cognito issued to the user whose user
     * attributes you want to update.

     */
    inline void SetAccessToken(Aws::String&& value) { m_accessTokenHasBeenSet = true; m_accessToken = std::move(value); }

    /**
     *
A valid access token that Amazon Cognito issued to the user whose user
     * attributes you want to update.

     */
    inline void SetAccessToken(const char* value) { m_accessTokenHasBeenSet = true; m_accessToken.assign(value); }

    /**
     *
A valid access token that Amazon Cognito issued to the user whose user
     * attributes you want to update.

     */
    inline UpdateUserAttributesRequest& WithAccessToken(const Aws::String& value) { SetAccessToken(value); return *this;}

    /**
     *
A valid access token that Amazon Cognito issued to the user whose user
     * attributes you want to update.

     */
    inline UpdateUserAttributesRequest& WithAccessToken(Aws::String&& value) { SetAccessToken(std::move(value)); return *this;}

    /**
     *
A valid access token that Amazon Cognito issued to the user whose user
     * attributes you want to update.

     */
    inline UpdateUserAttributesRequest& WithAccessToken(const char* value) { SetAccessToken(value); return *this;}

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline const Aws::Map<Aws::String, Aws::String>& GetClientMetadata() const{ return m_clientMetadata; }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline bool ClientMetadataHasBeenSet() const { return m_clientMetadataHasBeenSet; }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline void SetClientMetadata(const Aws::Map<Aws::String, Aws::String>& value) { m_clientMetadataHasBeenSet = true; m_clientMetadata = value; }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline void SetClientMetadata(Aws::Map<Aws::String, Aws::String>&& value) { m_clientMetadataHasBeenSet = true; m_clientMetadata = std::move(value); }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline UpdateUserAttributesRequest& WithClientMetadata(const Aws::Map<Aws::String, Aws::String>& value) { SetClientMetadata(value); return *this;}

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline UpdateUserAttributesRequest& WithClientMetadata(Aws::Map<Aws::String, Aws::String>&& value) { SetClientMetadata(std::move(value)); return *this;}

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline UpdateUserAttributesRequest& AddClientMetadata(const Aws::String& key, const Aws::String& value) { m_clientMetadataHasBeenSet = true; m_clientMetadata.emplace(key, value); return *this; }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline UpdateUserAttributesRequest& AddClientMetadata(Aws::String&& key, const Aws::String& value) { m_clientMetadataHasBeenSet = true; m_clientMetadata.emplace(std::move(key), value); return *this; }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline UpdateUserAttributesRequest& AddClientMetadata(const Aws::String& key, Aws::String&& value) { m_clientMetadataHasBeenSet = true; m_clientMetadata.emplace(key, std::move(value)); return *this; }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline UpdateUserAttributesRequest& AddClientMetadata(Aws::String&& key, Aws::String&& value) { m_clientMetadataHasBeenSet = true; m_clientMetadata.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline UpdateUserAttributesRequest& AddClientMetadata(const char* key, Aws::String&& value) { m_clientMetadataHasBeenSet = true; m_clientMetadata.emplace(key, std::move(value)); return *this; }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline UpdateUserAttributesRequest& AddClientMetadata(Aws::String&& key, const char* value) { m_clientMetadataHasBeenSet = true; m_clientMetadata.emplace(std::move(key), value); return *this; }

    /**
     *
A map of custom key-value pairs that you can provide as input for any custom
     * workflows that this action initiates.

You create custom workflows by
     * assigning Lambda functions to user pool triggers. When you use the
     * UpdateUserAttributes API action, Amazon Cognito invokes the function that is
     * assigned to the custom message trigger. When Amazon Cognito invokes this
     * function, it passes a JSON payload, which the function receives as input. This
     * payload contains a clientMetadata attribute, which provides the
     * data that you assigned to the ClientMetadata parameter in your
     * UpdateUserAttributes request. In your function code in Lambda, you can process
     * the clientMetadata value to enhance your workflow for your specific
     * needs.

For more information, see
     * Customizing user pool Workflows with Lambda Triggers in the Amazon
     * Cognito Developer Guide.

When you use the ClientMetadata
     * parameter, remember that Amazon Cognito won't do the following:

     *
Store the ClientMetadata value. This data is available only to Lambda
     * triggers that are assigned to a user pool to support custom workflows. If your
     * user pool configuration doesn't include triggers, the ClientMetadata parameter
     * serves no purpose.

Validate the ClientMetadata value.

     *

Encrypt the ClientMetadata value. Don't use Amazon Cognito to
     * provide sensitive information.

     */
    inline UpdateUserAttributesRequest& AddClientMetadata(const char* key, const char* value) { m_clientMetadataHasBeenSet = true; m_clientMetadata.emplace(key, value); return *this; }

  private:

    Aws::Vector<AttributeType> m_userAttributes;
    bool m_userAttributesHasBeenSet;

    Aws::String m_accessToken;
    bool m_accessTokenHasBeenSet;

    Aws::Map<Aws::String, Aws::String> m_clientMetadata;
    bool m_clientMetadataHasBeenSet;
  };

} // namespace Model
} // namespace CognitoIdentityProvider
} // namespace Aws


text:
import os
import unittest

from conans.test.utils.tools import TestClient

class UserChannelTestPackage(unittest.TestCase):

    def test(self):
        # https://github.com/conan-io/conan/issues/2501
        client = TestClient()
        conanfile = """from conans import ConanFile
class SayConan(ConanFile):
    pass
"""
        test = """from conans import ConanFile
class SayConan(ConanFile):
    def requirements(self):
        self.output.info("USER: %s!!" % self.user)
        self.output.info("CHANNEL: %s!!" % self.channel)

    def test(self):
        pass
"""

        client.save({"conanfile.py": conanfile,
                     "test_package/conanfile.py": test})
        client.run("create . Pkg/0.1@conan/testing")
        self.assertIn("Pkg/0.1@conan/testing (test package): USER: conan!!", client.out)
        self.assertIn("Pkg/0.1@conan/testing (test package): CHANNEL: testing!!", client.out)

class SameUserChannelTest(unittest.TestCase):

    def setUp(self):
        self.client = TestClient()
        conanfile = """
from conans import ConanFile

class SayConan(ConanFile):
    name = "Say"
    version = "0.1"
    build_policy = "missing"

    def build(self):
        self.output.info("Building %s")
"""
        for channel in ("lasote/stable", "other/testing"):
            self.client.save({"conanfile.py": conanfile % channel})
            self.client.run("export . %s" % channel)

        self.conanfile = """
from conans import ConanFile

class HelloConan(ConanFile):
    name = "Hello"
    version = "0.1"
    build_policy = "missing"

    def requirements(self):
        self.requires("Say/0.1@%s/%s" % (self.user, self.channel))

    def build(self):
        self.output.info("Building %s/%s" % (self.user, self.channel) )
"""

        self.test_conanfile = """
from conans import ConanFile, CMake
import os

class HelloReuseConan(ConanFile):
    requires = "Hello/0.1@lasote/stable"

    def test(self):
        pass
"""
        self.client.save({"conanfile.py": self.conanfile,
                          "test/conanfile.py": self.test_conanfile})

    def test_create(self):
        self.client.run("create . lasote/stable")
        self.assertIn("Say/0.1@lasote/stable: Building lasote/stable", self.client.user_io.out)
        self.assertIn("Hello/0.1@lasote/stable: Building lasote/stable", self.client.user_io.out)
        self.assertNotIn("other/testing", self.client.user_io.out)

        self.client.save({"conanfile.py": self.conanfile,
                          "test/conanfile.py": self.test_conanfile.replace("lasote/stable",
                                                                           "other/testing")})
        self.client.run("create . other/testing")
        self.assertIn("Say/0.1@other/testing: Building other/testing", self.client.user_io.out)
        self.assertIn("Hello/0.1@other/testing: Building other/testing", self.client.user_io.out)
        self.assertNotIn("lasote/stable", self.client.user_io.out)

    def test_local_commands(self):
        self.client.run("install .", assert_error=True)
        self.assertIn("ERROR: conanfile.py (Hello/0.1@None/None): "
                      "Error in requirements() method, line 10", self.client.out)
        self.assertIn("ConanException: CONAN_USERNAME environment "
                      "variable not defined, but self.user is used", self.client.out)

        os.environ["CONAN_USERNAME"] = "lasote"
        self.client.run("install .", assert_error=True)
        self.assertIn("ERROR: conanfile.py (Hello/0.1@None/None): "
                      "Error in requirements() method, line 10", self.client.out)
        self.assertIn("ConanException: CONAN_CHANNEL environment "
                      "variable not defined, but self.channel is used", self.client.out)

        os.environ["CONAN_CHANNEL"] = "stable"
        self.client.run("install .")
        self.assertIn("Say/0.1@lasote/stable: Building lasote/stable", self.client.user_io.out)
        self.assertNotIn("other/testing", self.client.user_io.out)

        os.environ["CONAN_USERNAME"] = "other"
        os.environ["CONAN_CHANNEL"] = "testing"
        self.client.run("install .")
        self.assertIn("Say/0.1@other/testing: Building other/testing", self.client.user_io.out)
        self.assertNotIn("lasote/stable", self.client.user_io.out)

        del os.environ["CONAN_USERNAME"]
        del os.environ["CONAN_CHANNEL"]

        # Now use the default_ methods to declare user and channel
        self.client = TestClient()
        conanfile = """
from conans import ConanFile

class SayConan(ConanFile):
    name = "Say"
    version = "0.1"
    build_policy = "missing"
    default_user = "userfoo"

    def build(self):
        self.output.info("Building %s/%s" % (self.user, self.channel) )

    @property
    def default_channel(self):
        return "channelbar"
"""
        self.client.save({"conanfile.py": conanfile})
        self.client.run("install .")
        self.client.run("build .")
        self.assertIn("Building userfoo/channelbar", self.client.out)

class BuildRequireUserChannelTest(unittest.TestCase):
    def test(self):
        # https://github.com/conan-io/conan/issues/2254
        client = TestClient()
        conanfile = """
from conans import ConanFile

class SayConan(ConanFile):
    def build_requirements(self):
        self.output.info("MYUSER: %s" % self.user)
        self.output.info("MYCHANNEL: %s" % self.channel)
"""
        client.save({"conanfile.py": conanfile})
        client.run("install . -e CONAN_USERNAME=myuser -e CONAN_CHANNEL=mychannel")
        self.assertIn("MYUSER: myuser", client.out)
        self.assertIn("MYCHANNEL: mychannel", client.out)

    def test_profile(self):
        # https://github.com/conan-io/conan/issues/2254
        client = TestClient()
        conanfile = """
from conans import ConanFile

class SayConan(ConanFile):
    def build_requirements(self):
        self.output.info("MYUSER: %s" % self.user)
        self.output.info("MYCHANNEL: %s" % self.channel)
"""
        myprofile = """[env]
CONAN_USERNAME=myuser
CONAN_CHANNEL=mychannel
"""
        client.save({"conanfile.py": conanfile,
                     "myprofile": myprofile})
        client.run("install . -pr=myprofile")
        self.assertIn("MYUSER: myuser", client.out)
        self.assertIn("MYCHANNEL: mychannel", client.out)


text:
package com.cloudera.flume.handlers.debug;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.cloudera.flume.conf.Context;
import com.cloudera.flume.conf.SinkFactory.SinkDecoBuilder;
import com.cloudera.flume.core.Event;
import com.cloudera.flume.core.EventSink;
import com.cloudera.flume.core.EventSinkDecorator;
import com.google.common.base.Preconditions;

/**
 * This is for throughput tests. Here we put a series of events into memory then
 * them flush them when close is called.
 *
 * This is similar to MemorySinkSource in functionality but is easier to
 * integrate with the initial single connector per process implementation.
 */
public class InMemoryDecorator<S extends EventSink> extends
    EventSinkDecorator<S> {

  List<Event> evts = new ArrayList<Event>();

  public InMemoryDecorator(S s) {
    super(s);
  }

  @Override
  public void append(Event e) throws IOException {
    evts.add(e);
  }

  public List<Event> getEvents() {
    return Collections.unmodifiableList(evts);
  }

  @Override
  public void close() throws IOException {
    for (Event e : evts) {
      getSink().append(e);
    }

    evts = null;
    super.close();
  }

  public static SinkDecoBuilder builder() {
    return new SinkDecoBuilder() {
      @Override
      public EventSinkDecorator<EventSink> build(Context context,
          String... argv) {
        Preconditions.checkArgument(argv.length == 0, "usage: inmem");
        return new InMemoryDecorator<EventSink>(null);
      }

    };
  }

}


text:
namespace cv
{

using std::vector;

class ChessBoardGenerator
{
public:
    double sensorWidth;
    double sensorHeight;
    size_t squareEdgePointsNum;
    double min_cos;
    mutable double cov;
    Size patternSize;
    int rendererResolutionMultiplier;

    ChessBoardGenerator(const Size& patternSize = Size(8, 6));
    Mat operator()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, std::vector<Point2f>& corners) const;
    Mat operator()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, const Size2f& squareSize, std::vector<Point2f>& corners) const;
    Mat operator()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, const Size2f& squareSize, const Point3f& pos, std::vector<Point2f>& corners) const;
    Size cornersSize() const;

    mutable std::vector<Point3f> corners3d;
private:
    void generateEdge(const Point3f& p1, const Point3f& p2, std::vector<Point3f>& out) const;
    Mat generateChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
        const Point3f& zero, const Point3f& pb1, const Point3f& pb2,
        float sqWidth, float sqHeight, const std::vector<Point3f>& whole, std::vector<Point2f>& corners) const;
    void generateBasis(Point3f& pb1, Point3f& pb2) const;

    Mat rvec, tvec;
};

}

#endif


text:
@interface CallingTests : KIFTestCase
@end

@implementation CallingTests

#pragma mark - Pre and Post Test Methods

- (void)beforeAll
{
    [tester initializeLoginScreen];
    [tester loginEndpoint:[KIFUITestActor generateTestEndpointID] groupName:TEST_BOT_GROUP_ID appID:nil];
}

- (void)afterAll
{
    [tester logout];
    [tester resetLoginScreen];
}

#pragma mark - UI Tests

- (void)testOutgoingAudioCall
{
    // click on table cell (testbot endpoint)
    [tester tapViewWithAccessibilityLabel:TEST_BOT_ENDPOINT_ID];

    // hit "call" bar button item
    [tester tapViewWithAccessibilityLabel:CHAT_CALL_BUTTON];

    // hit "audio only" button
    [tester tapViewWithAccessibilityLabel:CHAT_AUDIO_CALL_BUTTON];

    // wait for status indicator to disappear
    [tester waitForAbsenceOfViewWithAccessibilityLabel:CALL_VIEW_STATUS_INDICATOR];

    // hit mute button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_MUTE_AUDIO_BUTTON];

    // hit unmute button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_UNMUTE_AUDIO_BUTTON];

    // verify mute button reappears
    [tester waitForViewWithAccessibilityLabel:CALL_VIEW_MUTE_AUDIO_BUTTON];

    // hit end call button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_END_CALL_BUTTON];

    // verify we navigate back to chat view
    [tester waitForViewWithAccessibilityLabel:CHAT_MESSAGE_TEXTFIELD];

    // hit back bar button item to navigate back to group list
    [tester tapViewWithAccessibilityLabel:CHAT_BACK_BUTTON];

    // verify we navigate to group list
    [tester waitForViewWithAccessibilityLabel:GROUP_LIST_TABLE_VIEW];
}

- (void)testIncomingAudioCall
{
    // click on table cell (testbot endpoint)
    [tester tapViewWithAccessibilityLabel:TEST_BOT_ENDPOINT_ID];

    // enter "call me" message into textbox
    [tester enterText:TEST_BOT_CALL_ME_AUDIO_MESSAGE intoViewWithAccessibilityLabel:CHAT_MESSAGE_TEXTFIELD];

    // click send to request audio call
    [tester tapViewWithAccessibilityLabel:CHAT_SEND_BUTTON];

    // click answer button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_ANSWER_BUTTON];

    // wait for status indicator to disappear
    [tester waitForAbsenceOfViewWithAccessibilityLabel:CALL_VIEW_STATUS_INDICATOR];

    // hit end call button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_END_CALL_BUTTON];

    // verify we navigate back to chat view
    [tester waitForViewWithAccessibilityLabel:CHAT_MESSAGE_TEXTFIELD];

    // hit back bar button item to navigate back to group list
    [tester tapViewWithAccessibilityLabel:CHAT_BACK_BUTTON];

    // verify we navigate to group list
    [tester waitForViewWithAccessibilityLabel:GROUP_LIST_TABLE_VIEW];
}

- (void)testIncomingCallIgnore
{
    // click on table cell (testbot endpoint)
    [tester tapViewWithAccessibilityLabel:TEST_BOT_ENDPOINT_ID];

    // enter message in textbox to request audio call
    [tester enterText:TEST_BOT_CALL_ME_AUDIO_MESSAGE intoViewWithAccessibilityLabel:CHAT_MESSAGE_TEXTFIELD];

    // click send
    [tester tapViewWithAccessibilityLabel:CHAT_SEND_BUTTON];

    // click the ignore button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_IGNORE_BUTTON];

    // verify we navigate back to chat view
    [tester waitForViewWithAccessibilityLabel:CHAT_MESSAGE_TEXTFIELD];

    // hit back bar button item to navigate back to group list
    [tester tapViewWithAccessibilityLabel:CHAT_BACK_BUTTON];

    // verify we navigate to group list
    [tester waitForViewWithAccessibilityLabel:GROUP_LIST_TABLE_VIEW];
}

- (void)testOutgoingVideoCall
{
    // click on table cell (testbot endpoint)
    [tester tapViewWithAccessibilityLabel:TEST_BOT_ENDPOINT_ID];

    // hit "call" bar button item
    [tester tapViewWithAccessibilityLabel:CHAT_CALL_BUTTON];

    // hit "video call" button
    [tester tapViewWithAccessibilityLabel:CHAT_VIDEO_CALL_BUTTON];

    // wait for status indicator to disappear
    [tester waitForAbsenceOfViewWithAccessibilityLabel:CALL_VIEW_STATUS_INDICATOR];

    // verify local video view
    [tester waitForViewWithAccessibilityLabel:CALL_VIEW_LOCAL_VIDEO_VIEW];

    // verify remote video view
    [tester waitForViewWithAccessibilityLabel:CALL_VIEW_REMOTE_VIDEO_VIEW];

    // hit mute audio button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_MUTE_AUDIO_BUTTON];

    // hit unmute audio button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_UNMUTE_AUDIO_BUTTON];

    // verify mute audio button reappears
    [tester waitForViewWithAccessibilityLabel:CALL_VIEW_MUTE_AUDIO_BUTTON];

    // hit "switch camera" button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_SWITCH_CAMERA_BUTTON];

    // TODO: verify camera switched?

    // hit mute video button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_MUTE_VIDEO_BUTTON];

    // verify local video view disappears
    [tester waitForAbsenceOfViewWithAccessibilityLabel:CALL_VIEW_LOCAL_VIDEO_VIEW];

    // hit unmute video button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_UNMUTE_VIDEO_BUTTON];

    // verify local video view reappears
    [tester waitForViewWithAccessibilityLabel:CALL_VIEW_LOCAL_VIDEO_VIEW];

    // hit end call button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_END_CALL_BUTTON];

    // verify we navigate back to chat view
    [tester waitForViewWithAccessibilityLabel:CHAT_MESSAGE_TEXTFIELD];

    // hit back bar button item to navigate back to group list
    [tester tapViewWithAccessibilityLabel:CHAT_BACK_BUTTON];

    // verify we navigate to group list
    [tester waitForViewWithAccessibilityLabel:GROUP_LIST_TABLE_VIEW];
}

- (void)testIncomingVideoCall
{
    // click on table cell (testbot endpoint)
    [tester tapViewWithAccessibilityLabel:TEST_BOT_ENDPOINT_ID];

    // enter "call me" message into textbox
    [tester enterText:TEST_BOT_CALL_ME_VIDEO_MESSAGE intoViewWithAccessibilityLabel:CHAT_MESSAGE_TEXTFIELD];

    // click send to request video call
    [tester tapViewWithAccessibilityLabel:CHAT_SEND_BUTTON];

    // click answer button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_ANSWER_BUTTON];

    // wait for status indicator to disappear
    [tester waitForAbsenceOfViewWithAccessibilityLabel:CALL_VIEW_STATUS_INDICATOR];

    // verify local video view
    [tester waitForViewWithAccessibilityLabel:CALL_VIEW_LOCAL_VIDEO_VIEW];

    // verify remote video view
    [tester waitForViewWithAccessibilityLabel:CALL_VIEW_REMOTE_VIDEO_VIEW];

    // hit end call button
    [tester tapViewWithAccessibilityLabel:CALL_VIEW_END_CALL_BUTTON];

    // verify we navigate back to chat view
    [tester waitForViewWithAccessibilityLabel:CHAT_MESSAGE_TEXTFIELD];

    // hit back bar button item to navigate back to group list
    [tester tapViewWithAccessibilityLabel:CHAT_BACK_BUTTON];

    // verify we navigate to group list
    [tester waitForViewWithAccessibilityLabel:GROUP_LIST_TABLE_VIEW];
}

#pragma mark - Helper Methods

@end


text:
<?xml version="1.0" encoding="utf-8"?>

<!-- Copyright (c) 2014 blinkbox Entertainment Limited. All rights reserved. -->

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%"
    android:pivotY="50%"
    android:fromDegrees="0"
    android:toDegrees="1080">

    <shape
        android:shape="ring"
        android:thicknessRatio="12"
        android:useLevel="false">

        <size
            android:width="90dip"
            android:height="90dip" />

        <gradient
            android:type="sweep"
            android:useLevel="false"
            android:startColor="@android:color/transparent"
            android:endColor="@color/hit_state_purple"
            android:angle="0" />
    </shape>
</rotate>


text:
package org.openrdf.repository.object.managers.converters;

import java.math.BigInteger;

import org.openrdf.model.Literal;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.XMLSchema;
import org.openrdf.repository.object.managers.Marshall;

/**
 * Converts BigInteger to and from Literal.
 *
 * @author James Leigh
 *
 */
public class BigIntegerMarshall implements Marshall<BigInteger> {
	private ValueFactory vf;

	private URI datatype;

	public BigIntegerMarshall(ValueFactory vf) {
		this.vf = vf;
		datatype = XMLSchema.INTEGER;
	}

	public String getJavaClassName() {
		return BigInteger.class.getName();
	}

	public URI getDatatype() {
		return datatype;
	}

	public void setDatatype(URI dt) {
		if (!dt.equals(datatype))
			throw new IllegalArgumentException(dt.toString());
	}

	public BigInteger deserialize(Literal literal) {
		return literal.integerValue();
	}

	public Literal serialize(BigInteger object) {
		// TODO add ValueFactory#createLiteral(BigInteger) method
		return vf.createLiteral(object.toString(), datatype);
	}

}


text:
package org.apache.tomcat.util.modeler;

import java.io.Serializable;

import javax.management.MBeanFeatureInfo;

/**
 *
Convenience base class for AttributeInfo and
 * OperationInfo classes that will be used to collect configuration
 * information for the ModelMBean beans exposed for management.

 *
 * @author Craig R. McClanahan
 */
public class FeatureInfo implements Serializable {
    static final long serialVersionUID = -911529176124712296L;

    protected String description = null;
    protected String name = null;
    protected MBeanFeatureInfo info = null;

    // all have type except Constructor
    protected String type = null;

    // ------------------------------------------------------------- Properties

    /**
     * @return the human-readable description of this feature.
     */
    public String getDescription() {
        return (this.description);
    }

    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * @return the name of this feature, which must be unique among features
     *  in the same collection.
     */
    public String getName() {
        return (this.name);
    }

    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the fully qualified Java class name of this element.
     */
    public String getType() {
        return (this.type);
    }

    public void setType(String type) {
        this.type = type;
    }

}


text:
using System;

namespace BLToolkit.Data.Linq
{
	public interface ISelectInsertable<TSource,TTarget>
	{
	}
}