<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Autosuggest from 'react-autosuggest';

export default class ReactAutosuggest extends Component {
    constructor(props) {
        super(props);

        this.state = {
            value: "",
            // suggestions: this.props.suggestions
            suggestions: [ { value: "Testing 1" }, { value: "Testing 2" } ]
        }
    }

    onChange = (event, { newValue }) => {
        this.setState({
            value: newValue
        });
    }

    onSuggestionsFetchRequested =({ value }) => {
        if (value.match(new RegExp(this.props.regex))) {
            this.setState({
                // suggestions: this.props.suggestions
                suggestions: [ { value: "Testing 1" }, { value: "Testing 2" } ]
            });
        } else {
            this.setState({
                suggestions: []
            });
        }
    }

    onSuggestionsClearRequested = () => {
        this.setState({
            suggestions: []
        });
    }

    onSuggestionSelected = (event, { suggestion }) => {
        const newValue = this.state.value.replace(new RegExp(this.props.regex), "<<" + suggestion.value + ">>")
        this.setState({ value: newValue })
    }

    getSuggestionValue = (value) => {
        return this.state.value;
    }

    renderSuggestion = (suggestion) => (
            {suggestion.value}
    );

    render() {

        const inputProps = {
            placeholder: this.props.placeholder,
            value: this.state.value,
            onChange: this.onChange
        };

        return (
            <Autosuggest
                suggestions={this.state.suggestions}
                onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
                onSuggestionsClearRequested={this.onSuggestionsClearRequested}
                getSuggestionValue={this.getSuggestionValue}
                onSuggestionSelected={this.onSuggestionSelected}
                renderSuggestion={this.renderSuggestion}
                inputProps={inputProps}
                theme={theme}
            />
        );
    }
}

const theme = {
    container: {
        position: 'relative'
    },
    input: {
        width: 240,
        height: 15,
        paddingBottom: 5,
        fontFamily: 'Roboto, sans-serif',
        fontWeight: 300,
        fontSize: 16,
        border: 'none',
        borderBottom: '1px solid #aaa',
    },
    inputFocused: {
        outline: 'none',
        borderBottom: '1.5px solid #3e30c1',
        transformOrigin: '0 0 0'
    },
    inputOpen: {
        borderBottomLeftRadius: 0,
        borderBottomRightRadius: 0
    },
    suggestionsContainer: {
        display: 'none'
    },
    suggestionsContainerOpen: {
        display: 'block',
        position: 'absolute',
        top: 20,
        width: 240,
        border: '1px solid #aaa',
        backgroundColor: '#fff',
        fontFamily: 'Helvetica, sans-serif',
        fontWeight: 300,
        fontSize: 16,
        borderBottomLeftRadius: 4,
        borderBottomRightRadius: 4,
        zIndex: 2
    },
    suggestionsList: {
        margin: 0,
        padding: 0,
        listStyleType: 'none',
    },
    suggestion: {
        cursor: 'pointer',
        padding: '10px 20px'
    },
    suggestionHighlighted: {
        backgroundColor: '#ddd'
    }
};

ReactAutosuggest.propTypes = {
    suggestions: PropTypes.arrayOf(PropTypes.object).isRequired,
    regex: PropTypes.string.isRequired,
    placeholder: PropTypes.string.isRequired
}<commit_msg>ReactAutosuggest  component WIP<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Autosuggest from 'react-autosuggest';

export default class ReactAutosuggest extends Component {
    constructor(props) {
        super(props);

        this.state = {
            value: "",
            // suggestions: this.props.suggestions
            suggestions: [ { value: "Testing 1" }, { value: "Testing 2" } ]
        }
    }

    onChange = (event, { newValue }) => {
        this.setState({
            value: newValue
        });
    }

    onSuggestionsFetchRequested =({ value }) => {
        if (value.match(new RegExp(this.props.regex))) {
            this.setState({
                // suggestions: this.props.suggestions
                suggestions: [ { value: "Testing 1" }, { value: "Testing 2" } ]
            });
        } else {
            this.setState({
                suggestions: []
            });
        }
    }

    onSuggestionsClearRequested = () => {
        this.setState({
            suggestions: []
        });
    }

    onSuggestionSelected = (event, { suggestion }) => {
        const newValue = this.state.value.replace(new RegExp(this.props.regex), "<<" + suggestion.value + ">>")
        this.setState({ value: newValue })
    }

    getSuggestionValue = (value) => {
        return this.state.value;
    }

    renderSuggestion = (suggestion) => (
            {suggestion.value}
    );

    render() {

        const inputProps = {
            placeholder: this.props.placeholder,
            value: this.state.value,
            onChange: this.onChange
        };

        return (
            <Autosuggest
                suggestions={this.state.suggestions}
                onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
                onSuggestionsClearRequested={this.onSuggestionsClearRequested}
                getSuggestionValue={this.getSuggestionValue}
                onSuggestionSelected={this.onSuggestionSelected}
                renderSuggestion={this.renderSuggestion}
                inputProps={inputProps}
                theme={theme}
            />
        );
    }
}

const theme = {
    container: {
        position: 'relative'
    },
    input: {
        width: 240,
        height: 15,
        paddingBottom: 8,
        fontFamily: 'Roboto, sans-serif',
        fontWeight: 300,
        fontSize: 16,
        border: 'none',
        borderBottom: '1px solid #aaa',
    },
    inputFocused: {
        outline: 'none',
        borderBottom: '1.5px solid #3e30c1',
        // TODO: add transition animation
    },
    inputOpen: {
        borderBottomLeftRadius: 0,
        borderBottomRightRadius: 0
    },
    suggestionsContainer: {
        display: 'none'
    },
    suggestionsContainerOpen: {
        display: 'block',
        position: 'absolute',
        top: 25,
        width: 240,
        border: '1px solid #aaa',
        backgroundColor: '#fff',
        fontFamily: 'Helvetica, sans-serif',
        fontWeight: 300,
        fontSize: 16,
        borderBottomLeftRadius: 4,
        borderBottomRightRadius: 4,
        zIndex: 2
    },
    suggestionsList: {
        margin: 0,
        padding: 0,
        listStyleType: 'none',
    },
    suggestion: {
        cursor: 'pointer',
        padding: '10px 20px'
    },
    suggestionHighlighted: {
        backgroundColor: '#ddd'
    }
};

ReactAutosuggest.propTypes = {
    suggestions: PropTypes.arrayOf(PropTypes.object).isRequired,
    regex: PropTypes.string.isRequired,
    placeholder: PropTypes.string.isRequired
}<|endoftext|>


