text:
package org.auraframework.test.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.lang3.StringEscapeUtils;
import org.auraframework.util.AuraTextUtil;
import org.auraframework.util.json.JsonReader;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.google.common.base.Function;
import com.google.common.collect.Lists;

/**
 * A place to put common UI testing specific helper methods
 */

public class AuraUITestingUtil {
    private final WebDriver driver;
    private int timeoutInSecs;
    private int rerunCount = 0;
    protected static final Random RAND = new Random(System.currentTimeMillis());

    public AuraUITestingUtil(WebDriver driver) {
        this(driver, 30);
    }

    public AuraUITestingUtil(WebDriver driver, int timeoutInSecs) {
        this.driver = driver;
        setTimeoutInSecs(timeoutInSecs);
    }

    public enum ActionDuringTransit {
        DROPACTION,
        NAVIGATEBACK
        //TODO: navigate to other place
        //TODO: delay the action
    }

    public enum ActionTiming {
        PRESEND,
        POSTSEND,
        PREDECODE,
        //TODO: AFTERDECODE
    }

    public static class StressAction {
    	private String auraActionWeCare;
    	private ActionTiming actionTiming;
    	private ActionDuringTransit[] actionDuringTransit;
    	public StressAction(String auraActionWeCare, ActionTiming actionTiming, ActionDuringTransit... actionDuringTransit) {
    		this.auraActionWeCare = auraActionWeCare;
    		this.actionTiming = actionTiming;
    		this.actionDuringTransit = actionDuringTransit;
    	}
		public String getAuraActionWeCare() {
			return auraActionWeCare;
		}
		public ActionTiming getActionTiming() {
			return actionTiming;
		}
		public ActionDuringTransit[] getActionDuringTransit() {
			return actionDuringTransit;
		}
    };

    public static StressAction createStressAction(String auraActionWeCare, ActionTiming stressActionTiming, ActionDuringTransit... stressActionDuringTransitList) {
    	return new StressAction(auraActionWeCare, stressActionTiming, stressActionDuringTransitList);
    }

    public Object performStressActionsDuringTransit(StressAction stressAction) {
    	return performStressActionsDuringTransit(stressAction.getAuraActionWeCare(), stressAction.getActionTiming(), stressAction.getActionDuringTransit());
    }

    public Object performStressActionsDuringTransit(String auraActionWeCare, ActionTiming stressActionTiming, ActionDuringTransit... stressActionDuringTransitList) {
        String jsScript;
        jsScript ="var customCallback = function(actions) { "+
        		"var i;"+
        		"var action = undefined;"+
        		"for (i = 0; i < actions.length; i++) {"+
        		"if (actions[i].getDef().name === '"+ auraActionWeCare +"') {"+
        			"action = actions[i];"+
        			"break;"+
        		"}"+
        "}"+
        "if (action) {";

		for(ActionDuringTransit actionDuringTransit : stressActionDuringTransitList) {
			switch(actionDuringTransit) {
            case DROPACTION :
                jsScript+= "actions.splice(i, 1);";
                break;
            case NAVIGATEBACK :
                jsScript += "$A.historyService.back();";
                break;
            default: //do nothing
                break;
			}
        }

        //remove the callback once we are done, only do it once
        jsScript += "$A.test.removePrePostSendCallback(cb_handle);";
        jsScript += "}"+ //end of if(action)
        "};"; //end of function customCallback

        //register the custom callback
        switch(stressActionTiming) {
            case PRESEND:
                jsScript += "var cb_handle = $A.test.addPrePostSendCallback(undefined, customCallback, undefined);";
                break;
            case POSTSEND:
                jsScript += "var cb_handle = $A.test.addPrePostSendCallback(undefined, undefined, customCallback);";
                break;
            //we need different customCallback for this case PREDECODE:
            //jsScript += "var cb_handle = $A.test.addPreDecodeCallback(customCallback);";
            default:
                break;
        }

        //TODO & Note:
        //getEval will wrap jsScript in a try...catch(e), return an array of  [result, jsTestErrors, scriptExecException]
        //result is the result of executing jsScript
        //jsTestErrors = window.$A.test.getErrors() if there is any
        //scriptExecException = e.message() , e is what we catched if any
        //if jsTestErrors exist, we fail the test right away -- this is not what we want, if we are expecting some error in test
        return getEval(jsScript);
    }

    public void setTimeoutInSecs(int timeoutInSecs) {
        this.timeoutInSecs = timeoutInSecs;
        if (SauceUtil.areTestsRunningOnSauce()) {
            // things are slower in SauceLabs
            this.timeoutInSecs *= 6;
        }
    }

    public int getTimeout() {
        return timeoutInSecs;
    }

    /**
     * An internal class to wait for and retrieve an element from the driver.
     */
    private static class WaitAndRetrieve implements ExpectedCondition<Boolean> {
        private final By locator;
        private WebElement found = null;

        public WaitAndRetrieve(By locator) {
            this.locator = locator;
        }

        @Override
        public Boolean apply(WebDriver d) {
            List<WebElement> elements = d.findElements(locator);

            if (elements.size() > 0) {
                found = elements.get(0);
                return true;
            }
            return false;
        }

        public WebElement getFound() {
            return this.found;
        }

        @Override
        public String toString() {
            return "WaitAndRetrieve: " + this.locator + " found " + this.found;
        }
    }

    /**
     * Waits for element with matching locator to appear in dom.
     *
     * This will wait for at least one element with the locator to appear in the dom, and it will return the first
     * element found. If there are more than one element that match the locator, this will succeed when the first one
     * appears.
     *
     * @param msg Error message on timeout.
     * @param locator By of element waiting for.
     */
    public WebElement waitForElement(String msg, By locator) {
        WaitAndRetrieve war = new WaitAndRetrieve(locator);
        WebDriverWait wait = new WebDriverWait(driver, timeoutInSecs);
        wait.withMessage(msg);
        wait.ignoring(NoSuchElementException.class);
        wait.until(war);
        return war.getFound();
    }

    /**
     * Waits for element with matching locator to appear in dom.
     *
     * Convenience routine to supply a message.
     *
     * @param locator By of element waiting for.
     */
    public WebElement waitForElement(By locator) {
        String msg = "Element with locator \'" + locator.toString() + "\' never appeared";
        return waitForElement(msg, locator);
    }

    /**
     * Waits for element to be not present
     *
     * @param locator By of element waiting to disapear
     * @return
     */
    public boolean waitForElementNotPresent(String msg, final By locator) {
        WebDriverWait wait = new WebDriverWait(driver, timeoutInSecs);
        return wait.withMessage(msg)
                .ignoring(StaleElementReferenceException.class).until(new ExpectedCondition<Boolean>() {

                    @Override
                    public Boolean apply(WebDriver d) {
                        WebElement element = driver.findElement(locator);
                        return element == null ? true : false;
                    }
                });
    }

    public WebElement findElementAndTypeEventNameInIt(String event) {
        String locatorTemplate = "input[class*='%s']";
        String locator = String.format(locatorTemplate, event);
        WebElement input = findDomElement(By.cssSelector(locator));
        input.click(); // IE7 need to bring focus
        input.clear();
        input.sendKeys(event);
        return input;
    }

    public void assertClassNameContains(WebElement element, String namePart) {
        assertClassNameContains(element, namePart, true);
    }

    public void assertClassNameDoesNotContain(WebElement element, String namePart) {
        assertClassNameContains(element, namePart, false);
    }

    private void assertClassNameContains(WebElement element, String namePart, boolean doesContain) {
        String className = element.getAttribute("class").trim();
        className = " " + className + " "; // so we wont get false positive for
        // nonactive if looking for active
        namePart = " " + namePart + " ";

        if (doesContain) {
            Assert.assertTrue("Class name '" + className + "' does not contain '" + namePart + "'",
                    className.contains(namePart));
        } else {
            Assert.assertFalse("Class name '" + className + "' contains '" + namePart + "'",
                    className.contains(namePart));
        }
    }

    public String getValueFromRootExpr(String val) {
        String exp = "window.$A.getRoot().get('" + val + "')";
        return exp;
    }

    public String getFindAtRootExpr(String cmp) {
        String exp = "window.$A.getRoot().find('" + cmp + "')";
        return exp;
    }

    public String getEncodedContextForServer() {
        String exp = "window.$A.getContext().encodeForServer()";
        return exp;
    }

    /**
     * Very useful to get handle on the component passing globalId
     *
     * @param cmp: globalId of the component
     * @return
     */
    public String getCmpExpr(String cmp) {
        String exp = "window.$A.getCmp('" + cmp + "')";
        return exp;
    }

    /**
     * Return the javascript using which component's attribute value could be found out
     *
     * @param cmp : cmpName whose attribute you are looking for
     * @param val : attribute name
     * @return
     */
    public String getValueFromCmpRootExpression(String cmp, String val) {
        return this.prepareReturnStatement(this.getFindAtRootExpr(cmp) + ".get('" + val + "')");
    }

    /**
     * Very useful when we know the globalId of the component, inorder to get the attribute value of cmp
     *
     * @param cmp: globalId of the component
     * @param val: attribute name of the component
     * @return
     */
    public String getValueFromCmpExpression(String cmp, String val) {
        return this.prepareReturnStatement(this.getCmpExpr(cmp) + ".get('" + val + "')");
    }

    public void pressEnter(WebElement e) {
        e.sendKeys("\n");
    }

    public void pressTab(WebElement e) {
        e.sendKeys("\t");
    }