<commit_before>/**
 * Replace @ref fields and array elements with referenced object.  Recursively
 * traverse JSON object tree in two passes, once to record @id's of objects, and
 * a second pass to replace @ref fields with objects identified by @id fields.
 *
 * Copyright 2010 John DeRegnaucourt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function resolveRefs(jObj)
{
    var idsToObjs = [];

    // First pass, store all objects that have an @ID field, mapped to their instance (self)
    walk(jObj, idsToObjs);

    // Replace all @ref: objects with the object from the association above.
    substitute(null, null, jObj, idsToObjs);

    idsToObjs = null;
}

function walk(jObj, idsToObjs)
{
    for (var field in jObj)
    {
        var value = jObj[field];
        if (field == "@id")
        {
            idsToObjs[value] = jObj;
        }
        else if (typeof(value) == "object")
        {
            walk(value, idsToObjs);
        }
    }
}

function substitute(parent, fieldName, jObj, idsToObjs)
{
    for (var field in jObj)
    {
        var value = jObj[field];
        if (field == "@ref")
        {
            if (parent != null && fieldName != null)
            {
                parent[fieldName] = idsToObjs[jObj["@ref"]];
            }
        }
        else if (typeof(value) == "object")
        {
            substitute(jObj, field, value, idsToObjs);
        }
    }
}
<commit_msg>update jsonUtil.js to only look at keys on the object (no hidden enumeration or inherited fields)<commit_after>/**
 * Replace @ref fields and array elements with referenced object.  Recursively
 * traverse JSON object tree in two passes, once to record @id's of objects, and
 * a second pass to replace @ref fields with objects identified by @id fields.
 *
 * Copyright 2010-2015 John DeRegnaucourt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function resolveRefs(jObj)
{
    if (!jObj)
        return;

    var idsToObjs = [];

    // First pass, store all objects that have an @ID field, mapped to their instance (self)
    walk(jObj, idsToObjs);

    // Replace all @ref: objects with the object from the association above.
    substitute(null, null, jObj, idsToObjs);

    idsToObjs = null;
}

function walk(jObj, idsToObjs)
{
    if (!jObj)
        return;

    var keys = Object.keys(jObj); // will return an array of own properties

    for (var i = 0, len = keys.length; i < len; i++)
    {
        var field = keys[i];
        var value = jObj[field];

        if (!value)
            continue;

        if (field === "@id")
        {
            idsToObjs[value] = jObj;
        }
        else if (typeof(value) === "object")
        {
            walk(value, idsToObjs);
        }
    }
}

function substitute(parent, fieldName, jObj, idsToObjs)
{
    if (!jObj)
        return;

    var keys = Object.keys(jObj); // will return an array of own properties

    for (var i = 0, len = keys.length; i < len; i++)
    {
        var field = keys[i];
        var value = jObj[field];

        if (field === "@ref")
        {
            if (parent && fieldName)
            {
                parent[fieldName] = idsToObjs[jObj["@ref"]];
            }
        }
        else if (typeof(value) === "object")
        {
            substitute(jObj, field, value, idsToObjs);
        }
    }
}
<|endoftext|>


<commit_before>require([
"esri/map",
"esri/dijit/Geocoder",
"esri/graphic",
"esri/geometry/Point",
"esri/symbols/PictureMarkerSymbol",
"esri/InfoTemplate",
"esri/geometry/webMercatorUtils",
"dojo/dom",
"dojo/domReady!"
], function(
Map, Geocoder, Graphic, Point, PictureMarkerSymbol, InfoTemplate, webMercatorUtils, dom
) {

    var W3WKEY = '';

    // create a map
    var map = new Map("map", {
        basemap: "topo",
        center: [ 0, 40 ], //Centralish view of the world
        zoom: 3, // Zoomed out far (lower is further out)
        spatialReference: 4326 //WGS84
    });

    //Instance of the Geocoder widget here, assign it to search dom element
    var geocoder =  new Geocoder({
        arcgisGeocoder: {
           placeholder: "Type an address or a what3words (word.word.word)"
        },
        autoComplete: false,
        autoNavigate: false, //override autozoom to location (this is necessary to allow for custom geocoding functionality)
        highlightLocation: false, //stop automatic location marker placement
        map: map
    }, dom.byId("search"));

    // w3w Marker
    w3wMarker = new PictureMarkerSymbol("img/marker-icon-w3w.png", 38, 44);

    // On search
    geocoder.on("find-results", showLocation);
    geocoder.on("clear", function() { $(".esriGeocoder").css("border-color", "black"); } );

    //Reverse geocode URL and unchanging parameters
    var reverseGeocodeURL = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?"
    var distance = "&distance=200";
    var asJSON = "&outSR=&f=json";

    var check = ""

    function showLocation(evt) {

        console.log(evt);

        //Get the search box value
        var searchTerm = evt.target.value;

        var validTextAddress = evt.results.results.length > 0;

        // Check that there are two dots in the query and no spaces in the search term i.e. dogs.dogs.dogs or cats.cats.cats
        var w3wBool = ( ((searchTerm.split(".").length - 1)  === 2) &&
                               ((searchTerm.split(" ").length - 1) === 0) );

        // Set the resulting search object
        var searchObject = evt.results.results[0];

        // Only assign coordinates if there are actual results from the esri geocode
        if (validTextAddress) {
            console.log("Valid geocodable address");

            //webMercatorUtils allows us to convert from the Web Mercator projected coordinate system to WGS84 (a geographic coordinate system used by GPS).
            var searchGeometry = evt.results.results[0].feature.geometry;
            var coordinates = webMercatorUtils.webMercatorToGeographic(searchGeometry);
            var lng = coordinates.x;
            var lat = coordinates.y;
            var latlng = lat + "," + lng;
        }

        // Check if its a valid what 3 words format
        console.log("Search term is 3words: ", w3wBool);

        // If 3 words
         if (w3wBool) {
            console.log("what3words search term");

            var w3wParameters = {
                'key':	W3WKEY,
                'string':	searchTerm
            };

            $.post('http://api.what3words.com/w3w', w3wParameters, function(w3w) {

                //Check that it is a valid 3words there is an error in the return
                if (w3w.hasOwnProperty("error") === false) {
                    $(".esriGeocoder").css("border-color", "green");
                    console.log("Valid 3 words", w3w);

                    var w3wLng = w3w.position[1];
                    var w3wLat = w3w.position[0];

                    // Get the longitude and latitude of the 3 words, note the order!
                    var point = new Point(w3wLng, w3wLat);
                    var symbol = w3wMarker;
                    var graphic = new Graphic(point, symbol);

                    //Reverse geocode the address
                    var locationCoordinates = "location=" + w3wLng + "," + w3wLat;

                    $.get(reverseGeocodeURL + locationCoordinates + distance + asJSON, function(returnedAddress) {

                        // Clear any previous marker additions
                        map.graphics.clear();

                        console.log(returnedAddress);
                        response = $.parseJSON(returnedAddress);

                        addressText = writeAddress(response);

                        //Print address
                        console.log(addressText);

                        //Set the content of the popup
                        content = "
" + w3w.words[0] + "." + w3w.words[1] + "." + w3w.words[2] +  "

";

                        //Set the popup for the graphic through the maps infoWindow
                        map.infoWindow.setTitle("3 words");
                        map.infoWindow.setContent(content + addressText);

                        // We need to use the w3w coordinate points in longitude latitude format as esri geocoder ones will be incorrect!
                        w3wGeom = new Point(w3wLng, w3wLat);
                        w3wGraphic = new Graphic(w3wGeom, w3wMarker);

                        //Add the w3w marker to the page
                        map.graphics.add(w3wGraphic);

                        //Override the logic that zooms you to the address result and zoom to our 3 words.
                        map.centerAndZoom(w3wGeom, 13)

                        //Show infoWindow (the marker popup)
                        map.infoWindow.show(w3wGeom);

                        // Reset address text
                        addressText = "";

                    });
                }

                else {

                    console.log("Invalid w3w", w3w);
                    $(".esriGeocoder").css("border-color", "red");

                }
            });
         }

        // If normal address
        else {

            if (validTextAddress) {

                console.log("Address search term");
                $(".esriGeocoder").css("border-color", "green");

                w3wParameters = {
                    'key':	W3WKEY,
                    'position': latlng
                };

                $.post('http://api.what3words.com/position', w3wParameters, function(w3w) {

                    // Clear any previous marker additions
                    map.graphics.clear();
                    var point = new Point(lng, lat);
                    var symbol = new PictureMarkerSymbol("img/marker-icon-w3w.png", 32, 32);
                    var graphic = new Graphic(point, symbol);

                    // check if 2 spaces or 3 spaces and one is at the end
                    var spaces = searchTerm.split(" ").length - 1;
                    var lastchar = searchTerm.charAt(searchTerm.length - 1);
                    if ( spaces  === 2 || ( spaces  === 3 && lastchar === " ") )  {

                        console.log("two or three spaces in search terms");
                        // if at the end get rid of the end
                        if ( spaces  === 3 && lastchar === " ") {
                            console.log("removing final space");
                            searchTerm = searchTerm.slice(0, -1);
                        }

                        threeWords = searchTerm.replace(/ /g, '.').toLowerCase();
                        console.log("three words", threeWords);

                        w3wCheck = {
                            'key':	W3WKEY,
                            'string': threeWords
                        }

                        $.post('http://api.what3words.com/w3w', w3wCheck, function(check) {

                            console.log(check);

                            if (check.hasOwnProperty("error") === true) {

                               check = "If you were trying to do a what 3 words " + threeWords + "  is not a valid 3 words";
                                console.log("invalid w3", check);
                            }

                            else {

                                check = "If you were trying to do a what 3 words try: " + threeWords + "";
                                console.log("valid w3 to try", check);
                            }

                            //Set the content of the popup
                            content = "
" + w3w.words[0] + "." + w3w.words[1] + "." +  w3w.words[2] +  "

";

                            console.log("is check blank", check);
                            //Set the popup for the graphic through the maps infoWindow
                            map.infoWindow.setTitle("3 words");
                            map.infoWindow.setContent(content + " Geocoded Address:  " + searchObject.name + "

" + check );

                            //Add the w3w marker to the page
                            map.graphics.add(graphic);
                            map.centerAndZoom(point, 13)

                            //Show infoWindow (the marker popup)
                            map.infoWindow.show(graphic.geometry);
                        });
                    }

                    else {
                        //Set the popup for the graphic through the maps infoWindow
                        map.infoWindow.setTitle("3 words");
                        map.infoWindow.setContent(content + " Geocoded Address:  " + searchObject.name + "

" + check );

                        //Add the w3w marker to the page
                        map.graphics.add(graphic);
                        map.centerAndZoom(point, 13)

                        //Show infoWindow (the marker popup)
                        map.infoWindow.show(graphic.geometry);

                    }
                });
            }

            else {
                $(".esriGeocoder").css("border-color", "red");
            }

        } // End of normal address geocoding

        // Write address function
        function writeAddress(response) {
            console.log(response);
            if (response.hasOwnProperty("error") === false) {
                var addressObject = response.address;
                var addressKeys = Object.keys(addressObject);
                addressText = "Geocoded Address: ";

                for (var i = 0; i <= addressKeys.length - 1; i++) {
                    var key = addressKeys[i];
                    if (addressObject[key] !== null && addressKeys[i] !== "Loc_name" ) {
                     addressText = addressText + addressObject[key] + ", " ;
                    }
                }

                //Remove any uncessary characters
                if (addressText.slice(-2) === ", ") { addressText = addressText.slice(0, -2); }
            }

            else { var addressText = "Geocoded Address:  Couldn't geocode"; }

            return addressText;

        }
    }; //End of showLocation function

}); //End of JavaScript
<commit_msg>define content in reachable spot<commit_after>require([
"esri/map",
"esri/dijit/Geocoder",
"esri/graphic",
"esri/geometry/Point",
"esri/symbols/PictureMarkerSymbol",
"esri/InfoTemplate",
"esri/geometry/webMercatorUtils",
"dojo/dom",
"dojo/domReady!"
], function(
Map, Geocoder, Graphic, Point, PictureMarkerSymbol, InfoTemplate, webMercatorUtils, dom
) {

    var W3WKEY = '';
    var content = '';
    // create a map
    var map = new Map("map", {
        basemap: "topo",
        center: [ 0, 40 ], //Centralish view of the world
        zoom: 3, // Zoomed out far (lower is further out)
        spatialReference: 4326 //WGS84
    });

    //Instance of the Geocoder widget here, assign it to search dom element
    var geocoder =  new Geocoder({
        arcgisGeocoder: {
           placeholder: "Type an address or a what3words (word.word.word)"
        },
        autoComplete: false,
        autoNavigate: false, //override autozoom to location (this is necessary to allow for custom geocoding functionality)
        highlightLocation: false, //stop automatic location marker placement
        map: map
    }, dom.byId("search"));

    // w3w Marker
    w3wMarker = new PictureMarkerSymbol("img/marker-icon-w3w.png", 38, 44);

    // On search
    geocoder.on("find-results", showLocation);
    geocoder.on("clear", function() { $(".esriGeocoder").css("border-color", "black"); } );

    //Reverse geocode URL and unchanging parameters
    var reverseGeocodeURL = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?"
    var distance = "&distance=200";
    var asJSON = "&outSR=&f=json";

    var check = ""

    function showLocation(evt) {

        console.log(evt);

        //Get the search box value
        var searchTerm = evt.target.value;

        var validTextAddress = evt.results.results.length > 0;

        // Check that there are two dots in the query and no spaces in the search term i.e. dogs.dogs.dogs or cats.cats.cats
        var w3wBool = ( ((searchTerm.split(".").length - 1)  === 2) &&
                               ((searchTerm.split(" ").length - 1) === 0) );

        // Set the resulting search object
        var searchObject = evt.results.results[0];

        // Only assign coordinates if there are actual results from the esri geocode
        if (validTextAddress) {
            console.log("Valid geocodable address");

            //webMercatorUtils allows us to convert from the Web Mercator projected coordinate system to WGS84 (a geographic coordinate system used by GPS).
            var searchGeometry = evt.results.results[0].feature.geometry;
            var coordinates = webMercatorUtils.webMercatorToGeographic(searchGeometry);
            var lng = coordinates.x;
            var lat = coordinates.y;
            var latlng = lat + "," + lng;
        }

        // Check if its a valid what 3 words format
        console.log("Search term is 3words: ", w3wBool);

        // If 3 words
         if (w3wBool) {
            console.log("what3words search term");

            var w3wParameters = {
                'key':	W3WKEY,
                'string':	searchTerm
            };

            $.post('http://api.what3words.com/w3w', w3wParameters, function(w3w) {

                //Check that it is a valid 3words there is an error in the return
                if (w3w.hasOwnProperty("error") === false) {
                    $(".esriGeocoder").css("border-color", "green");
                    console.log("Valid 3 words", w3w);

                    var w3wLng = w3w.position[1];
                    var w3wLat = w3w.position[0];

                    // Get the longitude and latitude of the 3 words, note the order!
                    var point = new Point(w3wLng, w3wLat);
                    var symbol = w3wMarker;
                    var graphic = new Graphic(point, symbol);

                    //Reverse geocode the address
                    var locationCoordinates = "location=" + w3wLng + "," + w3wLat;

                    $.get(reverseGeocodeURL + locationCoordinates + distance + asJSON, function(returnedAddress) {

                        // Clear any previous marker additions
                        map.graphics.clear();

                        console.log(returnedAddress);
                        response = $.parseJSON(returnedAddress);

                        addressText = writeAddress(response);

                        //Print address
                        console.log(addressText);

                        //Set the content of the popup
                        content = "
" + w3w.words[0] + "." + w3w.words[1] + "." + w3w.words[2] +  "

";

                        //Set the popup for the graphic through the maps infoWindow
                        map.infoWindow.setTitle("3 words");
                        map.infoWindow.setContent(content + addressText);

                        // We need to use the w3w coordinate points in longitude latitude format as esri geocoder ones will be incorrect!
                        w3wGeom = new Point(w3wLng, w3wLat);
                        w3wGraphic = new Graphic(w3wGeom, w3wMarker);

                        //Add the w3w marker to the page
                        map.graphics.add(w3wGraphic);

                        //Override the logic that zooms you to the address result and zoom to our 3 words.
                        map.centerAndZoom(w3wGeom, 13)

                        //Show infoWindow (the marker popup)
                        map.infoWindow.show(w3wGeom);

                        // Reset address text
                        addressText = "";

                    });
                }

                else {

                    console.log("Invalid w3w", w3w);
                    $(".esriGeocoder").css("border-color", "red");

                }
            });
         }

        // If normal address
        else {

            if (validTextAddress) {

                console.log("Address search term");
                $(".esriGeocoder").css("border-color", "green");

                w3wParameters = {
                    'key':	W3WKEY,
                    'position': latlng
                };

                $.post('http://api.what3words.com/position', w3wParameters, function(w3w) {

                    // Clear any previous marker additions
                    map.graphics.clear();
                    var point = new Point(lng, lat);
                    var symbol = new PictureMarkerSymbol("img/marker-icon-w3w.png", 32, 32);
                    var graphic = new Graphic(point, symbol);

                    // check if 2 spaces or 3 spaces and one is at the end
                    var spaces = searchTerm.split(" ").length - 1;
                    var lastchar = searchTerm.charAt(searchTerm.length - 1);
                    if ( spaces  === 2 || ( spaces  === 3 && lastchar === " ") )  {

                        console.log("two or three spaces in search terms");
                        // if at the end get rid of the end
                        if ( spaces  === 3 && lastchar === " ") {
                            console.log("removing final space");
                            searchTerm = searchTerm.slice(0, -1);
                        }

                        threeWords = searchTerm.replace(/ /g, '.').toLowerCase();
                        console.log("three words", threeWords);

                        w3wCheck = {
                            'key':	W3WKEY,
                            'string': threeWords
                        }

                        $.post('http://api.what3words.com/w3w', w3wCheck, function(check) {

                            console.log(check);

                            if (check.hasOwnProperty("error") === true) {

                               check = "If you were trying to do a what 3 words " + threeWords + "  is not a valid 3 words";
                                console.log("invalid w3", check);
                            }

                            else {

                                check = "If you were trying to do a what 3 words try: " + threeWords + "";
                                console.log("valid w3 to try", check);
                            }

                            //Set the content of the popup
                            content = "
" + w3w.words[0] + "." + w3w.words[1] + "." +  w3w.words[2] +  "

";

                            console.log("is check blank", check);
                            //Set the popup for the graphic through the maps infoWindow
                            map.infoWindow.setTitle("3 words");
                            map.infoWindow.setContent(content + " Geocoded Address:  " + searchObject.name + "

" + check );

                            //Add the w3w marker to the page
                            map.graphics.add(graphic);
                            map.centerAndZoom(point, 13)

                            //Show infoWindow (the marker popup)
                            map.infoWindow.show(graphic.geometry);
                        });
                    }

                    else {
                        //Set the popup for the graphic through the maps infoWindow
                        map.infoWindow.setTitle("3 words");
                        map.infoWindow.setContent(content + " Geocoded Address:  " + searchObject.name + "

" + check );

                        //Add the w3w marker to the page
                        map.graphics.add(graphic);
                        map.centerAndZoom(point, 13)

                        //Show infoWindow (the marker popup)
                        map.infoWindow.show(graphic.geometry);

                    }
                });
            }

            else {
                $(".esriGeocoder").css("border-color", "red");
            }

        } // End of normal address geocoding

        // Write address function
        function writeAddress(response) {
            console.log(response);
            if (response.hasOwnProperty("error") === false) {
                var addressObject = response.address;
                var addressKeys = Object.keys(addressObject);
                addressText = "Geocoded Address: ";

                for (var i = 0; i <= addressKeys.length - 1; i++) {
                    var key = addressKeys[i];
                    if (addressObject[key] !== null && addressKeys[i] !== "Loc_name" ) {
                     addressText = addressText + addressObject[key] + ", " ;
                    }
                }

                //Remove any uncessary characters
                if (addressText.slice(-2) === ", ") { addressText = addressText.slice(0, -2); }
            }

            else { var addressText = "Geocoded Address:  Couldn't geocode"; }

            return addressText;

        }
    }; //End of showLocation function

}); //End of JavaScript
<|endoftext|>


<commit_before>// Person 1

// As a user, I want to take two lists of numbers, one with
// odd number of elements and the other with even number of elements,
// and calculate the sum, mean, and median for each list.

// One function called "sum" should calculate the sum for list 1 and the
// sum for list 2
// One function called "mean" should calculate the average (with decimal places)
// for list 1 and the average for list 2
// One function called "median" should calculate the median
// (with decimal places) for list 1 and the median for list 2

// Example:
// list1: 1, 2, 3, 4, 5, 5, 7
// list2: 4, 4, 5, 5, 6, 6, 6, 7
// The sum function should return 27 for list1 and 43 for list2.

//Initial solution

function sum(oddArray,evenArray){
  var sum1=0;
  var sum2=0;
  for(var i=0; i<oddArray.length; i++){
  var sum1=sum1+oddArray[i];
};
  for (var j=0; j<evenArray.length; j++){
  var sum2=sum2+evenArray[j];
};
  console.log(sum1);
  console.log(sum2);
};

function mean(oddArray,evenArray){
  var sum1=0;
  var sum2=0;
  var mean1=0;
  var mean2=0;
  for(var i=0; i<oddArray.length; i++){
  var sum1=sum1+oddArray[i];
};
  for (var j=0; j<evenArray.length; j++){
  var sum2=sum2+evenArray[j];
};
  mean1=sum1/oddArray.length;
  console.log(mean1);
  mean2=sum2/evenArray.length;
  console.log(mean2);
};

function median(oddArray,evenArray){
  var medn1;
  var medn2;
  var positionOdd;
  var x;
  var y;
  oddArray.sort;
  positionOdd=(oddArray.length-1)/2;
  medn1=oddArray[positionOdd]
  console.log(medn1);

  evenArray.sort;
  x=evenArray.length/2;
  y=x-1;
  medn2=(evenArray[x]+evenArray[y])/2
  console.log(medn2);
};

<commit_msg>Modify solution to return values<commit_after>// Person 1

// As a user, I want to take two lists of numbers, one with
// odd number of elements and the other with even number of elements,
// and calculate the sum, mean, and median for each list.

// One function called "sum" should calculate the sum for list 1 and the
// sum for list 2
// One function called "mean" should calculate the average (with decimal places)
// for list 1 and the average for list 2
// One function called "median" should calculate the median
// (with decimal places) for list 1 and the median for list 2

// Example:
// list1: 1, 2, 3, 4, 5, 5, 7
// list2: 4, 4, 5, 5, 6, 6, 6, 7
// The sum function should return 27 for list1 and 43 for list2.

//Initial solution

function sum(oddArray,evenArray){
  var sum1=0;
  var sum2=0;
  for(var i=0; i<oddArray.length; i++){
  var sum1=sum1+oddArray[i];
};
  for (var j=0; j<evenArray.length; j++){
  var sum2=sum2+evenArray[j];
};
  console.log(sum1);
  console.log(sum2);
  return sum1;
  return sum2;
};

function mean(oddArray,evenArray){
  var sum1=0;
  var sum2=0;
  var mean1=0;
  var mean2=0;
  for(var i=0; i<oddArray.length; i++){
  var sum1=sum1+oddArray[i];
};
  for (var j=0; j<evenArray.length; j++){
  var sum2=sum2+evenArray[j];
};
  mean1=sum1/oddArray.length;
  console.log(mean1);
  mean2=sum2/evenArray.length;
  console.log(mean2);
  return mean1;
  return mean2;
};

function median(oddArray,evenArray){
  var medn1;
  var medn2;
  var positionOdd;
  var x;
  var y;
  oddArray.sort;
  positionOdd=(oddArray.length-1)/2;
  medn1=oddArray[positionOdd]
  console.log(medn1);

  evenArray.sort;
  x=evenArray.length/2;
  y=x-1;
  medn2=(evenArray[x]+evenArray[y])/2
  console.log(medn2);
  return medn1;
  return medn2;
};

<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100 */
/*global require, applicationContext */

(function () {
  "use strict";
  var FoxxGenerator = require('./foxx_generator').Generator,
    generator;

  generator = new FoxxGenerator('example', {
    mediaType: 'application/vnd.api+json',
    applicationContext: applicationContext,
  });

  generator.defineTransition('asignee', {
    description: 'Get the person this object is assigned to',
    to: 'one',
  }).inverseTransition('assigned', {
    description: 'Get all objects that are assigned to this person',
    to: 'many'
  });

  generator.addState('person', {
    type: 'entity',

    attributes: {
      name: { type: 'string', required: true }
    },

    transitions: [
      { to: 'people', via: 'container' },
      { to: 'todo', via: 'assigned' }
    ]
  });

  generator.addState('todo', {
    type: 'entity',

    attributes: {
      // Title of the state
      title: { type: 'string', required: true },

      // User ID of the person this is assigned to
      asignee: { type: 'string' }
    },

    transitions: [
      { to: 'todos', via: 'container' },
      { to: 'person', via: 'asignee' }
    ]
  });

  generator.addState('todos', {
    type: 'repository',

    transitions: [
      { to: 'todo', via: 'element' }
    ]
  });

  generator.addState('people', {
    type: 'repository',

    transitions: [
      { to: 'person', via: 'element' }
    ]
  });

  generator.generate();
}());
<commit_msg>The entities are parameterized<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100 */
/*global require, applicationContext */

(function () {
  "use strict";
  var FoxxGenerator = require('./foxx_generator').Generator,
    generator;

  generator = new FoxxGenerator('example', {
    mediaType: 'application/vnd.api+json',
    applicationContext: applicationContext,
  });

  generator.defineTransition('asignee', {
    description: 'Get the person this object is assigned to',
    to: 'one',
  }).inverseTransition('assigned', {
    description: 'Get all objects that are assigned to this person',
    to: 'many'
  });

  generator.addState('person', {
    type: 'entity',
    parameterized: true,

    attributes: {
      name: { type: 'string', required: true }
    },

    transitions: [
      { to: 'people', via: 'container' },
      { to: 'todo', via: 'assigned' }
    ]
  });

  generator.addState('todo', {
    type: 'entity',
    parameterized: true,

    attributes: {
      // Title of the state
      title: { type: 'string', required: true },

      // User ID of the person this is assigned to
      asignee: { type: 'string' }
    },

    transitions: [
      { to: 'todos', via: 'container' },
      { to: 'person', via: 'asignee' }
    ]
  });

  generator.addState('todos', {
    type: 'repository',

    transitions: [
      { to: 'todo', via: 'element' }
    ]
  });

  generator.addState('people', {
    type: 'repository',

    transitions: [
      { to: 'person', via: 'element' }
    ]
  });

  generator.generate();
}());
<|endoftext|>


<commit_before>/**
 * dependencies
 */

var _           = require('lodash'),
    Marionette  = require('backbone.marionette'),
    $           = require('jquery');

/**
 * super view constructor
 */