    /**
     * Execute the given javascript and args in the current window. Fail if the result is not a boolean. Otherwise,
     * return the result.
     */
    public boolean getBooleanEval(String javascript, Object... args) {
        Object status;
        status = getEval(javascript, args);

        // Special case for weird behavior with ios-driver returning 'ok' instead of true or false. Appears to be an
        // ios-driver bug. Return false so we can retry executing the js instead of erroring out.
        if (status instanceof String && status.equals("ok")) {
            return false;
        }

        if (status == null) {
            Assert.fail("Got a null status for " + javascript + "(" + args + ")");
        }
        if (!(status instanceof Boolean)) {
            Assert.fail("Got unexpected return value: for " + javascript + "(" + args + ") :\n" + status.toString());
        }

        return ((Boolean) status).booleanValue();
    }

    /**
     * Evaluate the given javascript in the current window. Upon completion, if the framework has loaded and is in a
     * test mode, then assert that there are no uncaught javascript errors.
     * <p>
     * As an implementation detail, we accomplish this by wrapping the given javascript so that we can perform the error
     * check on each evaluation without doing a round-trip to the browser (which might be long in cases of remote test
     * runs).
     *
     * @return the result of calling {@link JavascriptExecutor#executeScript(String, Object...) with the given
     *         javascript and args.
     */
    public Object getEval(final String javascript, Object... args) {
        /**
         * Wrapping the javascript on the native Android browser is broken. By not using the wrapper we won't catch any
         * javascript errors here, but on passing cases this should behave the same functionally. See W-1481593.
         */
        if (driver instanceof RemoteWebDriver
                && "android".equals(((RemoteWebDriver) driver).getCapabilities().getBrowserName())) {
            return getRawEval(javascript, args);
        }

        /**
         * Wrap the given javascript to evaluate and then check for any collected errors. Then, return the result and
         * errors back to the WebDriver. We must return as an array because
         * {@link JavascriptExecutor#executeScript(String, Object...)} cannot handle Objects as return values."
         */
        String escapedJavascript = StringEscapeUtils.escapeEcmaScript(javascript);
        String wrapper = "var ret,scriptExecException;"
                + String.format("var func = new Function('arguments', \"%s\");\n", escapedJavascript) + "try\n{"
                + " ret = func.call(this, arguments);\n" + "}\n" + "catch(e){\n"
                + " scriptExecException = e.message || e.toString();\n" + "}\n"
                + //
                "var jstesterrors = (window.$A && window.$A.test) ? window.$A.test.getErrors() : '';\n"
                + "return [ret, jstesterrors, scriptExecException];";

        try {
            @SuppressWarnings("unchecked")
            List<Object> wrapResult = (List<Object>) getRawEval(wrapper, args);
            Assert.assertEquals("Wrapped javsascript execution expects an array of exactly 3 elements", 3,
                    wrapResult.size());
            Object exception = wrapResult.get(2);
            Assert.assertNull("Following JS Exception occured while evaluating provided script:\n" + exception + "\n"
                    + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n", exception);
            String errors = (String) wrapResult.get(1);
            assertJsTestErrors(errors);
            rerunCount = 0;
            return wrapResult.get(0);
        } catch (WebDriverException e) {
            // shouldn't come here that often as we are also wrapping the js
            // script being passed to us in try/catch above
            Assert.fail("Script execution failed.\n" + "Exception type: " + e.getClass().getName()
                    + "\n" + "Failure Message: " + e.getMessage() + "\n" + "Arguments: ("
                    + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n");
            throw e;
        } catch (NullPointerException npe) {
            // Although it should never happen, ios-driver is occasionally returning null when trying to execute the
            // wrapped javascript. Re-run the script a couple more times before failing.
            if (++rerunCount > 2) {
                Assert.fail("Script execution failed.\n" + "Failure Message: " + npe.getMessage() + "\n"
                        + "Arguments: (" + Arrays.toString(args) + ")\n" + "Script:\n" + javascript + "\n");
            }
            return getEval(javascript, args);
        }
    }

    /**
     * Returns value of executing javascript in current window.
     *
     * @see org.openqa.selenium.JavscriptExecutor#executeSript(String, Object...)
     */
    public Object getRawEval(String javascript, Object... args) {
        return ((JavascriptExecutor) driver).executeScript(javascript, args);
    }

    /**
     * @return the User-Agent for the browser we are running tests on
     */
    public String getUserAgent() {
        try {
            return (String) getRawEval("return window.navigator.userAgent;");
        } catch (Exception e) {
            return "error getting User-Agent: " + e;
        }
    }

    /**
     * Process the results from $A.test.getErrors(). If there were any errors, then fail the test accordingly.
     *
     * @param errors the raw results from invoking $A.test.getErrors()
     */
    public void assertJsTestErrors(String errors) {
        if (errors == null) {
            return;
        }

        if (!errors.isEmpty()) {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> errorsList = (List<Map<String, Object>>) new JsonReader().read(errors);
            StringBuilder errorMessage = new StringBuilder();
            StringBuilder functions = new StringBuilder();
            for (Map<String, Object> error : errorsList) {
                errorMessage.append(error.get("message") + "\n");
                if (error.containsKey("lastStage")) {
                    functions.append(error.get("lastStage") + "\n");
                }
            }
            Assert.fail(errorMessage.toString() + functions.toString());
        }
    }

    public String prepareReturnStatement(String returnStatement) {
        return "return " + returnStatement;
    }

    public String findGlobalIdForComponentWithGivenProperties(String fromClause, String whereClause) {
        StringBuilder sb = new StringBuilder();
        sb.append("var cmp = $A.getQueryStatement().from('component').field('globalId').");
        sb.append(fromClause + ".where(\"" + whereClause + "\")" + ".query();\n");
        sb.append("$A.test.assertEquals(1, cmp.rowCount,'Expected to find only one component with given properties.');\n");
        sb.append("return cmp.rows[0].globalId;");
        Object returnVal = getEval(sb.toString());
        return returnVal == null ? null : returnVal.toString();
    }

    /**
     * use to do mouse over the element
     *
     * @param elem
     */
    public void setHoverOverElement(String elem) {
        Actions builder = new Actions(driver);
        // find the element a 2nd time which helps get around the IE hover issues by focusing the element
        WebElement element = driver.findElement(By.className(elem));
        builder.moveToElement(element).build().perform();
    }

    /**
     * Get the text content of a DOM node. Tries "innerText" followed by "textContext" to take browser differences into
     * account.
     *
     */
    public String getActiveElementText() {
        return (String) getEval("return $A.test.getActiveElementText()");
    }

    /**
     * Return Bounding Rectangle Property for given Element
     *
     * @param elementLocalId
     * @param position = "top, left, right, and bottom"
     * @return
     */
    public String getBoundingRectPropOfElement(String elementGlobalId, String position) {
        String element = getCmpExpr(elementGlobalId) + ".getElement().getBoundingClientRect()." + position;
        return getEval(prepareReturnStatement(element)).toString();
    }

    /**
     * Given Element className, method would return component globalId which could be used with $A.getCmp(globalId) to
     * have handle in the component in UI test
     *
     * @param className
     * @return
     */
    public String getCmpGlobalIdGivenElementClassName(String className) {
        String fields = "field('className',\"get('v.class')\").field(\"conc\", \"isConcrete()\")";
        String whereClause = "className === '" + className + "' && conc === true";
        String globalId = findGlobalIdForComponentWithGivenProperties(fields, whereClause);
        return globalId;
    }

    /**
     * Check for uncaught Aura or Javascript errors after executing a particular WebDriver function.
     *
     * @param function a Function accepting a WebDriver instance
     * @return
     */
    public <V> Function<? super WebDriver, V> addErrorCheck(final Function<? super WebDriver, V> function) {
        return new Function<WebDriver, V>() {
            @Override
            public V apply(WebDriver driver) {
                V value = function.apply(driver);
                if ((value == null) || (Boolean.class.equals(value.getClass()) && !Boolean.TRUE.equals(value))) {
                    String errors = (String) getRawEval("return (window.$A && window.$A.test) ? window.$A.test.getErrors() : '';");
                    assertJsTestErrors(errors);
                }
                return value;
            }
        };
    }

    /**
     * Look for any quickfix exceptions. These can sometimes reflect a framework load failure but provide a better error
     * message.
     */
    public void assertNoAuraErrorMessage(Set<String> exceptForThese) {
        String auraErrorMsg = getAuraErrorMessage();
        if (!auraErrorMsg.isEmpty()) {
            if (exceptForThese != null) {
                // Compare against any expected failures
                for (String allowedException : exceptForThese) {
                    if (auraErrorMsg.contains(allowedException)) {
                        return;
                    }
                }
            }
            Assert.fail("Initialization error: " + auraErrorMsg);
        }
    }

    /**
     * Find first matching element in the DOM.
     *
     * @param locator
     * @return
     */
    public WebElement findDomElement(final By locator) {
        List<WebElement> elements = findDomElements(locator);
        if (elements != null) {
            return elements.get(0);
        }
        return null;
    }

    /**
     * Find matching elements in the DOM.
     *
     * @param locator
     * @return
     */
    public List<WebElement> findDomElements(final By locator) {
        WebDriverWait wait = new WebDriverWait(driver, timeoutInSecs);
        return wait.withMessage("fail to find element in dom:" + locator.toString())
                .ignoring(StaleElementReferenceException.class).until(new ExpectedCondition<List<WebElement>>() {

                    @Override
                    public List<WebElement> apply(WebDriver d) {
                        List<WebElement> elements = driver.findElements(locator);
                        if (elements.size() > 0 &&
                                getBooleanEval("return arguments[0].ownerDocument === document", elements.get(0))) {
                            return elements;
                        }
                        return null;
                    }
                });
    }

    /**
     * Get the current aura error message.
     *
     * This will fail the test if the div is not found (which means that the page did not load at all). If the box is
     * not displayed, it returns an empty string.
     *
     * @return any error message that is displayed.
     */
    public String getAuraErrorMessage() {
        WebElement errorBox = driver.findElement(By.id("auraErrorMessage"));
        if (errorBox == null) {
            Assert.fail("Aura errorBox not found.");
        }
        if (!errorBox.isDisplayed()) {
            return "";
        }
        return errorBox.getText();
    }

    /**
     * Assert that our error message is the expected production error message.
     */
    public void assertProdErrorMessage() throws Exception {
        String actual = getAuraErrorMessage().replaceAll("\\s+", " ");
        Assert.assertEquals("Unable to process your request", actual);
    }

    /**
     * Get the quick fix title.
     */
    public String getQuickFixTitle() {
        WebElement toolBar = driver.findElement(By.className("toolbar"));
        if (toolBar == null) {
            // This is actually ok, as the box is not rendered if the cause is not present
            // In this case return an empty string.
            return "";
        }
        return toolBar.getText();
    }

    /**
     * Get any 'cause' message from a quick fix exception
     *
     * @return the quick fix cause exception.
     */
    public String getQuickFixCause() {
        WebElement errorBox = driver.findElement(By.className("causeWrapper"));
        if (errorBox == null) {
            // This is actually ok, as the box is not rendered if the cause is not present
            // In this case return an empty string.
            return "";
        }
        return errorBox.getText();
    }

    /**
     * @return true if Aura framework has loaded
     */
    public boolean isAuraFrameworkReady() {
        return getBooleanEval("return window.$A ? window.$A.finishedInit === true : false;");
    }

    /**
     * Wait until the provided Function returns true or non-null. Any uncaught javascript errors will trigger an
     * AssertionFailedError.
     */
    public <V> V waitUntil(Function<? super WebDriver, V> function) {
        return waitUntil(function, timeoutInSecs);
    }

    /**
     * Wait the specified number of seconds until the provided Function returns true or non-null. Any uncaught
     * javascript errors will trigger an AssertionFailedError.
     */
    public <V> V waitUntil(Function<? super WebDriver, V> function, long timeoutInSecs) {
        WebDriverWait wait = new WebDriverWait(driver, timeoutInSecs);
        return wait.until(addErrorCheck(function));
    }

    /**
     * Wait until the provided Function returns true or non-null. If this does not occur, error out with passed in
     * message. Any uncaught javascript errors will trigger an AssertionFailedError.
     */
    public <V> V waitUntil(Function<? super WebDriver, V> function, String message) {
        return waitUntil(function, timeoutInSecs, message);
    }

    /**
     * Wait the specified number of seconds until the provided Function returns true or non-null. If this does not
     * occur, error out with passed in message. Any uncaught javascript errors will trigger an AssertionFailedError.
     */
    public <V> V waitUntil(Function<? super WebDriver, V> function, long timeoutInSecs, String message) {
        WebDriverWait wait = new WebDriverWait(driver, timeoutInSecs);
        return wait.withMessage(message).until(addErrorCheck(function));
    }

    public String appCacheStatusIntToString(Integer ret) {
        String status = "Unknown cache state";
        switch (ret) {
        case 0:
            status = "UNCACHED";
            break;
        case 1:
            status = "IDLE";
            break;
        case 2:
            status = "CHECKING";
            break;
        case 3:
            status = "DOWNLOADING";
            break;
        case 4:
            status = "UPDATEREADY";
            break;
        case 5:
            status = "OBSOLETE";
            break;
        }
        return status;
    }

    public void waitForAppCacheReady() {
        waitUntilWithCallback(
                new ExpectedCondition<Boolean>() {
                    @Override
                    public Boolean apply(WebDriver d) {
                        return getBooleanEval("var cache=window.applicationCache;"
                                + "return $A.util.isUndefinedOrNull(cache) || (cache.status===cache.UNCACHED)"
                                + "||(cache.status===cache.IDLE)||(cache.status===cache.OBSOLETE);");
                    }
                },
                new ExpectedCondition<String>() {
                    @Override
                    public String apply(WebDriver d) {
                        Object ret = getRawEval("return window.applicationCache.status");
                        return "Current AppCache status is " + appCacheStatusIntToString(((Long) ret).intValue());
                    }
                },
                timeoutInSecs,
                "AppCache is not Ready!");
    }

    /**
     * @param timeoutSecs number of seconds to wait for test to finish
     */
    public void waitForAuraTestComplete(int timeoutSecs) {
        waitUntilWithCallback(
                new ExpectedCondition<Boolean>() {
                    @Override
                    public Boolean apply(WebDriver d) {
                        return getBooleanEval("return window.aura.test.isComplete();");
                    }
                },
                new ExpectedCondition<String>() {
                    @Override
                    public String apply(WebDriver d) {
                        String dump = (String) getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';");
                        if (dump.isEmpty()) {
                            dump = "no test dump available.";
                        }
                        return "Test dump - " + dump;
                    }
                },
                timeoutSecs,
                "Test did not complete within " + timeoutSecs);
    }

    /**
     * @param function function we will apply again and again until timeout
     * @param callbackWhenTimeout function we will run when timeout happens, the return will be append to other output
     *            message, start with "Extra message from callback". we can pass in function to evaluate the client side
     *            status, like applicationCache status
     * @param timeoutInSecs
     * @param message error message when timeout. notice this will get evaluated BEFORE the wait, so just use a string
     */
    public <V2, V1> void waitUntilWithCallback(Function<? super WebDriver, V1> function,
            Function<? super WebDriver, V2> callbackWhenTimeout, long timeoutInSecs, String message) {
        WebDriverWaitWithCallback wait = new WebDriverWaitWithCallback(driver, timeoutInSecs, message);
        wait.until(function, callbackWhenTimeout);
    }

    public void waitForAuraInit() {
        waitForAuraInit(null);
    }

    /**
     * Wait until Aura has finished initialization or encountered an error.
     */
    public void waitForAuraInit(final Set<String> expectedErrors) {
        waitForDocumentReady();
        waitForAuraFrameworkReady(expectedErrors);
        waitForAppCacheReady();
    }

    /**
     * Wait for the document to enter the complete readyState.
     */
    public void waitForDocumentReady() {
        waitUntil(
                new ExpectedCondition<Boolean>() {
                    @Override
                    public Boolean apply(WebDriver d) {
                        return getBooleanEval("return document.readyState === 'complete'");
                    }
                },
                "Document is not Ready!");
    }

    /**
     * First, verify that window.$A has been installed. Then, wait until {@link #isAuraFrameworkReady()} returns true.
     * We assume the document has finished loading at this point: callers should have previously called
     * {@link #waitForDocumentReady()}.
     */
    public void waitForAuraFrameworkReady(final Set<String> expectedErrors) {
        WebDriverWait waitAuraPresent = new WebDriverWait(driver, timeoutInSecs);
        waitAuraPresent.withMessage("Initialization error: Perhaps the initial GET failed")
        .until(
                new Function<WebDriver, Boolean>() {
                    @Override
                    public Boolean apply(WebDriver input) {
                        return (Boolean) getRawEval("return !!window.$A");
                    }
                });

        WebDriverWait waitFinishedInit = new WebDriverWait(driver, timeoutInSecs);
        waitFinishedInit.ignoring(StaleElementReferenceException.class)
        .withMessage("Initialization error: $A present but failed to initialize")
        .until(
                new Function<WebDriver, Boolean>() {
                    @Override
                    public Boolean apply(WebDriver input) {
                        assertNoAuraErrorMessage(expectedErrors);
                        return isAuraFrameworkReady();
                    }
                });
    }

    /**
     * Finds the WebElement identified by locator and applies the provided Function to it, ignoring
     * StaleElementReferenceException.
     *
     * @param locator By locator to find WebElement in the DOM.
     * @param function Function to run on web
     * @param message Message to display to user on timeout.
     * @return
     */
    public <R> R waitForElementFunction(final By locator, final Function<WebElement, R> function, String message) {
        WebDriverWait wait = new WebDriverWait(driver, timeoutInSecs);
        return wait.withMessage(message).until(new ExpectedCondition<R>() {
            private WebElement element = null;

            @Override
            public R apply(WebDriver d) {
                if (element == null) {
                    element = findDomElement(locator);
                }
                try {
                    return function.apply(element);
                } catch (StaleElementReferenceException e) {
                    element = null;
                }
                return null;
            }
        });
    }

    public <R> R waitForElementFunction(final By locator, final Function<WebElement, R> function) {
        return waitForElementFunction(locator, function, "Timeout waiting for element");
    }

    /**
     * Wait for text of an element to be either present or not present.
     *
     * @param locator By locator to find WebElement in the DOM.
     * @param text Text on the found WebElement.
     * @param toBePresent True if we want text passed in as parameter to equal text on found WebElement.
     * @param message Message to display to user on timeout.
     * @param looking for exact match or just partial
     */
    public void waitForElementText(final By locator, final String text, final boolean toBePresent, String message,
            final Boolean matchFullText) {
        waitForElementFunction(locator, new Function<WebElement, Boolean>() {
            @Override
            public Boolean apply(WebElement element) {
                if (matchFullText == true) {
                    return toBePresent == element.getText().equals(text);
                } else {
                    return toBePresent == element.getText().contains(text);
                }
            }
        }, message);
    }

    public void waitForElementText(final By locator, final String text, final boolean toBePresent, String message) {
        waitForElementText(locator, text, toBePresent, message, true);
    }

    public void waitForElementText(final By locator, final String text, final boolean toBePresent) {
        waitForElementText(locator, text, toBePresent, "Timeout looking for element with text: " + text);
    }

    public void waitForElementTextContains(final By locator, final String text, final boolean toBePresent) {
        waitForElementText(locator, text, toBePresent, "Timeout looking for element with text: " + text, false);
    }

    /**
     * Method of exposing accessibility tool to be exposed for testing purposes
     *
     * @return ArrayList - either 0,1, or 2. Position 0: Indicates there were no errors Position 1: Indicates that there
     *         were errors Position 2: Indicates that something unexpected happened.
     */
    public ArrayList<String> doAccessibilityCheck() {
        String jsString = "return ((window.$A != null || window.$A !=undefined) && (!$A.util.isUndefinedOrNull($A.devToolService)))? "
                + "window.$A.devToolService.checkAccessibility() : \"Aura is not Present\"";

        String result = (String) getEval(jsString);

        ArrayList<String> resultList = new ArrayList<>();
        String output = "";

        // No errors
        if (result.equals("") || result.equals("Total Number of Errors found: 0")) {
            output = "0";
        } else if (result.contains("Total Number of Errors found")) {
            output = "1";
        } else {
            output = "2";
        }

        resultList.add(output);
        resultList.add(result);
        return resultList;
    }

    public void assertAccessible() {
        getEval("$A.test.assertAccessible()");

    }

    public String getUniqueIdOfFocusedElement() {
        return (String) getEval("return $A.test.getActiveElement().getAttribute('data-aura-rendered-by')");
    }

    public void assertClassesSame(String message, String expectedClasses, String actualClasses) {
        List<String> expected = AuraTextUtil.splitSimpleAndTrim(" ", expectedClasses, 3);
        List<String> actual = AuraTextUtil.splitSimpleAndTrim(" ", actualClasses, 3);
        List<String> extra = Lists.newArrayList();

        for (String x : actual) {
            if (expected.contains(x)) {
                expected.remove(x);
            } else {
                extra.add(x);
            }
        }
        Assert.assertTrue(message + ": Mismatched classes extra = " + extra + ", missing=" + expected,
                extra.size() == 0 && expected.size() == 0);
    }

    /**
     * Creates a random lower case string. NOTE: this is BAD WAY to produce Strings, as the results are
     * non-reproducible. Do not use it: call {@link #randString(int,long)} instead.
     */
    public String randString(int len) {
        return randString(len, RAND);
    }

    /**
     * Creates a random lower case string of specified length, using given pseudo-Random number generator.
     */
    public String randString(int len, Random rnd) {
        byte[] buff = new byte[len];
        for (int i = 0; i < len; i++) {
            buff[i] = (byte) (rnd.nextInt(26) + 'a');
        }
        try {
            return new String(buff, "US-ASCII");
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * Return true if div has scrollBar
     *
     * @param elementClassName
     * @return
     */
    public boolean hasScrollBar(String elementClassName) {
        String js = "var elementBody = $A.test.getElementByClass('" + elementClassName
                + "')[0];return (elementBody.scrollHeight > this.innerHeight);";
        boolean hasScroll = this.getBooleanEval(js);
        return hasScroll;
    }

}


text:
using System;

namespace com.celigo.net.ServiceManager.SuiteTalk
{
	public partial class JobSearchBasic : ISearchBasic, ISupportsCustomFields<SearchCustomField>
	{
		/// <summary>
		/// Gets custom field with the given ID or <c>null</c> if a field with the
		/// given ID was not found.
		/// </summary>
		public T FindCustomField<T>(string fieldId) where T: SearchCustomField
		{
			T match = null;
			if (null != this.customFieldList)
			{
				match = (T)Array.Find(
									this.customFieldList,
									f => f is T && f.GetInternalId() == fieldId);
			}
			return match;
		}

        /// <summary>
        /// Gets custom field with the given ID or <c>null</c> if a field with the
        /// given ID was not found.
        /// </summary>
        public SearchCustomField FindCustomField(string fieldId)
		{
			SearchCustomField match = null;
			if (null != this.customFieldList)
			{
				match = Array.Find(
									this.customFieldList,
									f => f.GetInternalId() == fieldId);
			}
			return match;
		}	}

	public partial class JobSearch : ISearchRecord
	{
		/// <summary>
		/// Gets the basic search criteria.
		/// </summary>
		/// <returns>The basic search criteria</returns>
		public ISearchBasic GetSearchBasic()
		{
			return this.basic;
		}

		/// <summary>
		/// Gets the basic search criteria.
		/// </summary>
		/// <param name="create">if set to <c>true</c> creates the basic criteria if null.</param>
		/// <returns>The basic search criteria</returns>
		public ISearchBasic GetSearchBasic(bool create)
		{
			if (create && this.basic == null)
				this.basic = new JobSearchBasic();
			return this.basic;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class I18nExtTest < ActiveSupport::TestCase
  # Replace this with your real tests.
  test "the truth" do
    assert true
  end
end


text:
var jobs = {

    getJobs: function () {

        /*
        var jobs = [];
        var term = {};
        jQuery.support.cors = true;

        alert('a');
        jQuery.getJSON("http://www.c4logistics.com/userdata/CurrentLiveForCarrier.aspx?callback=?",
        null,function (data) {
        alert("dd");
        });
        alert('a');

        return jobs;
        }
        }

        alert('a');
        downloadUrl("http://www.c4logistics.com/userdata/CurrentLiveForCarrier.aspx", function (doc) {
        alert('b');
        var xml = xmlParse(doc);
        var movements = xml.documentElement.getElementsByTagName("movement");

        for (var i = 0; i < movements.length; i++) {
        job = new Object();
        job.MovementNumber = movements[i].getAttribute("MovementNumber");
        jobs.push(job);
        }
        });
        */

    }
}

var lat = 0;
var lng = 0;
//A button click will call this function
function getLocation() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: true });
}

// onSuccess Geolocation
//
function onSuccess(position) {
    //Lat long will be fetched and stored in session variables
    //These variables will be used while storing data in local database
    lat = position.coords.latitude;
    lng = position.coords.longitude;
    alert('Lattitude: ' + lat + ' Longitude: ' + long);
    sessionStorage.setItem('lattitude', lat);
    sessionStorage.setItem('longitude', lng);
}
// onError Callback receives a PositionError object
//
function onError(error) {
    alert('code: ' + error.code + '\n' +
          'message: ' + error.message + '\n');
}


text:
layout: post
title: "Greedy Algorithms"
description: ""
category: "algorithm"
tags: []
---

#####Entropy is the optimal(best we can do) of infomation compression

####About greedy algorithm

- You don't have to show that your greedy algorithm beats OPT, you just need to show that it's as good as the OPT
- Proving greedy algorithm:
    - Induction
    - Extreme

###Problem 1

To disprove it, just try find counterexamples

###Problem 2

Greedy algorithm is not always the solution, if it's the case, try some other algorithms

###Problem 3

When swap into OPT, make sure that it's at least as good as OPT

###Problem 4

- Shannon-Fano is not good, you need to modify it to make it actually work
- If encoding individually is not good, try encoding grouply
- Proof technique: use contradiction when it's not easy to quantitize the constraints
- Lempel-Ziv is a good compression algorithm

###Problem 5

- Huffman encoding is guaranteed to be within range $$1$$ of $$H(p)$$
- For infomation with low entropy, use Huffman combined with run-length


text:
package killer

import (
	"testing"

	"github.com/crawl/go-sequell/crawl/data"
)

var killerTests = []struct {
	start  string
	finish string
}{
	{"a two-headed hydra", "a hydra"},
	{"a 12-headed hydra", "a hydra"},
	{"the 27-headed Lernaean hydra zombie", "the Lernaean hydra zombie"},
	{"Foobar's ghost", "a player ghost"},
	{"ackbar's illusion", "a player illusion"},
	{"a red draconian shifter", "a draconian shifter"},
	{"a yak (shapeshifter)", "a shapeshifter"},
	{"a camel (glowing shapeshifter)", "a glowing shapeshifter"},
	{"a red ugly thing", "an ugly thing"},
	{"a green very ugly thing", "a very ugly thing"},
	{"Grum", "Grum"},
	{"Bogdan the orc", "an orc"},
	{"Ghib", "a pandemonium lord"},
}

func TestNormalizeKiller(t *testing.T) {
	k := NewNormalizer(data.CrawlData())
	for _, test := range killerTests {
		res := k.NormalizeKiller("0.10", test.start, test.start, "")
		if res != test.finish {
			t.Errorf("Expected '%s' to normalize to '%s', but got '%s'", test.start, test.finish, res)
		}
	}
}

var kmodTests = [][]string{
	{"a spectral warrior", ""},
	{"a spectral hydra", "spectre"},
	{"a dragon (shapeshifter)", "shapeshifter"},
	{"a glowing shapeshifter", "shapeshifter"},
	{"an 18-headed hydra zombie", "zombie"},
	{"a bat skeleton", "skeleton"},
	{"a goblin simulacrum", "simulacrum"},
	{"a kobold", ""},
}

func TestNormalizeKmod(t *testing.T) {
	for _, test := range kmodTests {
		killer, kmod := test[0], test[1]
		actual := NormalizeKmod(killer)
		if actual != kmod {
			t.Errorf("NormalizeKmod(%s) == %s, expected %s\n",
				killer, actual, kmod)
		}
	}
}

var kauxTests = [][]string{
	{"a longsword {cow}", "longsword"},
	{"a +2 sling (mu)", "sling"},
	{"an ox", "ox"},
	{"an elven crossbow", "crossbow"},
	{"Hit by a dart thrown by a horse", "dart"},
	{"Shot with an arrow by an elf", "arrow"},
	{"a cursed dagger", "dagger"},
}

func TestNormalizeKaux(t *testing.T) {
	for _, kauxTest := range kauxTests {
		kaux, ckaux := kauxTest[0], kauxTest[1]
		res := NormalizeKaux(kaux)
		if res != ckaux {
			t.Errorf("NormalizeKaux(%#v) == %#v, expected %#v\n",
				kaux, res, ckaux)
		}
	}
}


text:
[![Actions Status](https://github.com/bigeasy/memento/workflows/Node%20CI/badge.svg)](https://github.com/bigeasy/memento/actions)
[![codecov](https://codecov.io/gh/bigeasy/memento/branch/master/graph/badge.svg)](https://codecov.io/gh/bigeasy/memento)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A pure-JavaScript `async`/`await` indexed, persistant database.

| What          | Where                                         |
| --- | --- |
| Discussion    | https://github.com/bigeasy/memento/issues/1   |
| Documentation | https://bigeasy.github.io/memento             |
| Source        | https://github.com/bigeasy/memento            |
| Issues        | https://github.com/bigeasy/memento/issues     |
| CI            | https://travis-ci.org/bigeasy/memento         |
| Coverage:     | https://codecov.io/gh/bigeasy/memento         |
| License:      | MIT                                           |

Memento installs from NPM.

```text
npm install memento
```

Memento is a database that supports atomic, isolated transactions, written to a
write-ahead log and synced for durability in the event of system crash, and
merged into b-trees for fast retrieval. It reads from an in memory page cache
and evicts pages from the cache when they reach a user specified memory limit.

Memento is written in pure JavaScript.

Memento provides a contemporary `async`/`await` interface.

This `README.md` is also a unit test using the
[Proof](https://github.com/bigeasy/proof) unit test framework. We'll use the
Proof `okay` function to assert out statements in the readme. A Proof unit test
generally looks like this.

```javascript
require('proof')(4, async okay => {
    okay('always okay')
    okay(true, 'okay if true')
    okay(1, 1, 'okay if equal')
    okay({ value: 1 }, { value: 1 }, 'okay if deep strict equal')
})
```

You can run this unit test yourself to see the output from the various
code sections of the readme.

```text
git clone git@github.com:bigeasy/memento.git
cd memento
npm install --no-package-lock --no-save
node test/readme.t.js
```

The `'memento'` module exports a single `Memento` object.

```javascript
const Memento = require('memento')
```

We create a database object with the static `async Memento.open` function. It
returns an open database ready for use.

The first argument to `async Memento.open()` is an options object.

The second argument is an `async` database upgrade function. You are only able
to create new stores and indices in the update function. Once the database is
open you're not allowed to make any schema changes.

```javascript
const directory = path.resolve(__dirname, './tmp/readme')
const memento = await Memento.open({ directory }, async schema => {
    switch (schema.version.current + 1) {
    case 1:
        await schema.create('president', { lastName: String, firstName: String })
    }
})
```

In order to add or remove data from the database you invoke `memento.mutator()`
with an `async` mutation callback function. The mutation function will be called
with a `Mutator` object.

The mutator function represents an atomic transaction against the database.
Changes made within the function are only visible within the function. They only
become visible outside of the function when the function returns successfully.

If the function raises and exception, the changes are rolled back.

```javascript
await memento.mutator(async mutator => {
    mutator.set('president', { firstName: 'George', lastName: 'Washington', state: 'VA' })
    const got = await mutator.get('president', [ 'Washington', 'George' ])
    okay(got, {
        firstName: 'George', lastName: 'Washington', state: 'VA'
    }, 'isolated view of inserted record')
})
```

You'll notice that the `mutator.set()` method is a synchronous function. This is
because we want inserts and deletes to be fast. Rather than performing
asynchronous file operations for each insert and delete, we cache the changes in
memory and write them out in batches.

The `mutator.get()` method on the other hand is an `async` function. We have to
go and check the database to see if the value is there and compare it with our
write cache. Checking the database may require a read operation, or it may not,
depending on the database cache.

So, `mutator.set()` ought to be pretty quick, making batch inserts relatively
painless. `async mutator.get()` not so quick because it has to go out through
the `Promise`s event loop.

We'll make up for this discrepancy when we look at ranged queries, iterators,
and joins.

Note that the `Snapshot` object is only valid during the invocation of the
snapshot callback function. If you attempt to save it and use later you will get
undefined behavior. Currently, there are no assertions to keep you from doing
this, just don't do it.

```javascript
let evilMutator
await memento.mutator(async mutator => {
    evilMutator = mutator
})
// No!
evilMutator.set('president', { firstName: 'John', lastName: 'Adams', state: 'VA' })
```

When we only want to read the database we use a `mutator.snapshot()` with an
`async` snapshot callback function. The snapshot function will be called with a
`Snapshot` object.

Use the `Snapshot`, the snapshot function can perform read-only requests on the
database. The `Snapshot` will have a point in time view of the database. Any
changes made by mutators that commit after the snapshot callback function begins
will not be visible to the snapshot function.

```javascript
await memento.snapshot(async snapshot => {
    const got = await snapshot.get('president', [ 'Washington', 'George' ])
    okay(got, {
        firstName: 'George', lastName: 'Washington', state: 'VA'
    }, 'snapshot view of inserted record')
})
```

When you are done with Memento you close it.

```javascript
await memento.close()
```

### Create, Retrieve, Update and Delete

Let's create a database.

Insert is done with `set`.

We're going to reopen the database. Usually you'll only have one spot in your
program where you open your database and it will have a schema function that
builds or migrates the database. In our example we are reopening an existing
database that has already been built to the schema function should not be
called. In our test here, we're going to assert that it is not called with an
exception.

```javascript
const directory = path.resolve(__dirname, './tmp/readme')
const memento = await Memento.open({ directory }, async schema => {
    throw new Error('should not be called')
})
```

We use `set` to insert or update a record into the database. We use `get` to get
a single record out of the database.

```javascript
await memento.mutator(async mutator => {
    mutator.set('president', { firstName: 'Jack', lastName: 'Adams', state: 'NY' })
    const get = await mutator.get('president', [ 'Adams', 'Jack' ])
    okay(get, { firstName: 'Jack', lastName: 'Adams', state: 'NY' }, 'isolated retrieve')
})
```

Once the mutator is complete other snapshots and mutators will see the written
record.

```javascript
await memento.snapshot(async mutator => {
    const get = await mutator.get('president', [ 'Adams', 'Jack' ])
    okay(get, { firstName: 'Jack', lastName: 'Adams', state: 'NY' }, 'snapshot retrieve')
})
```

We update records using `set` as well. Let's fix the home state of John Adams.

```javascript
await memento.mutator(async mutator => {
    mutator.set('president', { firstName: 'Jack', lastName: 'Adams', state: 'MA' })
    const get = await mutator.get('president', [ 'Adams', 'Jack' ])
    okay(get, { firstName: 'Jack', lastName: 'Adams', state: 'MA' }, 'retrieve')
})
```

Note that we can't change the name of one of our presidents because we are using
last name and first name as the key. You would have to delete and insert.

Let's delete "Jack Adams".

```javascript
await memento.mutator(async mutator => {
    mutator.unset('president', [ 'Adams', 'Jack' ])
    const get = await mutator.get('president', [ 'Adams', 'Jack' ])
    okay(get, null, 'deleted')
})
```

Still removed when we search in a subsequent snapshot.

```javascript
await memento.snapshot(async mutator => {
    const get = await mutator.get('president', [ 'Adams', 'Jack' ])
    okay(get, null, 'deleted')
})
```

Let's insert John Adams.

```javascript
await memento.mutator(async mutator => {
    mutator.set('president', { lastName: 'Adams', firstName: 'John', state: 'MA' })
})
```

```javascript
```

Close the database.

```javascript
await memento.close()
```

### Stores and Indices

Index example.

```javascript
const directory = path.resolve(__dirname, './tmp/readme')
const memento = await Memento.open({ directory, version: 2 }, async schema => {
    switch (schema.version.current + 1) {
    case 1:
        await schema.create('president', { lastName: String, firstName: String })
    case 2:
        await schema.create([ 'president', 'state' ], { state: String })
    }
})
```

We can use our index immediately after creating it.

```javascript
await memento.snapshot(async snapshot => {
    const got = await snapshot.get([ 'president', 'state' ], [ 'MA' ])
    okay(got, { firstName: 'John', lastName: 'Adams', state: 'MA' }, 'get by index')
})
```

When you get by an index the index can match multiple records. The first one is
returned.

```javascript
await memento.mutator(async mutator => {
    mutator.set('president', { firstName: 'Thomas', lastName: 'Jefferson', state: 'VA' })
    const got = await mutator.get([ 'president', 'state' ], [ 'VA' ])
    okay(got, { firstName: 'Thomas', lastName: 'Jefferson', state: 'VA' }, 'get first by index')
})
```

TODO Make a point of closing here and opening in the next section.

### Cursors and Iteration

So far we've only seen get which returns a single entry.

```javascript
await memento.snapshot(async snapshot => {
    const gathered = []
    for await (const presidents of snapshot.cursor('president')) {
        for (const president of presidents) {
            gathered.push(president)
        }
    }
    okay(gathered, [{
        firstName: 'John', lastName: 'Adams', state: 'MA'
    }, {
        firstName: 'Thomas', lastName: 'Jefferson', state: 'VA'
    }, {
        firstName: 'George', lastName: 'Washington', state: 'VA'
    }], 'cursor')
})
```

Let's add some more presidents for the sake of the index search.

```javascript
await memento.mutator(async mutator => {
    mutator.set('president', { firstName: 'James', lastName: 'Monroe', state: 'VA' })
    mutator.set('president', { firstName: 'John Quincy', lastName: 'Adams', state: 'MA' })
})
```

Iterating over an index.

```javascript
await memento.snapshot(async snapshot => {
    const gathered = []
    for await (const presidents of snapshot.cursor([ 'president', 'state' ], [ 'VA' ])) {
        for (const president of presidents) {
            gathered.push(president)
        }
    }
    okay(gathered, [{
        firstName: 'Thomas', lastName: 'Jefferson', state: 'VA'
    }, {
        firstName: 'James', lastName: 'Monroe', state: 'VA'
    }, {
        firstName: 'George', lastName: 'Washington', state: 'VA'
    }], 'cursor')
})
```

Reversing an index.

```javascript
await memento.snapshot(async snapshot => {
    const gathered = []
    for await (const presidents of snapshot.cursor([ 'president', 'state' ], [ 'MA' ]).reverse()) {
        for (const president of presidents) {
            gathered.push(president)
        }
    }
    okay(gathered, [{
        firstName: 'John Quincy', lastName: 'Adams', state: 'MA'
    }, {
        firstName: 'John', lastName: 'Adams', state: 'MA'
    }], 'cursor')
})
```

We'll shutdown the database before moving onto isolation with snapshots and
mutators.

```javascript
await memento.close()
```

### Snapshots versus Mutators

You use mutators to change data. None of the changes made by the mutator are
visible to any of the other snapshots or mutators until the mutator returns.

Let's reopen the database. In our program we'll have a single open stanza for a
database so we'll repeat the schema update block here.

**TODO** Maybe have an `openVersion1` and `openVersion2` function example.

```javascript
const directory = path.resolve(__dirname, './tmp/readme')
const memento = await Memento.open({ directory, version: 2 }, async schema => {
    switch (schema.version.current + 1) {
    case 1:
        await schema.create('president', { lastName: String, firstName: String })
    case 2:
        await schema.create([ 'president', 'state' ], { state: String })
    }
})
```

```javascript
const resolves = {}

const promises = {
    wrote: new Promise(resolve => resolves.wrote = resolve),
    reading: new Promise(resolve => resolves.reading = resolve)
}

const promise = memento.mutator(async mutator => {
    await promises.reading
    mutator.set('president', { firstName: 'Andrew', lastName: 'Jackson', state: 'SC' })
    resolves.wrote()
})

await memento.snapshot(async snapshot => {
    resolves.reading()
    await promises.wrote
    okay(await snapshot.get('president', [ 'Jackson', 'Andrew' ]), null, 'isolated write not visible')
})
```

We'll close the database before moving onto inner and outer joins.

```javascript
await memento.close()
```

### Inner and Outer Joins

### Migrations

### API

`memento = Memento.open(options, async upgrade => {})`

 * `options`
     * `destructible` — Optional instance of Destructible for structured
        concurrency management of the Memento instance.
     * `turnstile` — Optional Turnstile to manage parallel writes to file
        system.
     * `directory` — Directory in which to store data files.
     * `version` — Migration version.
     * `comparisons` — Optional of one or more comparision functions to use
        for collation.
 * `upgrade` —

`memento.snapshot(async snapshot => {})`

`memento.mutator(async mutator => {})`


text:
#include "util.h"
#include "wacrpt.h"

#define usage  "[ -f report_files_list | wordacc_report1 wordacc_report2 ... ] >wordacc_report"

Wacdata wacdata;

char *inputfilename;

Option option[] =
{
    {'f', &inputfilename, NULL},
    {'\0'}
};

/**********************************************************************/

void process_file(filename)
char *filename;
{
    read_wacrpt(&wacdata, filename);
}
/**********************************************************************/

int main(argc, argv)
int argc;
char *argv[];
{
    int i;
    initialize(&argc, argv, usage, option);
    if (argc < 2 && !inputfilename)
        error("not enough input files", Exit);
    process_all_files_from(inputfilename, &process_file);
    for (i = 0; i < argc; i++)
        process_file(argv[i]);
    write_wacrpt(&wacdata, NULL);
    return 0;
}


text:
forked from https://github.com/aaditmshah/lexer

## Installation ##

`npm install lex-es6`


text:
namespace chrono {
namespace sensor {

// forward declaration
class ChSensor;

/// @addtogroup sensor_filters
/// @{

/// GPS Noise Model base class. All GPS noise models should inherit from here.
class CH_SENSOR_API ChGPSNoiseModel {
  public:
    /// Class constructor
    ChGPSNoiseModel(){};
    /// Class destructor
    ~ChGPSNoiseModel(){};

    /// Virtual function that every GPS noise model must implement. Will be called when noise should be added to the
    /// data.
    /// @param coords The Cartesian coordinates to be augmented with data.
    virtual void AddNoise(ChVector<double>& coords) = 0;
};

/// GPS Noise model: individually parameterized independent gaussian distribution
class CH_SENSOR_API ChGPSNoiseNone : public ChGPSNoiseModel {
  public:
    /// Class constructor
    ChGPSNoiseNone() {}
    /// Class destructor
    ~ChGPSNoiseNone() {}

    /// Noise addition function. Adds no noise for this model.
    /// @param coords The Cartesian coordinates to be augmented with data.
    virtual void AddNoise(ChVector<double>& coords) {}
};

/// GPS Noise model: individually parameterized independent gaussian distribution
class CH_SENSOR_API ChGPSNoiseNormal : public ChGPSNoiseModel {
  public:
    /// Class constructor
    /// @param mean The mean of the normal distribution
    /// @param stdev The standard deviation of the normal distribution
    ChGPSNoiseNormal(ChVector<float> mean, ChVector<float> stdev);
    /// Class destructor
    ~ChGPSNoiseNormal();

    /// Noise addition function. Adds no noise for this model.
    /// @param coords The Cartesian coordinates to be augmented with data.
    virtual void AddNoise(ChVector<double>& coords);

  private:
    std::minstd_rand m_generator;  ///< random number generator
    ChVector<float> m_mean;        ///< mean of the normal distribution
    ChVector<float> m_stdev;       ///< standard deviation of the normal distribution
};

/// Class for generating GPS data for a GPS sensor
class CH_SENSOR_API ChFilterGPSUpdate : public ChFilter {
  public:
    /// Class constructor
    /// @param gps_reference The GPS location of the simulation origin
    /// @param noise_model The noise model for augmenting the GPS data
    ChFilterGPSUpdate(ChVector<double> gps_reference, std::shared_ptr<ChGPSNoiseModel> noise_model);

    /// Apply function. Generates GPS data.
    /// @param pSensor A pointer to the sensor on which the filter is attached.
    /// @param bufferInOut A buffer that is passed into the filter.
    virtual void Apply(std::shared_ptr<ChSensor> pSensor, std::shared_ptr<SensorBuffer>& bufferInOut);

    /// Initializes all data needed by the filter access apply function.
    /// @param pSensor A pointer to the sensor.
    virtual void Initialize(std::shared_ptr<ChSensor> pSensor) {}

  private:
    std::shared_ptr<SensorHostGPSBuffer> m_buffer;   ///< buffer that will be used for passing to the next filter
    std::shared_ptr<ChGPSNoiseModel> m_noise_model;  ///< pointer to the noise model for augmenting GPS data
    ChVector<double> m_ref;                          ///< for holding the reference location
};

/// @}

}  // namespace sensor
}  // namespace chrono

#endif


text:
<?php

require_once 'init.php';

use Agil\Model\Model as Model;

class Team extends Model {
	public $fields = array('id_team', 'id_admin', 'id_project', 'name', 'website', 'slug');
	public $auto_fields = array('create_date', 'update_date', 'status');
}

class TeamMemberSet extends Model {
	public $fields = array('id_team_member_set', 'id_team', 'id_member');
	public $auto_fields = array('create_date', 'update_date', 'status');
}


text:
@interface PodsDummy_RxRelay_watchOS : NSObject
@end
@implementation PodsDummy_RxRelay_watchOS
@end


text:
package gw.internal.gosu.ir.transform.expression;

import gw.internal.gosu.ir.nodes.IRMethodFactory;
import gw.internal.gosu.ir.transform.ExpressionTransformer;
import gw.internal.gosu.ir.transform.TopLevelTransformationContext;
import gw.internal.gosu.parser.BeanAccess;
import gw.internal.gosu.parser.expressions.AdditiveExpression;
import gw.internal.gosu.parser.expressions.Identifier;
import gw.internal.gosu.runtime.GosuRuntimeMethods;
import gw.lang.ir.IRExpression;
import gw.lang.ir.expression.IRArithmeticExpression;
import gw.lang.ir.expression.IRStringLiteralExpression;
import gw.lang.parser.IParseTree;
import gw.lang.parser.IParsedElement;
import gw.lang.parser.StandardSymbolTable;
import gw.lang.reflect.IMethodInfo;
import gw.lang.reflect.IType;
import gw.lang.reflect.java.JavaTypes;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collections;

/**
 */
public class AdditiveExpressionTransformer extends AbstractExpressionTransformer<AdditiveExpression>
{
  public static IRExpression compile( TopLevelTransformationContext cc, AdditiveExpression expr )
  {
    AdditiveExpressionTransformer gen = new AdditiveExpressionTransformer( cc, expr );
    return gen.compile();
  }

  private AdditiveExpressionTransformer( TopLevelTransformationContext cc, AdditiveExpression expr )
  {
    super( cc, expr );
  }

  protected IRExpression compile_impl()
  {
    boolean bNumeric = BeanAccess.isNumericType( _expr().getType() );
    IMethodInfo operatorOverload = _expr().getOverride();
    if( bNumeric && operatorOverload != null )
    {
      // The operator is overloaded, call into it...
      IRExpression lhs = ExpressionTransformer.compile( _expr().getLHS(), _cc() );
      IRExpression rhs = ExpressionTransformer.compile( _expr().getRHS(), _cc() );
      return callMethod( IRMethodFactory.createIRMethod( operatorOverload, null ), lhs, exprList( rhs ) );
    }
    else
    {
      if( isSimpleAddition() )
      {
        return simpleAddition();
      }
      else if( isBigDecimalAddition() )
      {
        return bigDecimalAddition();
      }
      else if( isBigIntegerAddition() )
      {
        return bigIntegerAddition();
      }
      else
      {
        if( isCompileTimeConstantConcatenation() )
        {
          return concatenate();
        }
//## todo: handle other cases efficiently
//   (ex var a = "1" var b = "2" var c = a + b  -> we should generate code using a StringBuilder)
//        else
//        {
//
//        }
        return complexAddition( bNumeric );
      }
    }
  }

  private boolean isBigDecimalAddition()
  {
    return !_expr().isNullSafe() &&
           JavaTypes.BIG_DECIMAL().equals( _expr().getType() ) &&
           JavaTypes.BIG_DECIMAL().equals( _expr().getLHS().getType() ) &&
           JavaTypes.BIG_DECIMAL().equals( _expr().getRHS().getType() );
  }
  private IRExpression bigDecimalAddition( )
  {
    IType type = _expr().getType();

    IRExpression lhs = ExpressionTransformer.compile( _expr().getLHS(), _cc() );
    IRExpression rhs = ExpressionTransformer.compile( _expr().getRHS(), _cc() );

    return callMethod( BigDecimal.class, _expr().isAdditive() ? "add" : "subtract", new Class[] {BigDecimal.class}, lhs, Collections.singletonList( rhs ) );
  }

  private boolean isBigIntegerAddition()
  {
    return !_expr().isNullSafe() &&
           JavaTypes.BIG_INTEGER().equals( _expr().getType() ) &&
           JavaTypes.BIG_INTEGER().equals( _expr().getLHS().getType() ) &&
           JavaTypes.BIG_INTEGER().equals( _expr().getRHS().getType() );
  }
  private IRExpression bigIntegerAddition( )
  {
    IType type = _expr().getType();

    IRExpression lhs = ExpressionTransformer.compile( _expr().getLHS(), _cc() );
    IRExpression rhs = ExpressionTransformer.compile( _expr().getRHS(), _cc() );

    return callMethod( BigInteger.class, _expr().isAdditive() ? "add" : "subtract", new Class[] {BigInteger.class}, lhs, Collections.singletonList( rhs ) );
  }

  private IRStringLiteralExpression concatenate()
  {
    return (IRStringLiteralExpression) pushConstant( GosuRuntimeMethods.toString( _expr().getLHS().evaluate() ) +
                                                     GosuRuntimeMethods.toString( _expr().getRHS().evaluate() ) );
  }

  private IRExpression simpleAddition( )
  {
    IType type = _expr().getType();

    // Push LHS
    IRExpression lhs = ExpressionTransformer.compile( _expr().getLHS(), _cc() );
    // Maybe convert to expression type
    lhs = numberConvert( _expr().getLHS().getType(), type, lhs );

    // Push RHS
    IRExpression rhs = ExpressionTransformer.compile( _expr().getRHS(), _cc() );
    // Maybe convert to expression type
    rhs = numberConvert( _expr().getRHS().getType(), type, rhs );

    return new IRArithmeticExpression(getDescriptor( type ), lhs, rhs, _expr().isAdditive() ? IRArithmeticExpression.Operation.Addition : IRArithmeticExpression.Operation.Subtraction );
  }

  private IRExpression complexAddition( boolean bNumeric )
  {

    // Call into Gosu's runtime for the answer.  The arguments are the result type, the boxed LHS, the boxed RHS,
    // the LHS type, the RHS type, whether it's addition, and whether it's numeric
    IRExpression evaluateCall = callStaticMethod( AdditiveExpression.class, "evaluate",
                                                  new Class[]{IType.class, Object.class, Object.class, IType.class, IType.class, boolean.class, boolean.class, boolean.class},
                                                  exprList( pushType( _expr().getType() ),
                                                            boxValue( _expr().getLHS().getType(), ExpressionTransformer.compile( _expr().getLHS(), _cc() ) ),
                                                            boxValue( _expr().getRHS().getType(), ExpressionTransformer.compile( _expr().getRHS(), _cc() ) ),
                                                            pushType( _expr().getLHS().getType() ),
                                                            pushType( _expr().getRHS().getType() ),
                                                            pushConstant( _expr().isAdditive() ),
                                                            pushConstant( _expr().isNullSafe() ),
                                                            pushConstant( bNumeric ) ) );

    // Ensure value is unboxed if type is primitive
    return unboxValueToType( _expr().getType(), evaluateCall );
  }

  public boolean isSimpleAddition()
  {
    return isPrimitiveNumberType( _expr().getType() ) &&
           isPrimitiveNumberType( _expr().getLHS().getType() ) &&
           isPrimitiveNumberType( _expr().getRHS().getType() );
  }

  private boolean isCompileTimeConstantConcatenation()
  {
    return  _expr().getType() == JavaTypes.STRING() &&
            _expr().isCompileTimeConstant() &&
            !containsIdentifier( _expr().isAssignment() ? _expr().getParent() : _expr() );
  }

  private boolean containsIdentifier( IParsedElement expr )
  {
    if ( expr instanceof Identifier &&
         !((Identifier) expr).isStaticFinalInitializedCompileTimeConstant() )
    {
      return true;
    }
    IParseTree location = expr.getLocation();
    if( location == null )
    {
      return true;
    }
    for( IParseTree child: location.getChildren() )
    {
      if( containsIdentifier( child.getParsedElement() ) )
      {
        return true;
      }
    }
    return false;
  }
}


text:
package org.apache.hadoop.lib.wsrs;

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.junit.Test;

public class TestInputStreamEntity {

  @Test
  public void test() throws Exception {
    InputStream is = new ByteArrayInputStream("abc".getBytes());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStreamEntity i = new InputStreamEntity(is);
    i.write(baos);
    baos.close();
    assertEquals(new String(baos.toByteArray()), "abc");

    is = new ByteArrayInputStream("abc".getBytes());
    baos = new ByteArrayOutputStream();
    i = new InputStreamEntity(is, 1, 1);
    i.write(baos);
    baos.close();
    assertEquals(baos.toByteArray()[0], 'b');
  }

}


text: export { DropButton } from './DropButton';


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>DMA Friends: DMA\Friends\Classes\UserExtend Class Reference</title>

<link href="bootstrap3/css/bootstrap.min.css" rel="stylesheet">

<link href="../../search/search.css" rel="stylesheet" type="text/css"/>

<link href="../../doxygen.css" rel="stylesheet" type="text/css" />

DMA Friends
    2.0

Main Page

Related Pages

Namespaces

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

DMA

Friends

Classes

UserExtend

Public Member Functions |
Static Public Member Functions |
Public Attributes |
List of all members

DMA\Friends\Classes\UserExtend Class Reference

Public Member Functions

 	__construct (User $user=null)

 	addPoints ($points)

 	removePoints ($points, $deduct=true)

 	getMembershipStatusOptions ()

Static Public Member Functions

static 	uploadAvatar ($user, $image)

static 	uploadAvatarFromString ($user, $source)

static 	parsePhone ($phone)

Public Attributes

 	$user = null

Constructor & Destructor Documentation

          DMA\Friends\Classes\UserExtend::__construct
          (
          User
          $user = null	)

Extended functionality against user objects This is a really ugly way to extend the functionality of the user object

Parameters

   42     {

   43         if (!$user)

   44             $user = new User;

   45

   46         $this->user = $user;

   47     }

User

Member Function Documentation

          DMA\Friends\Classes\UserExtend::addPoints
          (

          $points	)

Add points to a users account

Parameters

integer	$points	The amount of points to add to a user

   56     {

   57         if (!is_numeric($points))

   58             throw new SystemException('Points must be an integer');

   59

   60         $this->user->points += $points;

   61         $this->user->points_this_week += $points;

   62         $this->user->points_today += $points;

   63

   64         if ($this->user->forceSave()) {

   65

   66             // Process any activities awarded on points achievement

   67             Points::process($this->user);

   68

   69             Event::fire('dma.friends.user.pointsEarned', [$this->user, $points]);

   70

   71             $params = [

   72                 'user'          => $this->user,

   73                 'points_earned' => $points,

   74             ];

   75             FriendsLog::points($params);

   76         }

   77     }

SystemException

DMA\Friends\Activities\Points\process

static process(User $user, $params=[])

Definition: Points.php:47

DMA\Friends\Classes\FriendsLog\points

static points($params)

Definition: FriendsLog.php:137

          DMA\Friends\Classes\UserExtend::removePoints
          (

          $points,

          $deduct = true

          )

Remove points from a user account

Parameters

integer	$points	The amount of points to remove from a user account

boolean	$deduct	If false points will not be deducted from leaderboard points

Returns

boolean returns true if points where removed

   92     {

   93         if (!is_numeric($points))

   94             throw new SystemException('Points must be an integer');

   95

   96         if ($this->user->points < $points) {

   97             return false;

   98         }

   99

  100         $this->user->points -= $points;

  101

  102         if ($deduct) {

  103             $this->user->points_this_week -= $points;

  104             $this->user->points_today -= $points;

  105         }

  106

  107         if ($this->user->forceSave()) {

  108             Event::fire('dma.friends.user.pointsRemoved', [$this->user, $points]);

  109         }

  110

  111         return true;

  112     }

SystemException

          static DMA\Friends\Classes\UserExtend::uploadAvatarFromString
          (

          $user,

          $source

          )

static

Upload Avatar from Base64 encoded image

Parameters

\RainLab\User\Models\User	$user

string	$source	string contend of an image on Base64 enconding

  143     {

  144         $dst = '/tmp/avatar_' . $user->getKey() . '_' . uniqid();

  145

  146         FileHelper::put($dst, base64_decode($source));

  147

  148         $validImage = true;

  149         try{

  150             // Validated is a JPG or PNG

  151             $imageType = exif_imagetype($dst);

  152             $validImage = in_array($imageType, [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF]);

  153             // Validated is not bigger that xx by xx

  154             if($validImage){

  155                 // Test if image is corrupted if OctoberCMS Resizer can open it

  156                 // is more likely the image is ok

  157                 Resizer::open($dst);

  158

  159                 // Test image dimensions

  160                 list($width, $height, $type, $attr) = getimagesize($dst);

  161                 $validImage = ($width <= 400 && $height <= 400);

  162

  163             }

  164             // Add right file extension to the upload file

  165             if($validImage){

  166

  167                 // Save image with correct image extension

  168                 $extension = [ IMAGETYPE_JPEG => 'jpg', IMAGETYPE_PNG => 'png', IMAGETYPE_GIF => 'gif'][$imageType];

  169                 $newDst = $dst . '.' . $extension;

  170                 rename($dst, $newDst);

  171                 $dst = $newDst;

  172

  173             }

  174         } catch(\Exception $e){

  175             $validImage = false;

  176         }

  177

  178         if(!$validImage){

  179             throw new \Exception('Must be a valid JPG, GIF or PNG. And not bigger that 400x400 pixels.');

  180         }

  181

  182         $file = new File;

  183         $file->data = $dst;

  184         $file->is_public = true;

  185         $file->save();

  186

  187         if ($file) {

  188             $user->avatar()->add($file);

  189         }

  190

  191     }

File

Exception

The documentation for this class was generated from the following file:

classes/UserExtend.php

<address class="footer">
Generated on Fri Jun 26 2015 13:24:10 for DMA Friends by

 1.8.9.1
</address>


text:
template<typename MatrixType> void upperbidiag(const MatrixType& m)
{
  const Index rows = m.rows();
  const Index cols = m.cols();

  typedef Matrix<typename MatrixType::RealScalar, MatrixType::RowsAtCompileTime,  MatrixType::ColsAtCompileTime> RealMatrixType;
  typedef Matrix<typename MatrixType::Scalar, MatrixType::ColsAtCompileTime,  MatrixType::RowsAtCompileTime> TransposeMatrixType;

  MatrixType a = MatrixType::Random(rows,cols);
  internal::UpperBidiagonalization<MatrixType> ubd(a);
  RealMatrixType b(rows, cols);
  b.setZero();
  b.block(0,0,cols,cols) = ubd.bidiagonal();
  MatrixType c = ubd.householderU() * b * ubd.householderV().adjoint();
  VERIFY_IS_APPROX(a,c);
  TransposeMatrixType d = ubd.householderV() * b.adjoint() * ubd.householderU().adjoint();
  VERIFY_IS_APPROX(a.adjoint(),d);
}

EIGEN_DECLARE_TEST(upperbidiagonalization)
{
  for(int i = 0; i < g_repeat; i++) {
   CALL_SUBTEST_1( upperbidiag(MatrixXf(3,3)) );
   CALL_SUBTEST_2( upperbidiag(MatrixXd(17,12)) );
   CALL_SUBTEST_3( upperbidiag(MatrixXcf(20,20)) );
   CALL_SUBTEST_4( upperbidiag(Matrix<std::complex<double>,Dynamic,Dynamic,RowMajor>(16,15)) );
   CALL_SUBTEST_5( upperbidiag(Matrix<float,6,4>()) );
   CALL_SUBTEST_6( upperbidiag(Matrix<float,5,5>()) );
   CALL_SUBTEST_7( upperbidiag(Matrix<double,4,3>()) );
  }
}


text:
package org.diirt.datasource.sys;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.diirt.vtype.Alarm;
import org.diirt.vtype.AlarmSeverity;
import static org.diirt.vtype.ValueFactory.*;

/**
 *
 * @author carcassi
 */
class HostnameChannelHandler extends SystemChannelHandler {

    private String previousValue = null;

    public HostnameChannelHandler(String channelName) {
        super(channelName);
    }

    @Override
    protected Object createValue() {
        String hostname;
        Alarm alarm;
        try {
            hostname = InetAddress.getLocalHost().getHostName();
            alarm = alarmNone();
        } catch (UnknownHostException ex) {
            hostname = "Unknown host";
            alarm = newAlarm(AlarmSeverity.INVALID, "Undefined");
        }
        if (!Objects.equals(hostname, previousValue)) {
            previousValue = hostname;
            return newVString(hostname, alarm, timeNow());
        } else {
            return null;
        }
    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.github.windbender</groupId>
	<artifactId>angular-dropwizard</artifactId>
	<version>1.0-SNAPSHOT</version>
	<name>angular-dropwizard</name>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.yammer.dropwizard</groupId>
			<artifactId>dropwizard-core</artifactId>
			<version>0.6.2</version>
		</dependency>
		<dependency>
			<groupId>com.yammer.dropwizard</groupId>
			<artifactId>dropwizard-auth</artifactId>
			<version>0.6.2</version>
		</dependency>
		<dependency>
			<groupId>com.bazaarvoice.dropwizard</groupId>
			<artifactId>dropwizard-configurable-assets-bundle</artifactId>
			<version>0.1.11</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>angular-dropwizard</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>

				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
				<inherited>true</inherited>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>1.6</version>
				<configuration>
					<createDependencyReducedPom>true</createDependencyReducedPom>
					<filters>
						<filter>
							<artifact>*:*</artifact>
							<excludes>
								<exclude>META-INF/*.SF</exclude>
								<exclude>META-INF/*.DSA</exclude>
								<exclude>META-INF/*.RSA</exclude>
							</excludes>
						</filter>
					</filters>
				</configuration>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<transformers>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass>com.github.windbender.RESTServer</mainClass>
								</transformer>
							</transformers>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<archive>
						<manifest>
							<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
						</manifest>
					</archive>
				</configuration>
			</plugin>
		</plugins>

	</build>
</project>


text:
var pull = require('pull-stream')
var through = require('through')
var toPull = require('../')

pull(
  pull.count(1000000),
  pull.map(function (e) {
    return e.toString()+'\n'
  }),
  toPull.sink(through())
)


text:
import React, { Component } from 'react';

export function GameOverScoreboard({ game }) {
  let message;
  let first;
  let second;
  let third;
  let fourth;
  let fifth;
  let information;

  function scoreboard() {
    first = `${game.globalScoreBoard.topScores.first.name}:
    ${game.globalScoreBoard.topScores.first.score}`;
    second = `${game.globalScoreBoard.topScores.second.name}:
    ${game.globalScoreBoard.topScores.second.score}`;
    third = `${game.globalScoreBoard.topScores.third.name}:
    ${game.globalScoreBoard.topScores.third.score}`;
    fourth = `${game.globalScoreBoard.topScores.fourth.name}:
    ${game.globalScoreBoard.topScores.fourth.score}`;
    fifth = `${game.globalScoreBoard.topScores.fifth.name}:
    ${game.globalScoreBoard.topScores.fifth.score}`;
  }

  if(!game.inGame && !game.newTopScore && game.landscape) {
    if(game.currentScore >= parseInt(game.topScore)){
      message = `WOW! You beat your old top score! ${game.currentScore}`;
      scoreboard();
    } else if(game.currentScore < parseInt(game.topScore)){
      message = `Your Score: ${game.currentScore}`;
      scoreboard();
    }

    information = (

{message}

Top Scoreboard

{first}

{second}

{third}

{fourth}

{fifth}

        <button className="startgame">
          try again
        </button>

    );
  }

  return (

      {information}

  );
}


text:
using System;

public class InvalidSongNameException : InvalidSongException
{
    private const string DefaultMessage = ExceptionMessages.InvalidSongNameException;

    public InvalidSongNameException() : base(DefaultMessage)
    {
    }
}


text:
layout: post
title: "Classes in Ruby"
date: 2015-11-29T00:00:00-06:00
---
In object-oriented programming, classes are essentially templates for creating new objects. They allow you to describe the basic attributes that members of a class should have, and enable you to establish modes of interaction for the class.

One way in which classes are very useful is that they allow you to create easily understandable representations of real-world objects in code. Let's take the example of a car. Here is how you would initialize a Car object in Ruby:

{% highlight ruby %}
class Car
attr_reader :make
attr_reader :model
attr_reader :year
def initialize(make, model, year)
  @make = make
  @model = model
  @year = year
end
end
{% endhighlight %}

What does this code do? It sets up a template for a car that we can then reuse. Our initialize method set up the required attributes for the car - make, model, and year. The attr_reader statement allows for quick and easy creation of methods for accessing these attributes of the car.

What was putting @ before the variable names all about, though? We were creating instance variables for the car object. Instance variables are stored in each individual instance of the object, so you can recall them every time you recall that object. If we kept them as local variables - without the @ - we would lose their values as soon as the initialize method finished, which wouldn't be very useful! Okay, let's see how we can interact with this Car object in practice after entering the code above:

{% highlight ruby %}
irb(main):011:0> my_miata = Car.new('Mazda', 'Miata', 2009)
=> #Car:0x007fcd531123a8 @make="Mazda", @model="Miata", @year=2009
{% endhighlight %}

What did this do? We created a new instance of the Car object and gave it a make (Mazda), model (Miata), and year (2009). Now we can use our attr_reader methods to look up these attributes of the car:

{% highlight ruby %}
irb(main):012:0> my_miata.make
=> "Mazda"
irb(main):013:0> my_miata.model
=> "Miata"
irb(main):014:0> my_miata.year
=> 2009
{% endhighlight %}

This kind of basic data initialization, storage, and retrieval is just scratching the surface of what you can do with objects. You can define methods for interaction with objects - think of things like turning the car on or off:

{% highlight ruby %}
class Car
  def turn_on
    @on = true
  end

  def turn_off
    @on = false
  end
end
{% endhighlight %}

or changing some kind of control on the car:

{% highlight ruby %}
class Car
attr_accessor :wipers_setting
end
{% endhighlight %}

As you can see, classes are an extremely powerful feature of Ruby and many other programming languages.