var Super = Marionette.ItemView;

/**
 * ChapterBookView definition
 *
 * @help http://marionettejs.com/docs/v2.4.7/marionette.itemview.html
 */

var ChapterBookView = Super.extend({

  /**
   * handlebars pre-compiled template
   */

  template: require('../templates/chapter-book'),

  /**
   * event bindings for view's collection
   */

  collectionEvents: {
    'add': 'addPage'
  },

  /**
   * init internal parameters and start events listening
   */

  initialize: function() {

    // require jQuery dependencies
    require('../assets/js/jquery.easing.1.3.js');
    require('../assets/js/jquery.booklet.latest.js');

    // load chapter's page
    this.model.loadPages();

    // listen for window resizing
    $(window).on('resize', _.bind(this.onWindowResize, this));

    // listen keyboard
    $('body').on('keyup', _.bind(this.onKeyUp, this));

  },

  /**
   * triggered on view destruction but before DOM destruction
   */

  onBeforeDestroy: function() {

    // destroy booklet instance
    if (this.book) this.book.booklet('destroy');

    // stop events listening
    $(window).off('resize', _.bind(this.onWindowResize, this));

    // stop keyboard listening
    $('body').off('keyup', _.bind(this.onKeyUp, this));

  },

  /**
   * the results of the data serialization will be passed to the template
   *
   * @return {Object}
   */

  serializeData: function() {

    // get base model data
    var data = this.model.toJSON();

    // add collection data
    data.items = this.collection.toJSON();

    // return data object
    return data;

  },

  /**
   * render chapter's book
   */

  onRender: function() {

    // do not render book if there's no pages
    if (this.collection.length <= 0) return;

    // create book component
    this.book = this.$el.find('#book').booklet({

      // default dimensions
      width: 400,
      height: 300,

      // direction of the overall page organization
      direction: this.model.getFirst('pageDirection'),

      // speed of the transition between pages in milliseconds
      speed: 500,

      // padding added to each page wrapper
      pagePadding: 0,

      // display page numbers on each page
      pageNumbers: false,

      // disable keyboard bindings
      keyboard: false,

      // this event triggers after pages have finished turning
      change: _.bind(this.onPageChange, this)

    });

  },

  /**
   * add page to rendered book
   *
   * @param {PageModel} page
   */

  addPage: function(page) {

    // create new book if not defined
    if (!this.book) return this.render();

    // get template function
    var template = require('../templates/chapter-bookPage');

    // create DOM element
    var $page = $(template(page.toJSON()));

    // get page index
    var index = this.collection.findIndex(page.pick('id'));

    // add page to book
    this.book.booklet('add', index, $page);

    // refresh book size
    this.refreshBookSize();

  },

  /**
   * callback after book's page load
   *
   * @param {*} e                   jQuery event object
   * @param {Object} data
   * @param {Object} data.options   booklet options
   * @param {Number} data.index     zero-based index of the currently visible page spread
   * @param {Array} [data.pages]    an array of elements, the two currently visible pages
   * @param {*} [data.page]         element, the page that was either just added or just removed
   */

  onPageChange: function(e, data) {

    // this instance
    var self = this;

    // save rendered images internally
    this.images = _.map(data.pages, function(el) {

      // get jquery element
      var $img = $(el).find('img');

      // get raw DOM element
      var img = $img.get(0);

      // ensure image element
      if (!img) return;

      // check image loading status
      if (img.naturalWidth === 0) {

        // bind image loading event
        $img.one('load', _.bind(self.refreshBookSize, self));

      }

      // return raw <img> element
      return img;

    });

    // refresh book dimensions
    this.refreshBookSize();

  },

  /**
   * get image's ratio
   *
   * @param {*} img       <img> DOM element
   * @return {Number}
   */

  getRatio: function(img) {

    return _.get(img, 'naturalWidth') / _.get(img, 'naturalHeight');

  },

  /**
   * refresh book dimensions
   */

  refreshBookSize: _.debounce(function() {

    // ensure book instance
    if (!this.book) return;

    // link to this instance
    var self = this;

    // get the image with smallest ration (height > width)
    var img = _.reduce(this.images, function(result, img) {

      // if result is not defined then return
      if (!result) return img;

      // check witch image has smallest ratio
      if (self.getRatio(img) < self.getRatio(result)) {
        return img;
      } else {
        return result;
      }

    });

    // real image width
    var imgWidth = _.get(img, 'naturalWidth');

    // real image height
    var imgHeight = _.get(img, 'naturalHeight');

    // jQuery header
    var $header = $('header');

    // jQuery window
    var $window = $(window);

    // max possible width for this view
    var viewWidth = this.$el.width();

    // max possible height for view
    var viewHeight = $window.height() - $header.height() - 75;

    // calculate book width
    var bookWidth = _.round((imgWidth * viewHeight) / imgHeight) * 2;

    // ensure that image will not overflow
    if (bookWidth > viewWidth) bookWidth = viewWidth;

    // refresh book dimension
    this.book.booklet('option', {
      width: bookWidth,
      height: viewHeight
    });

  }, 250),

  /**
   * triggered on window resize
   */

  onWindowResize: function() {

    // refresh book size
    this.refreshBookSize();

  },

  /**
   * keyboard keys bindings
   *
   * @param {*} e   DOM event object
   */

  onKeyUp: function(e) {

    // ensure booklet instance
    if (!this.book) return;

    switch (e.which) { // e.which >> keyCode

      case 37: // left arrow
        this.book.booklet('prev'); break;

      case 39: // right arrow
        this.book.booklet('next'); break;

    }

  }

});

/**
 * exports constructor
 */

module.exports = ChapterBookView;
<commit_msg>fix missing events deregistration<commit_after>/**
 * dependencies
 */

var _           = require('lodash'),
    Marionette  = require('backbone.marionette'),
    $           = require('jquery');

/**
 * super view constructor
 */

var Super = Marionette.ItemView;

/**
 * ChapterBookView definition
 *
 * @help http://marionettejs.com/docs/v2.4.7/marionette.itemview.html
 */

var ChapterBookView = Super.extend({

  /**
   * handlebars pre-compiled template
   */

  template: require('../templates/chapter-book'),

  /**
   * event bindings for view's collection
   */

  collectionEvents: {
    'add': 'addPage'
  },

  /**
   * init internal parameters and start events listening
   */

  initialize: function() {

    // require jQuery dependencies
    require('../assets/js/jquery.easing.1.3.js');
    require('../assets/js/jquery.booklet.latest.js');

    // load chapter's page
    this.model.loadPages();

    // force function context
    this.onWindowResize = _.bind(this.onWindowResize, this);

    // listen for window resizing
    $(window).on('resize', this.onWindowResize);

    // force function context
    this.onKeyUp = _.bind(this.onKeyUp, this);

    // listen keyboard
    $('body').on('keyup', this.onKeyUp);

  },

  /**
   * triggered on view destruction but before DOM destruction
   */

  onBeforeDestroy: function() {

    // destroy booklet instance
    if (this.book) this.book.booklet('destroy');

    // stop events listening
    $(window).off('resize', this.onWindowResize);

    // stop keyboard listening
    $('body').off('keyup', this.onKeyUp);

  },

  /**
   * the results of the data serialization will be passed to the template
   *
   * @return {Object}
   */

  serializeData: function() {

    // get base model data
    var data = this.model.toJSON();

    // add collection data
    data.items = this.collection.toJSON();

    // return data object
    return data;

  },

  /**
   * render chapter's book
   */

  onRender: function() {

    // do not render book if there's no pages
    if (this.collection.length <= 0) return;

    // create book component
    this.book = this.$el.find('#book').booklet({

      // default dimensions
      width: 400,
      height: 300,

      // direction of the overall page organization
      direction: this.model.getFirst('pageDirection'),

      // speed of the transition between pages in milliseconds
      speed: 500,

      // padding added to each page wrapper
      pagePadding: 0,

      // display page numbers on each page
      pageNumbers: false,

      // disable keyboard bindings
      keyboard: false,

      // this event triggers after pages have finished turning
      change: _.bind(this.onPageChange, this)

    });

  },

  /**
   * add page to rendered book
   *
   * @param {PageModel} page
   */

  addPage: function(page) {

    // create new book if not defined
    if (!this.book) return this.render();

    // get template function
    var template = require('../templates/chapter-bookPage');

    // create DOM element
    var $page = $(template(page.toJSON()));

    // get page index
    var index = this.collection.findIndex(page.pick('id'));

    // add page to book
    this.book.booklet('add', index, $page);

    // refresh book size
    this.refreshBookSize();

  },

  /**
   * callback after book's page load
   *
   * @param {*} e                   jQuery event object
   * @param {Object} data
   * @param {Object} data.options   booklet options
   * @param {Number} data.index     zero-based index of the currently visible page spread
   * @param {Array} [data.pages]    an array of elements, the two currently visible pages
   * @param {*} [data.page]         element, the page that was either just added or just removed
   */

  onPageChange: function(e, data) {

    // this instance
    var self = this;

    // save rendered images internally
    this.images = _.map(data.pages, function(el) {

      // get jquery element
      var $img = $(el).find('img');

      // get raw DOM element
      var img = $img.get(0);

      // ensure image element
      if (!img) return;

      // check image loading status
      if (img.naturalWidth === 0) {

        // bind image loading event
        $img.one('load', _.bind(self.refreshBookSize, self));

      }

      // return raw <img> element
      return img;

    });

    // refresh book dimensions
    this.refreshBookSize();

  },

  /**
   * get image's ratio
   *
   * @param {*} img       <img> DOM element
   * @return {Number}
   */

  getRatio: function(img) {

    return _.get(img, 'naturalWidth') / _.get(img, 'naturalHeight');

  },

  /**
   * refresh book dimensions
   */

  refreshBookSize: _.debounce(function() {

    // ensure book instance
    if (!this.book) return;

    // link to this instance
    var self = this;

    // get the image with smallest ration (height > width)
    var img = _.reduce(this.images, function(result, img) {

      // if result is not defined then return
      if (!result) return img;

      // check witch image has smallest ratio
      if (self.getRatio(img) < self.getRatio(result)) {
        return img;
      } else {
        return result;
      }

    });

    // real image width
    var imgWidth = _.get(img, 'naturalWidth');

    // real image height
    var imgHeight = _.get(img, 'naturalHeight');

    // jQuery header
    var $header = $('header');

    // jQuery window
    var $window = $(window);

    // max possible width for this view
    var viewWidth = this.$el.width();

    // max possible height for view
    var viewHeight = $window.height() - $header.height() - 75;

    // calculate book width
    var bookWidth = _.round((imgWidth * viewHeight) / imgHeight) * 2;

    // ensure that image will not overflow
    if (bookWidth > viewWidth) bookWidth = viewWidth;

    // refresh book dimension
    this.book.booklet('option', {
      width: bookWidth,
      height: viewHeight
    });

  }, 250),

  /**
   * triggered on window resize
   */

  onWindowResize: function() {

    // refresh book size
    this.refreshBookSize();

  },

  /**
   * keyboard keys bindings
   *
   * @param {*} e   DOM event object
   */

  onKeyUp: function(e) {

    // ensure booklet instance
    if (!this.book) return;

    switch (e.which) { // e.which >> keyCode

      case 37: // left arrow
        this.book.booklet('prev'); break;

      case 39: // right arrow
        this.book.booklet('next'); break;

    }

  }

});

/**
 * exports constructor
 */

module.exports = ChapterBookView;
<|endoftext|>


<commit_before>// Constants
var MEM_SIZE = 0x2000;

// Registers and memory
var PC 		= 0,
	REG		= new Uint32Array(8),
	STAT	= 'AOK',
	MEMORY 	= new Uint8Array(MEM_SIZE),
	SF = 0, ZF = 0, OF = 0,
	ERR = '';

// Bounds check the register array
function getRegister (idx) {
	if (idx < 0 || idx > 8) {
		STAT = 'INS';
		throw new Error('Invalid register ID: 0x' + idx.toString(16));
	}
	return REG[idx];
}

// Uint32Arrays are not actually arrays
Uint8Array.prototype.slice = function () {
	return Array.prototype.slice.apply(this, arguments);
}

// Print
function print (x) {
	console.log(x);
}

// Reset
function RESET() {
	PC 	= 0;
	REG	= new Uint32Array(8);
	STAT = 'AOK';
	SF = 0; ZF = 0; OF = 0;
	ERR = '';
}

// Load
function LD (addr, mem) {
	mem = mem || MEMORY;
	var result;
	if (addr < 0 || addr + 4 > MEM_SIZE) {
		STAT = 'ADR';
		throw new Error("Invalid address 0x" + addr.toString(16));
	}
	result  = mem[addr];
	result |= mem[addr + 1] << 8;
	result |= mem[addr + 2] << 16;
	result |= mem[addr + 3] << 24;
	return result;
}

// Store
function ST(addr, data, bytes){
	var result, i;
	if (addr < 0 || addr + bytes > MEM_SIZE) {
		STAT = 'ADR';
		throw new Error("Invalid address 0x" + addr.toString(16));
	}
	if (typeof bytes === 'undefined') {
		bytes = Math.ceil(Math.log(data + 1) / Math.log(16) / 2);
	}
	for (i = 0; i < bytes; i++){
		MEMORY[addr + i] = data & 0xFF;
		data = data >> 8;
	}
	return addr;
}

// Decode instruction
function DECODE (bytearr) {
	var args = {
			icode: 	bytearr[0] >> 4,
			fn: 	bytearr[0] & 0x0F
		},
		len = bytearr.length;

	if (len > 1) {
		args['rA'] = (bytearr[1] >> 4) & 0x0F;
		args['rB'] = bytearr[1] & 0x0F;
	}
	if (len === 5) {
		var temp = bytearr[1];
		temp |= bytearr[2] << 8;
		temp |= bytearr[3] << 16;
		temp |= bytearr[4] << 24;
		args['Dest'] = temp;
	} else if (len === 6) {
		var temp = bytearr[2];
		temp |= bytearr[3] << 8;
		temp |= bytearr[4] << 16;
		temp |= bytearr[5] << 24;
		args['D'] = temp;
		args['V'] = temp;
	}
	return args;
}

function getRegCode (num) {
	var code = num2reg.indexOf(num);
	if (code === -1)
		throw new Error('Not a register: "' + num + '"');
	else
		return code.toString(16);
}

function evalArgs(list, args, symbols){
	var item, result = {};
	for (i in list) {
		item = list[i];
		if (item === 'rA') {
			result['rA'] = getRegCode(args[i]);
		}
		else if (item === 'rB') {
			result['rB'] = getRegCode(args[i]);
		}
		else if (item === 'V' || item === 'D') {
			if (symbols.hasOwnProperty(args[i])) {
				result['V'] = toBigEndian(padHex(symbols[args[i]], 8));
				result['D'] = result['V'];
			} else {
				try {
					result['V'] = toBigEndian(padHex(parseNumberLiteral(args[i].replace('$', '')) >>> 0));
				} catch (e) {
					// Use 'not a symbol' instead of the more cryptic 'not a number'
					throw new Error('Undefined symbol: ' + args[i]);
				}
				result['D'] = result['V'];
			}
		} else if (item === 'Dest') {
			try {
				result['Dest'] = toBigEndian(padHex(symbols[args[i]].toString(16), 8));
			} catch (e) {
				throw new Error('Undefined symbol: ' + args[i]);
			}
		} else if (item === 'D(rB)') {
			result['D'] = toBigEndian(padHex(parseNumberLiteral(args[i].replace(/\(.*/, '')) >>> 0, 8));
			result['rB'] = getRegCode(args[i].replace(/^.*\((.*)\)/, '$1'));
		}
	}
	return result;
}

function ENCODE(instr, symbols) {
	var result = '',
		args = [],
		vars = {},
		icode;

	instr = instr.replace(/\s*,\s*/i, ',');
	args = instr.split(' ');
	instr = args.splice(0, 1)[0];
	args = args[0] ? args[0].split(',') : new Array();

	vars = evalArgs(SYNTAX[instr], args, symbols);
	icode = inst2num[instr];
	if (inst2fn.hasOwnProperty(instr)) {
		vars['fn'] = inst2fn[instr];
	}

	if (icode in ASSEM) {
		result = ASSEM[icode].call(vars);
	} else {
		throw new Error('Invalid instruction "' + instr + '"');
	}
	return result;
}

// Remove comments and fix spacing in code
function normalizeSource (lines) {
	_.each(lines, function (line, i) {
		line = line.replace(/#.*/gi, '');
		line = line.replace(/\/\*.*\*\//gi, '');
		line = line.replace(/^\s+/gi, '');
		line = line.replace(/\s+$/gi, '');
		line = line.replace(/\s+/gi, ' ');
		lines[i] = line;
	});
}

function ASSEMBLE (raw, errorsOnly) {
	errorsOnly = !!errorsOnly;

	var lines = raw.split('\n'), line,
		symbols = {},
		result = new Array(lines.length),
		inst, icode,
		sym, next = 0,
		counter = 0;
		raw = raw.split('\n'),
		errors = [];

	// Clean up raw e.g. remove comments, fix spacing
	normalizeSource(lines);

	// Last line must be blank in Linux simulator
	if (lines[lines.length - 1].trim() !== '')
		errors.push([lines.length, 'Last line must be blank.']);

	// Create symbol table and mark memory addresses
	_.each(lines, function (line, i) {
		result[i] = ['', '', raw[i]];

		// Ignore empty lines
		if (line === '')
			return;

		// Add line number
		result[i][0] = ['0x' + padHex(counter, 4)];

		// Look for symbol and add to symbols
		sym = line.match(/(^.*?):/i);
		if (sym) {
			symbols[sym[1]] = counter;
			// Delete symbol from line
			lines[i] = line = line.replace(/^.*?:\s*/i, '');
		}

		// Look for directive
		dir = line.match(/(^\..*?) (.*)/i);
		if (dir) {
			if (dir[1] === '.pos') {
				try {
					counter = parseNumberLiteral(dir[2]);
				} catch (e) {
					errors.push([i + 1, e.message]);
				}
			} else if (dir[1] === '.align') {
				try {
					var alignTo = parseNumberLiteral(dir[2]);
				} catch (e) {
					errors.push([i + 1, e.message]);
				}
				counter = Math.ceil(counter / alignTo) * alignTo;
			} else if (dir[1] === '.long') {
				counter += 4;
			} else {
				errors.push([i + 1, 'Unknown directive: ' + dir[1]]);
			}
		}

		// Move counter
		inst = line.match(/(^[a-z]+)/i);
		if (inst) {
			icode = inst2num[inst[1]];
			counter += INSTRUCTION_LEN[icode];
		}
	});

	// Assemble instructions and long directives
	_.each(lines, function (line, i) {
		// Ignore empty lines
		if (line.trim() === '')
			return;

		// Long directives
		dir = line.match(/^\.long (.*)/i);
		if (dir) {
			var value;
			try {
				// Try to parse the value as a number literal first...
				value = parseNumberLiteral(dir[1]);
			} catch (e) {
				// ...and if that fails, try to find it in the symbol table
				if (symbols.hasOwnProperty(dir[1]))
					value = symbols[dir[1]];
				else
					errors.push([i + 1, 'Error while parsing .long directive: undefined symbol ' + dir[1]]);
			}
			result[i][1] = toBigEndian(padHex(value >>> 0, 8));
			counter += 4;
			return;
		}

		// Ignore other directives
		if (line[0] === '.')
			return;

		// Instructions
		inst = line.match(/^([a-z]+)(.*)/i);
		if (inst) {
			try {
				result[i][1] = ENCODE(line, symbols);
			} catch (e) {
				errors.push([i + 1, e.message]);
			}
		}
	});

	if (errorsOnly)
		return { errors: errors }

	var objectCode = _.map(result, function (line) {
		// 0xXXXX: XXXXXX...
		var compiledPart = '  ';
		if (line[0].length)
			compiledPart += line[0] + ': ' + line[1];

		// pad to fit 22 characters
		var padding = new Array(24 - compiledPart.length).join(' ');

		return compiledPart + padding + '| ' + line[2];
	}).join('\n');

	return {
		obj: objectCode,
		errors: errors
	}
}

// Initialize the VM with some object code
function INIT (obj) {
	MEMORY = toByteArray(obj);
	STAT = 'AOK';
	ERR = '';
	RESET();
}

var STEP_INTERVAL = null, RUN_DONE_CALLBACK;

// Run 256 instructions
function RUN_STEP () {
	for (var i = 0; i < 256; i++) {
		if (PC < MEM_SIZE && STAT === 'AOK')
			STEP();
		else {
			PAUSE();
			break;
		}
	}
}

// Returns true if the machine is currently running
function IS_RUNNING () {
	return STEP_INTERVAL !== null;
}

// Stops machine execution.
function PAUSE () {
	clearInterval(STEP_INTERVAL);
	STEP_INTERVAL = null;
	if (STAT === 'AOK')
		STAT = 'DBG';
	if (RUN_DONE_CALLBACK)
		RUN_DONE_CALLBACK();
	RUN_DONE_CALLBACK = null;
}

// Run until hitting a breakpoint, halting, or erroring
function RUN (cb) {
	// Resume from breakpoint, if applicable
	if (STAT === 'DBG')
		STAT = 'AOK';

	// Use fastest available interval the browser can provide
	STEP_INTERVAL = setInterval(RUN_STEP, 0);
	RUN_DONE_CALLBACK = cb;
}

// TODO: eventually, this will become a five-part pipeline
function STEP () {
	// Fetch
	var icode = MEMORY[PC] >> 4;
	var ilen = INSTRUCTION_LEN[icode];
	var instr = MEMORY.slice(PC, PC + ilen);

	PC += ilen;

	// Decode
	var args = DECODE(instr);

	// Execute + Memory + Write Back ???
	try {
		INSTR[icode].call(args);
	} catch (e) {
		ERR = e.message;
	}
}

function hex2arr (str) {
	var result = [], i;
	for (i = 0; i < str.length; i += 2) {
		result.push(parseInt(str[i] + str[i + 1], 16));
	}
	return result;
}

// Object file string to byte array
function toByteArray(str) {
	var lines = str.split('\n'),
		line, addr, size, bytearr;

	bytearr = new Uint8Array(MEM_SIZE);

	// Set instructions at correct locations
	for (i in lines) {
		line = lines[i];
		match = line.match(/\s*(0x([0-9a-f]+):\s*)?([0-9a-f]*)\s*\|.*/i);
		if (!match) {
			throw 'Invalid instruction format on line ' + i + ': "' + lines[i] + '"';
		}
		instr = hex2arr(match[3]);
		icode = parseInt(instr[0], 16);
		if (instr !== '') {
			addr = parseInt(match[2], 16);
			for (var i = 0; i < instr.length; i++) {
				bytearr[addr + i] = instr[i];
			}
		}
	}
	return bytearr;
}
<commit_msg>Pad hex literals to 4 bytes when encoding instructions. Fixes #5.<commit_after>// Constants
var MEM_SIZE = 0x2000;

// Registers and memory
var PC 		= 0,
	REG		= new Uint32Array(8),
	STAT	= 'AOK',
	MEMORY 	= new Uint8Array(MEM_SIZE),
	SF = 0, ZF = 0, OF = 0,
	ERR = '';

// Bounds check the register array
function getRegister (idx) {
	if (idx < 0 || idx > 8) {
		STAT = 'INS';
		throw new Error('Invalid register ID: 0x' + idx.toString(16));
	}
	return REG[idx];
}

// Uint32Arrays are not actually arrays
Uint8Array.prototype.slice = function () {
	return Array.prototype.slice.apply(this, arguments);
}

// Print
function print (x) {
	console.log(x);
}

// Reset
function RESET() {
	PC 	= 0;
	REG	= new Uint32Array(8);
	STAT = 'AOK';
	SF = 0; ZF = 0; OF = 0;
	ERR = '';
}

// Load
function LD (addr, mem) {
	mem = mem || MEMORY;
	var result;
	if (addr < 0 || addr + 4 > MEM_SIZE) {
		STAT = 'ADR';
		throw new Error("Invalid address 0x" + addr.toString(16));
	}
	result  = mem[addr];
	result |= mem[addr + 1] << 8;
	result |= mem[addr + 2] << 16;
	result |= mem[addr + 3] << 24;
	return result;
}

// Store
function ST(addr, data, bytes){
	var result, i;
	if (addr < 0 || addr + bytes > MEM_SIZE) {
		STAT = 'ADR';
		throw new Error("Invalid address 0x" + addr.toString(16));
	}
	if (typeof bytes === 'undefined') {
		bytes = Math.ceil(Math.log(data + 1) / Math.log(16) / 2);
	}
	for (i = 0; i < bytes; i++){
		MEMORY[addr + i] = data & 0xFF;
		data = data >> 8;
	}
	return addr;
}

// Decode instruction
function DECODE (bytearr) {
	var args = {
			icode: 	bytearr[0] >> 4,
			fn: 	bytearr[0] & 0x0F
		},
		len = bytearr.length;

	if (len > 1) {
		args['rA'] = (bytearr[1] >> 4) & 0x0F;
		args['rB'] = bytearr[1] & 0x0F;
	}
	if (len === 5) {
		var temp = bytearr[1];
		temp |= bytearr[2] << 8;
		temp |= bytearr[3] << 16;
		temp |= bytearr[4] << 24;
		args['Dest'] = temp;
	} else if (len === 6) {
		var temp = bytearr[2];
		temp |= bytearr[3] << 8;
		temp |= bytearr[4] << 16;
		temp |= bytearr[5] << 24;
		args['D'] = temp;
		args['V'] = temp;
	}
	return args;
}

function getRegCode (num) {
	var code = num2reg.indexOf(num);
	if (code === -1)
		throw new Error('Not a register: "' + num + '"');
	else
		return code.toString(16);
}

function evalArgs(list, args, symbols){
	var item, result = {};
	for (i in list) {
		item = list[i];
		if (item === 'rA') {
			result['rA'] = getRegCode(args[i]);
		}
		else if (item === 'rB') {
			result['rB'] = getRegCode(args[i]);
		}
		else if (item === 'V' || item === 'D') {
			if (symbols.hasOwnProperty(args[i])) {
				result['V'] = toBigEndian(padHex(symbols[args[i]], 8));
				result['D'] = result['V'];
			} else {
				try {
					result['V'] = toBigEndian(padHex(parseNumberLiteral(args[i].replace('$', '')) >>> 0, 8));
				} catch (e) {
					// Use 'not a symbol' instead of the more cryptic 'not a number'
					throw new Error('Undefined symbol: ' + args[i]);
				}
				result['D'] = result['V'];
			}
		} else if (item === 'Dest') {
			try {
				result['Dest'] = toBigEndian(padHex(symbols[args[i]].toString(16), 8));
			} catch (e) {
				throw new Error('Undefined symbol: ' + args[i]);
			}
		} else if (item === 'D(rB)') {
			result['D'] = toBigEndian(padHex(parseNumberLiteral(args[i].replace(/\(.*/, '')) >>> 0, 8));
			result['rB'] = getRegCode(args[i].replace(/^.*\((.*)\)/, '$1'));
		}
	}
	return result;
}

function ENCODE(instr, symbols) {
	var result = '',
		args = [],
		vars = {},
		icode;

	instr = instr.replace(/\s*,\s*/i, ',');
	args = instr.split(' ');
	instr = args.splice(0, 1)[0];
	args = args[0] ? args[0].split(',') : new Array();

	vars = evalArgs(SYNTAX[instr], args, symbols);
	icode = inst2num[instr];
	if (inst2fn.hasOwnProperty(instr)) {
		vars['fn'] = inst2fn[instr];
	}

	if (icode in ASSEM) {
		result = ASSEM[icode].call(vars);
	} else {
		throw new Error('Invalid instruction "' + instr + '"');
	}
	return result;
}

// Remove comments and fix spacing in code
function normalizeSource (lines) {
	_.each(lines, function (line, i) {
		line = line.replace(/#.*/gi, '');
		line = line.replace(/\/\*.*\*\//gi, '');
		line = line.replace(/^\s+/gi, '');
		line = line.replace(/\s+$/gi, '');
		line = line.replace(/\s+/gi, ' ');
		lines[i] = line;
	});
}

function ASSEMBLE (raw, errorsOnly) {
	errorsOnly = !!errorsOnly;

	var lines = raw.split('\n'), line,
		symbols = {},
		result = new Array(lines.length),
		inst, icode,
		sym, next = 0,
		counter = 0;
		raw = raw.split('\n'),
		errors = [];

	// Clean up raw e.g. remove comments, fix spacing
	normalizeSource(lines);

	// Last line must be blank in Linux simulator
	if (lines[lines.length - 1].trim() !== '')
		errors.push([lines.length, 'Last line must be blank.']);

	// Create symbol table and mark memory addresses
	_.each(lines, function (line, i) {
		result[i] = ['', '', raw[i]];

		// Ignore empty lines
		if (line === '')
			return;

		// Add line number
		result[i][0] = ['0x' + padHex(counter, 4)];

		// Look for symbol and add to symbols
		sym = line.match(/(^.*?):/i);
		if (sym) {
			symbols[sym[1]] = counter;
			// Delete symbol from line
			lines[i] = line = line.replace(/^.*?:\s*/i, '');
		}

		// Look for directive
		dir = line.match(/(^\..*?) (.*)/i);
		if (dir) {
			if (dir[1] === '.pos') {
				try {
					counter = parseNumberLiteral(dir[2]);
				} catch (e) {
					errors.push([i + 1, e.message]);
				}
			} else if (dir[1] === '.align') {
				try {
					var alignTo = parseNumberLiteral(dir[2]);
				} catch (e) {
					errors.push([i + 1, e.message]);
				}
				counter = Math.ceil(counter / alignTo) * alignTo;
			} else if (dir[1] === '.long') {
				counter += 4;
			} else {
				errors.push([i + 1, 'Unknown directive: ' + dir[1]]);
			}
		}

		// Move counter
		inst = line.match(/(^[a-z]+)/i);
		if (inst) {
			icode = inst2num[inst[1]];
			counter += INSTRUCTION_LEN[icode];
		}
	});

	// Assemble instructions and long directives
	_.each(lines, function (line, i) {
		// Ignore empty lines
		if (line.trim() === '')
			return;

		// Long directives
		dir = line.match(/^\.long (.*)/i);
		if (dir) {
			var value;
			try {
				// Try to parse the value as a number literal first...
				value = parseNumberLiteral(dir[1]);
			} catch (e) {
				// ...and if that fails, try to find it in the symbol table
				if (symbols.hasOwnProperty(dir[1]))
					value = symbols[dir[1]];
				else
					errors.push([i + 1, 'Error while parsing .long directive: undefined symbol ' + dir[1]]);
			}
			result[i][1] = toBigEndian(padHex(value >>> 0, 8));
			counter += 4;
			return;
		}

		// Ignore other directives
		if (line[0] === '.')
			return;

		// Instructions
		inst = line.match(/^([a-z]+)(.*)/i);
		if (inst) {
			try {
				result[i][1] = ENCODE(line, symbols);
			} catch (e) {
				errors.push([i + 1, e.message]);
			}
		}
	});

	if (errorsOnly)
		return { errors: errors }

	var objectCode = _.map(result, function (line) {
		// 0xXXXX: XXXXXX...
		var compiledPart = '  ';
		if (line[0].length)
			compiledPart += line[0] + ': ' + line[1];

		// pad to fit 22 characters
		var padding = new Array(24 - compiledPart.length).join(' ');

		return compiledPart + padding + '| ' + line[2];
	}).join('\n');

	return {
		obj: objectCode,
		errors: errors
	}
}

// Initialize the VM with some object code
function INIT (obj) {
	MEMORY = toByteArray(obj);
	STAT = 'AOK';
	ERR = '';
	RESET();
}

var STEP_INTERVAL = null, RUN_DONE_CALLBACK;

// Run 256 instructions
function RUN_STEP () {
	for (var i = 0; i < 256; i++) {
		if (PC < MEM_SIZE && STAT === 'AOK')
			STEP();
		else {
			PAUSE();
			break;
		}
	}
}

// Returns true if the machine is currently running
function IS_RUNNING () {
	return STEP_INTERVAL !== null;
}

// Stops machine execution.
function PAUSE () {
	clearInterval(STEP_INTERVAL);
	STEP_INTERVAL = null;
	if (STAT === 'AOK')
		STAT = 'DBG';
	if (RUN_DONE_CALLBACK)
		RUN_DONE_CALLBACK();
	RUN_DONE_CALLBACK = null;
}

// Run until hitting a breakpoint, halting, or erroring
function RUN (cb) {
	// Resume from breakpoint, if applicable
	if (STAT === 'DBG')
		STAT = 'AOK';

	// Use fastest available interval the browser can provide
	STEP_INTERVAL = setInterval(RUN_STEP, 0);
	RUN_DONE_CALLBACK = cb;
}

// TODO: eventually, this will become a five-part pipeline
function STEP () {
	// Fetch
	var icode = MEMORY[PC] >> 4;
	var ilen = INSTRUCTION_LEN[icode];
	var instr = MEMORY.slice(PC, PC + ilen);

	PC += ilen;

	// Decode
	var args = DECODE(instr);

	// Execute + Memory + Write Back ???
	try {
		INSTR[icode].call(args);
	} catch (e) {
		ERR = e.message;
	}
}

function hex2arr (str) {
	var result = [], i;
	for (i = 0; i < str.length; i += 2) {
		result.push(parseInt(str[i] + str[i + 1], 16));
	}
	return result;
}

// Object file string to byte array
function toByteArray(str) {
	var lines = str.split('\n'),
		line, addr, size, bytearr;

	bytearr = new Uint8Array(MEM_SIZE);

	// Set instructions at correct locations
	for (i in lines) {
		line = lines[i];
		match = line.match(/\s*(0x([0-9a-f]+):\s*)?([0-9a-f]*)\s*\|.*/i);
		if (!match) {
			throw 'Invalid instruction format on line ' + i + ': "' + lines[i] + '"';
		}
		instr = hex2arr(match[3]);
		icode = parseInt(instr[0], 16);
		if (instr !== '') {
			addr = parseInt(match[2], 16);
			for (var i = 0; i < instr.length; i++) {
				bytearr[addr + i] = instr[i];
			}
		}
	}
	return bytearr;
}
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================
/*globals SC */

sc_require('views/mediaSlider');
/** @class

  (Document Your View Here)

  @extends SC.View
*/
SC.MediaControlsView = SC.View.extend({

  target: null,

  childViews: 'playButton progressView timeView minusLabelView volumeView plusLabelView theaterButton'.w(),
  classNames: 'controllers',

  playObserver: function(){
    console.log("playobserver");
    if(this.getPath('target.paused')){
      this.get('playButton').set('icon', 'play');
    }else{
      this.get('playButton').set('icon', 'stop');

    }

  }.observes('target.paused'),

  playButton: SC.ButtonView.design({
       title: '',
       titleMinWidth: 35,
       icon: 'play',
       noStyle: YES,
       layout: { top: 0, left: 0, width: 20, height:20},
       action: "playPause",
       targetBinding: "*owner.target",
       renderStyle: 'renderImage',
       theme: ''
     }),
      progressView: SC.mediaSlider.design({
        layout: { top: 0, left: 20, right: 220, height:20},
        value:0,
        minimum: 0,
        valueBinding: "*owner.target.currentTime" ,
        maximumBinding: "*owner.target.duration",
        videoViewBinding: "*owner.target"
      }),

      timeView: SC.LabelView.design({
        layout: { top: 0, right: 160, width: 60, height:20},
        classNames: 'time',
        textAlign: SC.ALIGN_CENTER,
        valueBinding: '*owner.target.time'
      }),
      theaterButton: SC.ButtonView.design({
        title: '',
        icon: 'theater',
        renderStyle: 'renderImage',
        theme: '',
        titleMinWidth: 35,
        layout: { top: 0, right: 140, width: 20, height:20},
        action: "fullScreen",
        targetBinding: "*owner.target"
      }),
      minusLabelView: SC.LabelView.design({
        layout: { top: 0, right: 120, width: 20, height:20},
        value: '',
        icon: 'minus'
      }),
      volumeView: SC.SliderView.design({
        layout: { top: 0, right: 20, width: 100, height:20},
        value:0,
        valueBinding: "*owner.target.volume" ,
        minimum: 0,
        maximum: 1,
        step: 0.01
      }),
      plusLabelView: SC.LabelView.design({
        layout: { top: 0, right: 0, width: 20, height:20},
        value: '',
        icon: 'plus'
      })

});<commit_msg>Fix regression on observer to switch play icon<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================
/*globals SC */

sc_require('views/mediaSlider');
/** @class

  (Document Your View Here)

  @extends SC.View
*/
SC.MediaControlsView = SC.View.extend({

  target: null,

  childViews: 'playButton progressView timeView minusLabelView volumeView plusLabelView theaterButton'.w(),
  classNames: 'controllers',

  playObserver: function(){
    if(this.getPath('target.paused')){
      this.get('playButton').set('icon', 'play');
    }else{
      this.get('playButton').set('icon', 'stop');
    }
  }.observes('*target.paused'),

  playButton: SC.ButtonView.design({
       title: '',
       titleMinWidth: 35,
       icon: 'play',
       noStyle: YES,
       layout: { top: 0, left: 0, width: 20, height:20},
       action: "playPause",
       targetBinding: "*owner.target",
       renderStyle: 'renderImage',
       theme: ''
     }),
      progressView: SC.mediaSlider.design({
        layout: { top: 0, left: 20, right: 220, height:20},
        value:0,
        minimum: 0,
        valueBinding: "*owner.target.currentTime" ,
        maximumBinding: "*owner.target.duration",
        videoViewBinding: "*owner.target"
      }),

      timeView: SC.LabelView.design({
        layout: { top: 0, right: 160, width: 60, height:20},
        classNames: 'time',
        textAlign: SC.ALIGN_CENTER,
        valueBinding: '*owner.target.time'
      }),
      theaterButton: SC.ButtonView.design({
        title: '',
        icon: 'theater',
        renderStyle: 'renderImage',
        theme: '',
        titleMinWidth: 35,
        layout: { top: 0, right: 140, width: 20, height:20},
        action: "fullScreen",
        targetBinding: "*owner.target"
      }),
      minusLabelView: SC.LabelView.design({
        layout: { top: 0, right: 120, width: 20, height:20},
        value: '',
        icon: 'minus'
      }),
      volumeView: SC.SliderView.design({
        layout: { top: 0, right: 20, width: 100, height:20},
        value:0,
        valueBinding: "*owner.target.volume" ,
        minimum: 0,
        maximum: 1,
        step: 0.01
      }),
      plusLabelView: SC.LabelView.design({
        layout: { top: 0, right: 0, width: 20, height:20},
        value: '',
        icon: 'plus'
      })

});<|endoftext|>


<commit_before>function optional(val) {
	this.defined = (val === undefined ? false : true);
	this.val = (val === undefined ? undefined : val);

	function isSet() {
		return this.defined;
	}
	function get() {
		if(this.isSet()) {
			return this.val;
		} else {
			throw new Error('You cannot unwrap an unset optional.');
		}
	}
	function set(val) {
		this.defined = true;
		this.val = val;
		return this.val;
	}
	function unset() {
		this.defined = false;
		this.val = undefined;
	}
}
<commit_msg>Made everything except constructions of `new Optional(x)` work.<commit_after>var Optional = function(val) {
	this.defined = false;
	this.val = undefined;

	Object.defineProperty(this, "val", {
		get: function() {
			if(this.defined) {
				return val;
			} else {
				throw new Error('You cannot unwrap an unset optional.');
			}
		},
		set: function(newVal) {
			if (newVal === undefined) {
				this.defined = false;
				val = undefined
			} else {
				this.defined = true;
				val = newVal;
			}
		}
	});

	this.isSet = function() {
		return this.defined;
	};

	this.unset = function() {
		this.val = undefined;
	}
}

//module.exports = Optional;
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.ui.TagEditor = Class.extend({
	init: function(opts) {
		/* docs:
		Arguments

		- parent
		- user_tags
		- doctype
		- docname
		*/
		$.extend(this, opts);
		var me = this;
		this.wrapper = $('
').appendTo(this.parent)
		var id = frappe.dom.set_unique_id(this.wrapper);
		this.taggle = new Taggle(id, {
			placeholder: __('Add a tag') + "...",
			onTagAdd: function(e, tag) {
				if(me.initialized && !me.refreshing) {
					tag = toTitle(tag);
					return frappe.call({
						method: 'frappe.desk.tags.add_tag',
						args: me.get_args(tag),
						callback: function(r) {
							var user_tags = me.user_tags.split(",");
							user_tags.push(tag)
							me.user_tags = user_tags.join(",");
							me.on_change && me.on_change(me.user_tags);
						}
					});
				}
			},
			onTagRemove: function(e, tag) {
				if(!me.refreshing) {
					return frappe.call({
						method: 'frappe.desk.tags.remove_tag',
						args: me.get_args(tag),
						callback: function(r) {
							var user_tags = me.user_tags.split(",");
							user_tags.splice(user_tags.indexOf(tag), 1);
							me.user_tags = user_tags.join(",");
							me.on_change && me.on_change(me.user_tags);
						}
					});
				}
			}
		});
		if (!this.user_tags) {
			this.user_tags = "";
		}
		this.initialized = true;
		this.refresh(this.user_tags);
		this.setup_awesomplete();
	},
	setup_awesomplete: function() {
		var me = this;
		var $input = this.wrapper.find("input.taggle_input");
		var input = $input.get(0);
		this.awesomplete = new Awesomplete(input, {
			minChars: 0,
			maxItems: 99,
			list: []
		});
		$input.on("awesomplete-open", function(e){
			$input.attr('state', 'open');
		});
		$input.on("awesomplete-close", function(e){
			$input.attr('state', 'closed');
		});
		$input.on("input", function(e) {
			var value = e.target.value;
			frappe.call({
				method:"frappe.desk.tags.get_tags",
				args:{
					doctype: me.frm.doctype,
					txt: value.toLowerCase(),
					cat_tags:JSON.stringify(me.list_sidebar.get_cat_tags())
				},
				callback: function(r) {
					me.awesomplete.list = r.message;
				}
			});
		});
		$input.on("focus", function(e) {
			if($input.attr('state') != 'open') {
				$input.trigger("input");
			}
		});
	},
	get_args: function(tag) {
		return {
			tag: tag,
			dt: this.frm.doctype,
			dn: this.frm.docname,
		}
	},
	refresh: function(user_tags) {
		var me = this;
		if(!me.initialized || me.refreshing)
			return;

		me.refreshing = true;
		try {
			me.taggle.removeAll();
			if(user_tags) {
				me.taggle.add(user_tags.split(','));
			}
		} catch(e) {
			me.refreshing = false;
			// wtf bug
			setTimeout( function() { me.refresh(); }, 100);
		}
		me.refreshing = false;

	}
})
<commit_msg>hide toolbar fix (#2497)<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.ui.TagEditor = Class.extend({
	init: function(opts) {
		/* docs:
		Arguments

		- parent
		- user_tags
		- doctype
		- docname
		*/
		$.extend(this, opts);
		var me = this;
		this.wrapper = $('
').appendTo(this.parent)
		if(!this.wrapper.length) return;
		var id = frappe.dom.set_unique_id(this.wrapper);
		this.taggle = new Taggle(id, {
			placeholder: __('Add a tag') + "...",
			onTagAdd: function(e, tag) {
				if(me.initialized && !me.refreshing) {
					tag = toTitle(tag);
					return frappe.call({
						method: 'frappe.desk.tags.add_tag',
						args: me.get_args(tag),
						callback: function(r) {
							var user_tags = me.user_tags.split(",");
							user_tags.push(tag)
							me.user_tags = user_tags.join(",");
							me.on_change && me.on_change(me.user_tags);
						}
					});
				}
			},
			onTagRemove: function(e, tag) {
				if(!me.refreshing) {
					return frappe.call({
						method: 'frappe.desk.tags.remove_tag',
						args: me.get_args(tag),
						callback: function(r) {
							var user_tags = me.user_tags.split(",");
							user_tags.splice(user_tags.indexOf(tag), 1);
							me.user_tags = user_tags.join(",");
							me.on_change && me.on_change(me.user_tags);
						}
					});
				}
			}
		});
		if (!this.user_tags) {
			this.user_tags = "";
		}
		this.initialized = true;
		this.refresh(this.user_tags);
		this.setup_awesomplete();
	},
	setup_awesomplete: function() {
		var me = this;
		var $input = this.wrapper.find("input.taggle_input");
		var input = $input.get(0);
		this.awesomplete = new Awesomplete(input, {
			minChars: 0,
			maxItems: 99,
			list: []
		});
		$input.on("awesomplete-open", function(e){
			$input.attr('state', 'open');
		});
		$input.on("awesomplete-close", function(e){
			$input.attr('state', 'closed');
		});
		$input.on("input", function(e) {
			var value = e.target.value;
			frappe.call({
				method:"frappe.desk.tags.get_tags",
				args:{
					doctype: me.frm.doctype,
					txt: value.toLowerCase(),
					cat_tags:JSON.stringify(me.list_sidebar.get_cat_tags())
				},
				callback: function(r) {
					me.awesomplete.list = r.message;
				}
			});
		});
		$input.on("focus", function(e) {
			if($input.attr('state') != 'open') {
				$input.trigger("input");
			}
		});
	},
	get_args: function(tag) {
		return {
			tag: tag,
			dt: this.frm.doctype,
			dn: this.frm.docname,
		}
	},
	refresh: function(user_tags) {
		var me = this;
		if(!me.initialized || me.refreshing)
			return;

		me.refreshing = true;
		try {
			me.taggle.removeAll();
			if(user_tags) {
				me.taggle.add(user_tags.split(','));
			}
		} catch(e) {
			me.refreshing = false;
			// wtf bug
			setTimeout( function() { me.refresh(); }, 100);
		}
		me.refreshing = false;

	}
})
<|endoftext|>


<commit_before>var fs = require('fs');
var gulp = require('gulp');
var Parker = require('parker/lib/Parker');
var prettyJSON = require('prettyjson');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');
var scssLint = require('gulp-scss-lint');

var PATHS = [
  'scss',
  'node_modules/motion-ui/src',
  'node_modules/foundation-docs/scss'
];

var COMPATIBILITY = [
  'last 2 versions',
  'ie >= 9',
  'and_chr >= 2.3'
];

// Compiles Sass files into CSS
gulp.task('sass', ['sass:foundation', 'sass:docs']);

// Compiles Foundation Sass
gulp.task('sass:foundation', function() {
  return gulp.src(['assets/*'])
    .pipe(scssLint({
      'config': 'config/scss-lint.yml'
    }))
    .pipe(sourcemaps.init())
    .pipe(plumber())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: COMPATIBILITY
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('_build/assets/css'));
});

// Compiles docs Sass (includes Foundation code also)
gulp.task('sass:docs', function() {
  return gulp.src('docs/assets/scss/docs.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({
      includePaths: PATHS
    }).on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: COMPATIBILITY
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('_build/assets/css'));
});

// Audits CSS filesize, selector count, specificity, etc.
gulp.task('sass:audit', ['sass:foundation'], function(cb) {
  fs.readFile('./_build/assets/css/foundation.css', function(err, data) {
    var parker = new Parker(require('parker/metrics/All'));
    var results = parker.run(data.toString());
    console.log(prettyJSON.render(results));
    cb();
  });
});
<commit_msg>Disable gulp-scss-lint for now as it's causing errors<commit_after>'use strict';

var fs = require('fs');
var gulp = require('gulp');
var Parker = require('parker/lib/Parker');
var prettyJSON = require('prettyjson');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');
var scssLint = require('gulp-scss-lint');

var PATHS = [
  'scss',
  'node_modules/motion-ui/src',
  'node_modules/foundation-docs/scss'
];

var COMPATIBILITY = [
  'last 2 versions',
  'ie >= 9',
  'and_chr >= 2.3'
];

// Compiles Sass files into CSS
gulp.task('sass', ['sass:foundation', 'sass:docs']);

// Compiles Foundation Sass
gulp.task('sass:foundation', function() {
  return gulp.src(['assets/*'])
    // .pipe(scssLint())
    .pipe(sourcemaps.init())
    .pipe(plumber())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: COMPATIBILITY
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('_build/assets/css'));
});

// Compiles docs Sass (includes Foundation code also)
gulp.task('sass:docs', function() {
  return gulp.src('docs/assets/scss/docs.scss')
    .pipe(sourcemaps.init())
    .pipe(sass({
      includePaths: PATHS
    }).on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: COMPATIBILITY
    }))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('_build/assets/css'));
});

// Audits CSS filesize, selector count, specificity, etc.
gulp.task('sass:audit', ['sass:foundation'], function(cb) {
  fs.readFile('./_build/assets/css/foundation.css', function(err, data) {
    var parker = new Parker(require('parker/metrics/All'));
    var results = parker.run(data.toString());
    console.log(prettyJSON.render(results));
    cb();
  });
});
<|endoftext|>


<commit_before>module.exports = function(config) {
  config.set({
    frameworks: ['mocha'],

    exclude: ['build/test/external.spec.js'],

    files: [
      'vendor/es5-shim.js',
      'vendor/es5-sham.js',
      'vendor/rsvp.js',
      'vendor/unexpected-magicpen.min.js',
      'build/test/promisePolyfill.js',
      'unexpected.js',
      'build/test/common.js',
      'build/test/**/*.spec.js'
    ],

    browsers: ['ChromeHeadlessNoSandbox', 'ie11'],

    browserDisconnectTimeout: '60000',
    browserNoActivityTimeout: '60000',

    client: {
      mocha: {
        reporter: 'html',
        timeout: 60000
      }
    },

    browserStack: {
      video: false,
      project:
        process.env.TRAVIS_BRANCH === 'master' ? 'unexpected' : 'unexpected-dev'
    },

    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
      },
      ie11: {
        base: 'BrowserStack',
        browser: 'IE',
        browser_version: '11',
        os: 'Windows',
        os_version: '7'
      }
    },

    reporters: ['dots', 'BrowserStack']
  });
};
<commit_msg>Use the unexpected-dev project on browserstack for Travis "PR" builds<commit_after>module.exports = function(config) {
  config.set({
    frameworks: ['mocha'],

    exclude: ['build/test/external.spec.js'],

    files: [
      'vendor/es5-shim.js',
      'vendor/es5-sham.js',
      'vendor/rsvp.js',
      'vendor/unexpected-magicpen.min.js',
      'build/test/promisePolyfill.js',
      'unexpected.js',
      'build/test/common.js',
      'build/test/**/*.spec.js'
    ],

    browsers: ['ChromeHeadlessNoSandbox', 'ie11'],

    browserDisconnectTimeout: '60000',
    browserNoActivityTimeout: '60000',

    client: {
      mocha: {
        reporter: 'html',
        timeout: 60000
      }
    },

    browserStack: {
      video: false,
      project:
        process.env.TRAVIS_BRANCH === 'master' &&
        !process.env.TRAVIS_PULL_REQUEST_BRANCH // Catch Travis "PR" builds
          ? 'unexpected'
          : 'unexpected-dev'
    },

    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
      },
      ie11: {
        base: 'BrowserStack',
        browser: 'IE',
        browser_version: '11',
        os: 'Windows',
        os_version: '7'
      }
    },

    reporters: ['dots', 'BrowserStack']
  });
};
<|endoftext|>


<commit_before>
var React = require('react');
var PropTypes = React.PropTypes;
var reactNativeBootstrapSliderObj = require('react-bootstrap-native-slider');
var ReactNativeBootstrapSlider = reactNativeBootstrapSliderObj.ReactNativeBootstrapSlider;
// var reactBootstrapSliderObj = require("react-bootstrap-slider");
// var ReactBootstrapSlider = reactBootstrapSliderObj.ReactBootstrapSlider;

var Slider = React.createClass({
  getInitialState(){
    var today = new Date();
    var year = today.getFullYear();
    return {
      currentValue: 100,
      step: 1,
      max: year,
      min: 0,
      range: true
    }
  },
  handleUpdateValue(e) {
    this.setState({ currentValue: e.target.value });
  },

  componentDidMount: function(){
    // componentDidMount is called by react when the component
    // has been rendered on the page. We can set the interval here:
  },

  componentWillUnmount: function(){
    // This method is called immediately before the component is removed
    // from the page and destroyed. We can clear the interval here:
    // clearInterval(this);
  },

  render(){
    var newValue = this.state.currentValue;
    // var newValue2 = this.state.currentValue[1];
    return(

        <ReactNativeBootstrapSlider
        value={this.state.currentValue}
        //range={this.state.range}
        handleChange={this.handleUpdateValue}
        step={this.state.step}
        max={this.state.max}
        min={this.state.min}
        reverse={true}/>
      year {this.state.min}
      {this.state.max}

       Year: {newValue}

    )
  }
})

module.exports = Slider;
<commit_msg>updated with a name field for the hidden input"<commit_after>
var React = require('react');
var PropTypes = React.PropTypes;
var reactNativeBootstrapSliderObj = require('react-bootstrap-native-slider');
var ReactNativeBootstrapSlider = reactNativeBootstrapSliderObj.ReactNativeBootstrapSlider;
// var reactBootstrapSliderObj = require("react-bootstrap-slider");
// var ReactBootstrapSlider = reactBootstrapSliderObj.ReactBootstrapSlider;

var Slider = React.createClass({
  getInitialState(){
    var today = new Date();
    var year = today.getFullYear();
    return {
      currentValue: 100,
      step: 1,
      max: year,
      min: 0,
      range: true
    }
  },
  handleUpdateValue(e) {
    this.setState({ currentValue: e.target.value });
  },

  componentDidMount: function(){
    // componentDidMount is called by react when the component
    // has been rendered on the page. We can set the interval here:
  },

  componentWillUnmount: function(){
    // This method is called immediately before the component is removed
    // from the page and destroyed. We can clear the interval here:
    // clearInterval(this);
  },

  render(){
    var newValue = this.state.currentValue;
    // var newValue2 = this.state.currentValue[1];
    return(

        <ReactNativeBootstrapSlider
        value={this.state.currentValue}
        handleChange={this.handleUpdateValue}
        step={this.state.step}
        max={this.state.max}
        min={this.state.min} />
      year {this.state.min}
      {this.state.max}

       Year: {newValue}

       <input type="hidden" value={newValue} name="year"/>

    )
  }
})

module.exports = Slider;
<|endoftext|>


<commit_before>/**
 * Russian translation for bootstrap-datetimepicker
 * Victor Taranenko <darwin@snowdale.com>
 */
;(function($){
	$.fn.datetimepicker.dates['ru'] = {
		days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"],
		daysShort: ["Вск", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Вск"],
		daysMin: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
		months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
		monthsShort: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
		today: "Сегодня",
		suffix: [],
		meridiem: []
	};
}(jQuery));<commit_msg>Fixed bootstrap-datetimepicker.ru.js<commit_after>/**
 * Russian translation for bootstrap-datetimepicker
 * Victor Taranenko <darwin@snowdale.com>
 */
;(function($){
	$.fn.datetimepicker.dates['ru'] = {
		days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"],
		daysShort: ["Вск", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Вск"],
		daysMin: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
		months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
		monthsShort: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
		today: "Сегодня",
		weekStart: 1,
		suffix: [],
		meridiem: []
	};
}(jQuery));
<|endoftext|>


<commit_before>this.is("temp")
<commit_msg>Delete main.js<commit_after><|endoftext|>