<commit_before>// Copyright 2016 The Oppia Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Directive for creating a new collection node.
 */

oppia.directive('collectionNodeCreator', [
  'UrlInterpolationService', function(UrlInterpolationService) {
    return {
      restrict: 'E',
      templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
        '/pages/collection_editor/editor_tab/' +
        'collection_node_creator_directive.html'),
      controller: [
        '$scope', '$http', '$window', '$filter', 'AlertsService',
        'ValidatorsService', 'CollectionEditorStateService',
        'CollectionLinearizerService', 'CollectionUpdateService',
        'CollectionNodeObjectFactory', 'ExplorationSummaryBackendApiService',
        'SearchExplorationsBackendApiService', 'siteAnalyticsService',
        function(
            $scope, $http, $window, $filter, AlertsService,
            ValidatorsService, CollectionEditorStateService,
            CollectionLinearizerService, CollectionUpdateService,
            CollectionNodeObjectFactory, ExplorationSummaryBackendApiService,
            SearchExplorationsBackendApiService, siteAnalyticsService) {
          $scope.collection = CollectionEditorStateService.getCollection();
          $scope.newExplorationId = '';
          $scope.newExplorationTitle = '';
          $scope.searchQueryHasError = false;

          var CREATE_NEW_EXPLORATION_URL_TEMPLATE = '/create/<exploration_id>';

          /**
           * Fetches a list of exploration metadata dicts from backend, given
           * a search query. It then extracts the title and id of the
           * exploration to prepare typeahead options.
           */
          $scope.fetchTypeaheadResults = function(searchQuery) {
            if (isValidSearchQuery(searchQuery)) {
              $scope.searchQueryHasError = false;
              return SearchExplorationsBackendApiService.fetchExplorations(
                searchQuery
              ).then(function(explorationMetadataBackendDict) {
                var options = [];
                explorationMetadataBackendDict.collection_node_metadata_list.
                  map(function(item) {
                    if (!$scope.collection.containsCollectionNode(item.id)) {
                      options.push(item.title + ' (#' + item.id + ')');
                    }
                  });
                return options;
              }, function() {
                AlertsService.addWarning(
                  'There was an error when searching for matching ' +
                  'explorations.');
              });
            } else {
              $scope.searchQueryHasError = true;
            }
          };

          var isValidSearchQuery = function(searchQuery) {
            if (/^[a-zA-Z0-9- ]*$/.test(searchQuery)) {
              return true;
            }
            return;
          };

          var addExplorationToCollection = function(newExplorationId) {
            if (!newExplorationId) {
              AlertsService.addWarning('Cannot add an empty exploration ID.');
              return;
            }
            if ($scope.collection.containsCollectionNode(newExplorationId)) {
              AlertsService.addWarning(
                'There is already an exploration in this collection ' +
                'with that id.');
              return;
            }

            ExplorationSummaryBackendApiService
              .loadPublicAndPrivateExplorationSummaries([newExplorationId])
              .then(function(summaries) {
                var summaryBackendObject = null;
                if (summaries.length !== 0 &&
                    summaries[0].id === newExplorationId) {
                  summaryBackendObject = summaries[0];
                }
                if (summaryBackendObject) {
                  CollectionLinearizerService.appendCollectionNode(
                    $scope.collection, newExplorationId, summaryBackendObject);
                } else {
                  AlertsService.addWarning(
                    'That exploration does not exist or you do not have edit ' +
                    'access to it.');
                }
              }, function() {
                AlertsService.addWarning(
                  'There was an error while adding an exploration to the ' +
                  'collection.');
              }
            );
          };

          var convertTypeaheadToExplorationId = function(typeaheadOption) {
            var matchResults = typeaheadOption.match(/\(#(.*?)\)$/);
            if (matchResults == null) {
              return typeaheadOption;
            }
            return matchResults[1];
          };

          // Creates a new exploration, then adds it to the collection.
          $scope.createNewExploration = function() {
            var title = $filter('normalizeWhitespace')(
              $scope.newExplorationTitle);

            if (!ValidatorsService.isValidExplorationTitle(title, true)) {
              return;
            }

            // Create a new exploration with the given title.
            $http.post('/contributehandler/create_new', {
              title: title
            }).then(function(response) {
              $scope.newExplorationTitle = '';
              var newExplorationId = response.data.explorationId;

              siteAnalyticsService
                .registerCreateNewExplorationInCollectionEvent(
                  newExplorationId);
              addExplorationToCollection(newExplorationId);
            });
          };

          // Checks whether the user has left a '#' at the end of their ID
          // by accident (which can happen if it's being copy/pasted from the
          // editor page.
          $scope.isMalformedId = function(typedExplorationId) {
            return (
              typedExplorationId &&
              typedExplorationId.lastIndexOf('#') ===
              typedExplorationId.length - 1);
          };

          $scope.addExploration = function() {
            addExplorationToCollection(convertTypeaheadToExplorationId(
              $scope.newExplorationId));
            $scope.newExplorationId = '';
          };
        }
      ]
    };
  }]);
<commit_msg>Exploration search validator (for new node) modification. (#4510)<commit_after>// Copyright 2016 The Oppia Authors. All Rights Reserved.
//
// 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.

/**
 * @fileoverview Directive for creating a new collection node.
 */

oppia.directive('collectionNodeCreator', [
  'UrlInterpolationService', function(UrlInterpolationService) {
    return {
      restrict: 'E',
      templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
        '/pages/collection_editor/editor_tab/' +
        'collection_node_creator_directive.html'),
      controller: [
        '$scope', '$http', '$window', '$filter', 'AlertsService',
        'ValidatorsService', 'CollectionEditorStateService',
        'CollectionLinearizerService', 'CollectionUpdateService',
        'CollectionNodeObjectFactory', 'ExplorationSummaryBackendApiService',
        'SearchExplorationsBackendApiService', 'siteAnalyticsService',
        function(
            $scope, $http, $window, $filter, AlertsService,
            ValidatorsService, CollectionEditorStateService,
            CollectionLinearizerService, CollectionUpdateService,
            CollectionNodeObjectFactory, ExplorationSummaryBackendApiService,
            SearchExplorationsBackendApiService, siteAnalyticsService) {
          $scope.collection = CollectionEditorStateService.getCollection();
          $scope.newExplorationId = '';
          $scope.newExplorationTitle = '';
          $scope.searchQueryHasError = false;

          var CREATE_NEW_EXPLORATION_URL_TEMPLATE = '/create/<exploration_id>';

          /**
           * Fetches a list of exploration metadata dicts from backend, given
           * a search query. It then extracts the title and id of the
           * exploration to prepare typeahead options.
           */
          $scope.fetchTypeaheadResults = function(searchQuery) {
            if (isValidSearchQuery(searchQuery)) {
              $scope.searchQueryHasError = false;
              return SearchExplorationsBackendApiService.fetchExplorations(
                searchQuery
              ).then(function(explorationMetadataBackendDict) {
                var options = [];
                explorationMetadataBackendDict.collection_node_metadata_list.
                  map(function(item) {
                    if (!$scope.collection.containsCollectionNode(item.id)) {
                      options.push(item.title + ' (#' + item.id + ')');
                    }
                  });
                return options;
              }, function() {
                AlertsService.addWarning(
                  'There was an error when searching for matching ' +
                  'explorations.');
              });
            } else {
              $scope.searchQueryHasError = true;
            }
          };

          var isValidSearchQuery = function(searchQuery) {
            if (/^[a-zA-Z0-9-_ ]*$/.test(searchQuery)) {
              return true;
            }
            return;
          };

          var addExplorationToCollection = function(newExplorationId) {
            if (!newExplorationId) {
              AlertsService.addWarning('Cannot add an empty exploration ID.');
              return;
            }
            if ($scope.collection.containsCollectionNode(newExplorationId)) {
              AlertsService.addWarning(
                'There is already an exploration in this collection ' +
                'with that id.');
              return;
            }

            ExplorationSummaryBackendApiService
              .loadPublicAndPrivateExplorationSummaries([newExplorationId])
              .then(function(summaries) {
                var summaryBackendObject = null;
                if (summaries.length !== 0 &&
                    summaries[0].id === newExplorationId) {
                  summaryBackendObject = summaries[0];
                }
                if (summaryBackendObject) {
                  CollectionLinearizerService.appendCollectionNode(
                    $scope.collection, newExplorationId, summaryBackendObject);
                } else {
                  AlertsService.addWarning(
                    'That exploration does not exist or you do not have edit ' +
                    'access to it.');
                }
              }, function() {
                AlertsService.addWarning(
                  'There was an error while adding an exploration to the ' +
                  'collection.');
              }
            );
          };

          var convertTypeaheadToExplorationId = function(typeaheadOption) {
            var matchResults = typeaheadOption.match(/\(#(.*?)\)$/);
            if (matchResults == null) {
              return typeaheadOption;
            }
            return matchResults[1];
          };

          // Creates a new exploration, then adds it to the collection.
          $scope.createNewExploration = function() {
            var title = $filter('normalizeWhitespace')(
              $scope.newExplorationTitle);

            if (!ValidatorsService.isValidExplorationTitle(title, true)) {
              return;
            }

            // Create a new exploration with the given title.
            $http.post('/contributehandler/create_new', {
              title: title
            }).then(function(response) {
              $scope.newExplorationTitle = '';
              var newExplorationId = response.data.explorationId;

              siteAnalyticsService
                .registerCreateNewExplorationInCollectionEvent(
                  newExplorationId);
              addExplorationToCollection(newExplorationId);
            });
          };

          // Checks whether the user has left a '#' at the end of their ID
          // by accident (which can happen if it's being copy/pasted from the
          // editor page.
          $scope.isMalformedId = function(typedExplorationId) {
            return (
              typedExplorationId &&
              typedExplorationId.lastIndexOf('#') ===
              typedExplorationId.length - 1);
          };

          $scope.addExploration = function() {
            addExplorationToCollection(convertTypeaheadToExplorationId(
              $scope.newExplorationId));
            $scope.newExplorationId = '';
          };
        }
      ]
    };
  }]);
<|endoftext|>


<commit_before>(function (window, document, undefined, Butter) {

  var urlRegex, videoURL,
    iframe, iframeBody,
    popcornString, butterId,
    userSetMedia, videoString,
    popcornURL, originalHead,
    popcorns;

  Butter.registerModule( "previewer", {

    // setup function used to set default values, as well as setting up the iframe
    setup: function( options ) {

      originalHead = {};
      popcornURL = options.popcornURL || "http://popcornjs.org/code/dist/popcorn-complete.js";
      urlRegex = /(?:http:\/\/www\.|http:\/\/|www\.|\.|^)(youtu|vimeo|soundcloud|baseplayer)/;
      layout = options.layout;
      butterIds = {};
      userSetMedia = options.media;
      popcorns = {};
      videoString = {};

      var that = this,
          targetSrc = document.getElementById( options.target );

        // check if target is a div or iframe
      if ( targetSrc.tagName === "DIV" ) {

        target = document.getElementById( options.target );

        // force iframe to fill parent and set source
        iframe = document.createElement( "IFRAME" );
        iframe.src = layout;
        iframe.width = target.style.width;
        iframe.height = target.style.height;
        target.appendChild( iframe );

        // begin scraping once iframe has loaded, remove listener when complete
        iframe.addEventListener( "load", function (e) {
          that.scraper( iframe, options.callback );
          this.removeEventListener( "load", arguments.callee, false );
        }, false);

      } else if ( targetSrc.tagName === "IFRAME" ) {

        iframe = targetSrc;
        iframe.src = options.layout;

        targetSrc.addEventListener( "load", function (e) {
          that.scraper( iframe, options.callback );
          this.removeEventListener( "load", arguments.callee, false );
        }, false);
      } // else
    }, // setup

    extend: {

      // scraper function that scrapes all DOM elements of the given layout,
      // only scrapes elements with the butter-data attribute
      scraper: function( iframe, callback ) {

        // obtain a reference to the iframes body
        var doc = ( iframe.contentWindow || iframe.contentDocument ).document;
        var body = doc.getElementsByTagName( "BODY" );
            that = this;

        Butter.extend( originalHead, ( iframe.contentWindow || iframe.contentDocument ).document.head );

        //originalHead = iframe.contentWindow.document.head;

        // store original iframeBody incase we rebuild
        var ifrmBody = ( iframe.contentWindow || iframe.contentDocument ).document;
        iframeBody = "" + ifrmBody.body.innerHTML + "\n";

        // function to ensure body is actually there
        var ensureLoaded = function() {

          if ( body.length < 1 ) {
            setTimeout( function() {
              ensureLoaded();
            }, 5 );
          } else {

            // begin scraping once body is actually there, call callback once done
            bodyReady( body[ 0 ].children );
            callback();
          } // else
        } // ensureLoaded

        ensureLoaded();

        // scraping is done here
        function bodyReady( children ) {

          // loop for every child of the body
          for( var i = 0; i < children.length; i++ ) {

            // if DOM element has an data-butter tag that is equal to target or media,
            // add it to butters target list with a respective type
            if( children[ i ].getAttribute( "data-butter" ) === "target" ) {
              that.addTarget( {
                name: children[ i ].id,
                type: "target"
              } );
            } else if( children[ i ].getAttribute( "data-butter" ) === "media" ) {
              that.addMedia( {
                name: children[ i ].id,
                media: userSetMedia
              } );
            } // else

            // ensure we get every child, search recursively
            if ( children[ i ].children.length > 0 ) {

              bodyReady( children[ i ].children );
            } // if
          } // for
        } // ok

      }, // scraper

      // buildPopcorn function, builds an instance of popcorn in the iframe and also
      // a local version of popcorn
      buildPopcorn: function( videoTarget, callback ) {

        videoURL = this.getCurrentMedia().getMedia();

        // default to first butter-media tagged object if none is specified
        videoTarget = videoTarget.getName() || this.getAllMedia()[ 0 ].getName();

        var bpIframe = ( iframe.contentWindow || iframe.contentDocument ).document;

        // create a string that will create an instance of popcorn with the proper video source
        popcornString = "document.addEventListener('DOMContentLoaded', function () {\n";

        var regexResult = urlRegex.exec( videoURL ) || "",
            players = [], that = this;

        players[ "youtu" ] = function() {
          bpIframe.getElementById( videoTarget ).innerHTML = "";
          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( Popcorn.youtube( '" + videoTarget + "', '" +
            videoURL + "', {\n" +
            "width: 430, height: 300\n" +
          "} ) );\n";
        };

        players[ "vimeo " ] = function() {
          bpIframe.getElementById( videoTarget ).innerHTML = "";
          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( Popcorn.vimeo( '" + videoTarget + "', '" +
          videoURL + "', {\n" +
            "css: {\n" +
              "width: '430px',\n" +
              "height: '300px'\n" +
            "}\n" +
          "} ) );\n";
        };

        players[ "soundcloud" ] = function() {
          bpIframe.getElementById( videoTarget ).innerHTML = "";
          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( Popcorn.soundcloud( '" + videoTarget + "'," +
          " '" + videoURL + "' ) );\n";
        };

        players[ "baseplayer" ] = function() {
          bpIframe.getElementById( videoTarget ).innerHTML = "";
          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( Popcorn.baseplayer( '" + videoTarget + "' ) );\n";
        };

        players[ undefined ] = function() {
          var src = document.createElement( "source" ),
          video = document.createElement( "video" );
          src.src = videoURL;

          video.style.width = videoTarget.width;
          video.style.height = videoTarget.height;
          video.appendChild( src );
          video.controls = true;
          video.id = videoTarget + "-butter";

          bpIframe.getElementById( videoTarget ).appendChild( video );

          var vidId = "#" + video.id;

          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( '" + vidId + "');\n";
        };

        // call certain player function depending on the regexResult
        players[ regexResult[ 1 ] ]();

        for( video in videoString ) {
          popcornString += videoString[ video ];
        }

        // if for some reason the iframe is refreshed, we want the most up to date popcorn code
        // to be represented in the head of the iframe, incase someone views source
        for( popcorn in popcorns ) {

          var trackEvents = popcorns[ popcorn ].getTrackEvents();

          if ( trackEvents ) {

            // loop through each track event
            for ( var k = 0; k < trackEvents.length; k++ ) {

              // obtain all of the options in the manifest
              var options = trackEvents[ k ]._natives.manifest.options;
              popcornString += " popcorn" + popcorn + "." + trackEvents[ k ]._natives.type + "({\n";

              // for each option
              for ( item in options ) {

                if ( options.hasOwnProperty( item ) ) {

                  // add the data to the string so it looks like normal popcorn code
                  // that someone would write
                  popcornString += item + ": '" + trackEvents[ k ][ item ] + "',\n";
                } // if
              } // for

              popcornString += "});";

            } // for
          } // if
        }

        popcornString += "}, false);";

        this.fillIframe( callback );
      },

      getPopcorn: function( callback ) {
        var popcornz = "var " + videoString;

        // if for some reason the iframe is refreshed, we want the most up to date popcorn code
        // to be represented in the head of the iframe, incase someone views source
        for( popcorn in popcorns ) {

          var trackEvents = popcorns[ popcorn ].getTrackEvents();

          if ( trackEvents ) {

            // loop through each track event
            for ( var k = 0; k < trackEvents.length; k++ ) {

              // obtain all of the options in the manifest
              var options = trackEvents[ k ]._natives.manifest.options;
              popcornz += "popcorn" + popcorn + "." + trackEvents[ k ]._natives.type + "({\n";

              // for each option
              for ( item in options ) {

                if ( options.hasOwnProperty( item ) ) {

                  // add the data to the string so it looks like normal popcorn code
                  // that someone would write
                  popcornz += item + ": '" + trackEvents[ k ][ item ] + "',\n";
                } // if
              } // for

              popcornz += "});\n";

            } // for
          } // if
        }

        return popcornz;

      },

      getRegistry: function() {
        var ifrme = iframe.contentWindow || iframe.contentDocument;
        return ifrme.Popcorn.registry;
      },

      // fillIframe function used to populate the iframe with changes made by the user,
      // which is mostly managing track events added by the user
      fillIframe: function( callback ) {

        var popcornScript, iframeHead, body,
            that = this, doc = ( iframe.contentWindow || iframe.contentDocument ).document;

        // create a script within the iframe and populate it with our popcornString
        popcornScript = doc.createElement( "script" );
        popcornScript.innerHTML = popcornString;

        doc.head.appendChild( popcornScript );

        // create a new head element with our new data
        iframeHead = "" + originalHead.innerHTML + "\n\n";

        iframeHead += "\n\n";

        // create a new body element with our new data
        body = doc.body.innerHTML;

        // open, write our changes to the iframe, and close it
        doc.open();
        doc.write( "\n" + iframeHead + body + "\n" );
        doc.close();

        var popcornReady = function( e, callback2 ) {

          var popcornIframe = iframe.contentWindow || iframe.contentDocument;
          var framePopcorn = popcornIframe[ "popcorn" + that.getCurrentMedia().getId() ];

          if ( !framePopcorn ) {
            setTimeout( function() {
              popcornReady( e, callback2 );
            }, 10 );
          } else {
            callback2 && callback2( framePopcorn );
          } // else
        }

        popcornReady( null, function( framePopcorn ) {

          var videoReady = function() {

            if( framePopcorn.media.readyState >= 2 || framePopcorn.media.duration > 0 ) {
              that.duration( framePopcorn.media.duration );

              that.trigger( "mediaready", that.getCurrentMedia() );
              framePopcorn.media.addEventListener( "timeupdate", function() {

                that.currentTime( framePopcorn.media.currentTime );
                that.trigger( "mediatimeupdate", that.getCurrentMedia() );
              },false);
              callback && callback();
            } else {
              setTimeout( function() {
                videoReady( framePopcorn );
              }, 10);
            }
          }
          videoReady( framePopcorn );
        } );

        this.teAdded = function( event ) {
          var that = this, e = event.data;

          popcornReady( e, function( framePopcorn ) {

            if( !popcorns[ that.getCurrentMedia().getId() ] ) {
                popcorns[ that.getCurrentMedia().getId() ] = framePopcorn;
            } else {
              framePopcorn = popcorns[ that.getCurrentMedia().getId() ];
            }

            framePopcorn.removeTrackEvent( butterIds[ e.getId() ] );

            // add track events to the iframe verison of popcorn
            framePopcorn[ e.type ]( ( iframe.contentWindow || iframe.contentDocument.parentWindow ).Popcorn.extend( {},
              e.popcornOptions ) );

            butterIds[ e.getId() ] = framePopcorn.getLastTrackEventId();

            e.manifest = framePopcorn.getTrackEvent( butterIds[ e.getId() ] )._natives.manifest;

          } );
        }

        // listen for a trackeventadded
        this.listen( "trackeventupdated", function ( e ) {
          this.teAdded( e );
        }); // listener

        this.listen( "trackeventadded", function ( e ) {
          e = e.data;
          popcornReady( e, function( framePopcorn ) {

            if( !popcorns[ that.getCurrentMedia().getId() ] ) {
              popcorns[ that.getCurrentMedia().getId() ] = framePopcorn;
            } else {
              framePopcorn = popcorns[ that.getCurrentMedia().getId() ];
            }

            // add track events to the iframe verison of popcorn
            framePopcorn[ e.type ]( ( iframe.contentWindow || iframe.contentDocument ).Popcorn.extend( {},
              e.popcornOptions ) );

            butterIds[ e.getId() ] = framePopcorn.getLastTrackEventId();

            e.manifest = framePopcorn.getTrackEvent( butterIds[ e.getId() ] )._natives.manifest;
          } );
        }); // listener

        this.listen( "trackeventremoved", function( e ) {
          var ifrme = iframe.contentWindow || iframe.contentDocument;
          ifrme[ "popcorn" + that.getCurrentMedia().getId() ].removeTrackEvent( butterIds[ e.data.getId() ] );
        } );

        this.listen( "mediachanged", function( e ) {
          that.buildPopcorn( e.data.getName() );
        } );

        this.listen( "mediatimeupdate", function( event ) {

          if ( event.domain === "previewer" ) {
            iframe.contentWindow[ "popcorn" + that.getCurrentMedia().getId() ].currentTime( event.data.currentTime() );
          }
        } );

      } // fillIframe
    } // exnteds

  });
})(window, document, undefined, Butter);
<commit_msg>Fixed one of the listeners that was affected by the previous change<commit_after>(function (window, document, undefined, Butter) {

  var urlRegex, videoURL,
    iframe, iframeBody,
    popcornString, butterId,
    userSetMedia, videoString,
    popcornURL, originalHead,
    popcorns;

  Butter.registerModule( "previewer", {

    // setup function used to set default values, as well as setting up the iframe
    setup: function( options ) {

      originalHead = {};
      popcornURL = options.popcornURL || "http://popcornjs.org/code/dist/popcorn-complete.js";
      urlRegex = /(?:http:\/\/www\.|http:\/\/|www\.|\.|^)(youtu|vimeo|soundcloud|baseplayer)/;
      layout = options.layout;
      butterIds = {};
      userSetMedia = options.media;
      popcorns = {};
      videoString = {};

      var that = this,
          targetSrc = document.getElementById( options.target );

        // check if target is a div or iframe
      if ( targetSrc.tagName === "DIV" ) {

        target = document.getElementById( options.target );

        // force iframe to fill parent and set source
        iframe = document.createElement( "IFRAME" );
        iframe.src = layout;
        iframe.width = target.style.width;
        iframe.height = target.style.height;
        target.appendChild( iframe );

        // begin scraping once iframe has loaded, remove listener when complete
        iframe.addEventListener( "load", function (e) {
          that.scraper( iframe, options.callback );
          this.removeEventListener( "load", arguments.callee, false );
        }, false);

      } else if ( targetSrc.tagName === "IFRAME" ) {

        iframe = targetSrc;
        iframe.src = options.layout;

        targetSrc.addEventListener( "load", function (e) {
          that.scraper( iframe, options.callback );
          this.removeEventListener( "load", arguments.callee, false );
        }, false);
      } // else
    }, // setup

    extend: {

      // scraper function that scrapes all DOM elements of the given layout,
      // only scrapes elements with the butter-data attribute
      scraper: function( iframe, callback ) {

        // obtain a reference to the iframes body
        var doc = ( iframe.contentWindow || iframe.contentDocument ).document;
        var body = doc.getElementsByTagName( "BODY" );
            that = this;

        Butter.extend( originalHead, ( iframe.contentWindow || iframe.contentDocument ).document.head );

        //originalHead = iframe.contentWindow.document.head;

        // store original iframeBody incase we rebuild
        var ifrmBody = ( iframe.contentWindow || iframe.contentDocument ).document;
        iframeBody = "" + ifrmBody.body.innerHTML + "\n";

        // function to ensure body is actually there
        var ensureLoaded = function() {

          if ( body.length < 1 ) {
            setTimeout( function() {
              ensureLoaded();
            }, 5 );
          } else {

            // begin scraping once body is actually there, call callback once done
            bodyReady( body[ 0 ].children );
            callback();
          } // else
        } // ensureLoaded

        ensureLoaded();

        // scraping is done here
        function bodyReady( children ) {

          // loop for every child of the body
          for( var i = 0; i < children.length; i++ ) {

            // if DOM element has an data-butter tag that is equal to target or media,
            // add it to butters target list with a respective type
            if( children[ i ].getAttribute( "data-butter" ) === "target" ) {
              that.addTarget( {
                name: children[ i ].id,
                type: "target"
              } );
            } else if( children[ i ].getAttribute( "data-butter" ) === "media" ) {
              that.addMedia( {
                name: children[ i ].id,
                media: userSetMedia
              } );
            } // else

            // ensure we get every child, search recursively
            if ( children[ i ].children.length > 0 ) {

              bodyReady( children[ i ].children );
            } // if
          } // for
        } // ok

      }, // scraper

      // buildPopcorn function, builds an instance of popcorn in the iframe and also
      // a local version of popcorn
      buildPopcorn: function( videoTarget, callback ) {

        videoURL = this.getCurrentMedia().getMedia();

        // default to first butter-media tagged object if none is specified
        videoTarget = videoTarget.getName();

        var bpIframe = ( iframe.contentWindow || iframe.contentDocument ).document;

        // create a string that will create an instance of popcorn with the proper video source
        popcornString = "document.addEventListener('DOMContentLoaded', function () {\n";

        var regexResult = urlRegex.exec( videoURL ) || "",
            players = [], that = this;

        players[ "youtu" ] = function() {
          bpIframe.getElementById( videoTarget ).innerHTML = "";
          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( Popcorn.youtube( '" + videoTarget + "', '" +
            videoURL + "', {\n" +
            "width: 430, height: 300\n" +
          "} ) );\n";
        };

        players[ "vimeo " ] = function() {
          bpIframe.getElementById( videoTarget ).innerHTML = "";
          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( Popcorn.vimeo( '" + videoTarget + "', '" +
          videoURL + "', {\n" +
            "css: {\n" +
              "width: '430px',\n" +
              "height: '300px'\n" +
            "}\n" +
          "} ) );\n";
        };

        players[ "soundcloud" ] = function() {
          bpIframe.getElementById( videoTarget ).innerHTML = "";
          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( Popcorn.soundcloud( '" + videoTarget + "'," +
          " '" + videoURL + "' ) );\n";
        };

        players[ "baseplayer" ] = function() {
          bpIframe.getElementById( videoTarget ).innerHTML = "";
          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( Popcorn.baseplayer( '" + videoTarget + "' ) );\n";
        };

        players[ undefined ] = function() {
          var src = document.createElement( "source" ),
          video = document.createElement( "video" );
          src.src = videoURL;

          video.style.width = videoTarget.width;
          video.style.height = videoTarget.height;
          video.appendChild( src );
          video.controls = true;
          video.id = videoTarget + "-butter";

          bpIframe.getElementById( videoTarget ).appendChild( video );

          var vidId = "#" + video.id;

          videoString[ that.getCurrentMedia().getId() ] = "popcorn" + that.getCurrentMedia().getId() + " = Popcorn( '" + vidId + "');\n";
        };

        // call certain player function depending on the regexResult
        players[ regexResult[ 1 ] ]();

        for( video in videoString ) {
          popcornString += videoString[ video ];
        }

        // if for some reason the iframe is refreshed, we want the most up to date popcorn code
        // to be represented in the head of the iframe, incase someone views source
        for( popcorn in popcorns ) {

          var trackEvents = popcorns[ popcorn ].getTrackEvents();

          if ( trackEvents ) {

            // loop through each track event
            for ( var k = 0; k < trackEvents.length; k++ ) {

              // obtain all of the options in the manifest
              var options = trackEvents[ k ]._natives.manifest.options;
              popcornString += " popcorn" + popcorn + "." + trackEvents[ k ]._natives.type + "({\n";

              // for each option
              for ( item in options ) {

                if ( options.hasOwnProperty( item ) ) {

                  // add the data to the string so it looks like normal popcorn code
                  // that someone would write
                  popcornString += item + ": '" + trackEvents[ k ][ item ] + "',\n";
                } // if
              } // for

              popcornString += "});";

            } // for
          } // if
        }

        popcornString += "}, false);";

        this.fillIframe( callback );
      },

      getPopcorn: function( callback ) {
        var popcornz = "var " + videoString;

        // if for some reason the iframe is refreshed, we want the most up to date popcorn code
        // to be represented in the head of the iframe, incase someone views source
        for( popcorn in popcorns ) {

          var trackEvents = popcorns[ popcorn ].getTrackEvents();

          if ( trackEvents ) {

            // loop through each track event
            for ( var k = 0; k < trackEvents.length; k++ ) {

              // obtain all of the options in the manifest
              var options = trackEvents[ k ]._natives.manifest.options;
              popcornz += "popcorn" + popcorn + "." + trackEvents[ k ]._natives.type + "({\n";

              // for each option
              for ( item in options ) {

                if ( options.hasOwnProperty( item ) ) {

                  // add the data to the string so it looks like normal popcorn code
                  // that someone would write
                  popcornz += item + ": '" + trackEvents[ k ][ item ] + "',\n";
                } // if
              } // for

              popcornz += "});\n";

            } // for
          } // if
        }

        return popcornz;

      },

      getRegistry: function() {
        var ifrme = iframe.contentWindow || iframe.contentDocument;
        return ifrme.Popcorn.registry;
      },

      // fillIframe function used to populate the iframe with changes made by the user,
      // which is mostly managing track events added by the user
      fillIframe: function( callback ) {

        var popcornScript, iframeHead, body,
            that = this, doc = ( iframe.contentWindow || iframe.contentDocument ).document;

        // create a script within the iframe and populate it with our popcornString
        popcornScript = doc.createElement( "script" );
        popcornScript.innerHTML = popcornString;

        doc.head.appendChild( popcornScript );

        // create a new head element with our new data
        iframeHead = "" + originalHead.innerHTML + "\n\n";

        iframeHead += "\n\n";

        // create a new body element with our new data
        body = doc.body.innerHTML;

        // open, write our changes to the iframe, and close it
        doc.open();
        doc.write( "\n" + iframeHead + body + "\n" );
        doc.close();

        var popcornReady = function( e, callback2 ) {

          var popcornIframe = iframe.contentWindow || iframe.contentDocument;
          var framePopcorn = popcornIframe[ "popcorn" + that.getCurrentMedia().getId() ];

          if ( !framePopcorn ) {
            setTimeout( function() {
              popcornReady( e, callback2 );
            }, 10 );
          } else {
            callback2 && callback2( framePopcorn );
          } // else
        }

        popcornReady( null, function( framePopcorn ) {

          var videoReady = function() {

            if( framePopcorn.media.readyState >= 2 || framePopcorn.media.duration > 0 ) {
              that.duration( framePopcorn.media.duration );

              that.trigger( "mediaready", that.getCurrentMedia() );
              framePopcorn.media.addEventListener( "timeupdate", function() {

                that.currentTime( framePopcorn.media.currentTime );
                that.trigger( "mediatimeupdate", that.getCurrentMedia() );
              },false);
              callback && callback();
            } else {
              setTimeout( function() {
                videoReady( framePopcorn );
              }, 10);
            }
          }
          videoReady( framePopcorn );
        } );

        this.teAdded = function( event ) {
          var that = this, e = event.data;

          popcornReady( e, function( framePopcorn ) {

            if( !popcorns[ that.getCurrentMedia().getId() ] ) {
                popcorns[ that.getCurrentMedia().getId() ] = framePopcorn;
            } else {
              framePopcorn = popcorns[ that.getCurrentMedia().getId() ];
            }

            framePopcorn.removeTrackEvent( butterIds[ e.getId() ] );

            // add track events to the iframe verison of popcorn
            framePopcorn[ e.type ]( ( iframe.contentWindow || iframe.contentDocument.parentWindow ).Popcorn.extend( {},
              e.popcornOptions ) );

            butterIds[ e.getId() ] = framePopcorn.getLastTrackEventId();

            e.manifest = framePopcorn.getTrackEvent( butterIds[ e.getId() ] )._natives.manifest;

          } );
        }

        // listen for a trackeventadded
        this.listen( "trackeventupdated", function ( e ) {
          this.teAdded( e );
        }); // listener

        this.listen( "trackeventadded", function ( e ) {
          e = e.data;
          popcornReady( e, function( framePopcorn ) {

            if( !popcorns[ that.getCurrentMedia().getId() ] ) {
              popcorns[ that.getCurrentMedia().getId() ] = framePopcorn;
            } else {
              framePopcorn = popcorns[ that.getCurrentMedia().getId() ];
            }

            // add track events to the iframe verison of popcorn
            framePopcorn[ e.type ]( ( iframe.contentWindow || iframe.contentDocument ).Popcorn.extend( {},
              e.popcornOptions ) );

            butterIds[ e.getId() ] = framePopcorn.getLastTrackEventId();

            e.manifest = framePopcorn.getTrackEvent( butterIds[ e.getId() ] )._natives.manifest;
          } );
        }); // listener

        this.listen( "trackeventremoved", function( e ) {
          var ifrme = iframe.contentWindow || iframe.contentDocument;
          ifrme[ "popcorn" + that.getCurrentMedia().getId() ].removeTrackEvent( butterIds[ e.data.getId() ] );
        } );

        this.listen( "mediachanged", function( e ) {
          that.buildPopcorn( butter.getAllMedia()[ 0 ] );
        } );

        this.listen( "mediatimeupdate", function( event ) {

          if ( event.domain === "previewer" ) {
            iframe.contentWindow[ "popcorn" + that.getCurrentMedia().getId() ].currentTime( event.data.currentTime() );
          }
        } );

      } // fillIframe
    } // exnteds

  });
})(window, document, undefined, Butter);
<|endoftext|>


<commit_before>import React from 'react';
import SingleUnitOnMap from './SingleUnitOnMap';
import {sortByCondition} from '../helpers';

export const UnitsOnMap = ({units, selectedUnitId, openUnit}) => {
  let unitsInOrder = units.slice();

  // Draw things in condition order
  unitsInOrder = sortByCondition(unitsInOrder).reverse();

  if(selectedUnitId) {
    const index = unitsInOrder.findIndex((unit) => unit.id === selectedUnitId);
    const selectedUnit = unitsInOrder[index];

    unitsInOrder = [
      ...unitsInOrder.slice(0, index),
      ...unitsInOrder.slice(index + 1),
      selectedUnit
    ];
  }

  return(

    {
      unitsInOrder && unitsInOrder.map(
        (unit, index) => //{console.log(unit); return
getAttr(unit.name)
;}
          <SingleUnitOnMap isSelected={unit.id === selectedUnitId} unit={unit} key={index} openUnit={openUnit} />
      )
    }

  );
};

export default UnitsOnMap;
<commit_msg>Render selected unit on map only when there’s units available<commit_after>import React from 'react';
import isEmpty from 'lodash/isEmpty';
import SingleUnitOnMap from './SingleUnitOnMap';
import {sortByCondition} from '../helpers';

export const UnitsOnMap = ({units, selectedUnitId, openUnit}) => {
  let unitsInOrder = units.slice();

  // Draw things in condition order
  unitsInOrder = sortByCondition(unitsInOrder).reverse();

  if(!isEmpty(unitsInOrder) && selectedUnitId) {
    const index = unitsInOrder.findIndex((unit) => unit.id === selectedUnitId);
    const selectedUnit = unitsInOrder[index];

    unitsInOrder = [
      ...unitsInOrder.slice(0, index),
      ...unitsInOrder.slice(index + 1),
      selectedUnit
    ];
  }

  return(

    {
      !isEmpty(unitsInOrder) && unitsInOrder.map(
        (unit, index) =>
          <SingleUnitOnMap isSelected={unit.id === selectedUnitId} unit={unit} key={index} openUnit={openUnit} />
      )
    }

  );
};

export default UnitsOnMap;
<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe(FILL_ME_IN);

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(FILL_ME_IN);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe(FILL_ME_IN);
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>Made test for extra function arguments pass.<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe("first");

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(undefined);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe(FILL_ME_IN);

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe(FILL_ME_IN);

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>WINDOW_CONTENTS = window.location.href.split('/')

function currentVersion(){
    if (WINDOW_CONTENTS.includes('$web') && WINDOW_CONTENTS.length > 5)
    {
      return WINDOW_CONTENTS[6];
    }
    else {
      return ''
    }
}

function currentPackage(){
    if (WINDOW_CONTENTS.includes('$web') && WINDOW_CONTENTS.length > 5)
    {
      return WINDOW_CONTENTS[5];
    }
    else {
      return ''
    }
}

function httpGetAsync(targetUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
          callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", targetUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

function showSelectors(selectors){
  selectors.forEach(function(item, index){
    $(item).show()
  })
}

function hideSelectors(selectors){
  selectors.forEach(function(item, index){
    $(item).hide()
  })
}

function populateOptions(optionSelector, otherSelectors){
  if(currentPackage()){
    var versionRequestUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + currentPackage() + "/versioning/versions"

    httpGetAsync(versionRequestUrl, function(responseText){
      if(responseText){
        options = responseText.match(/[^\r\n]+/g)

        populateVersionDropDown(optionSelector, options)
        showSelectors(otherSelectors)

        $(optionSelector).change(function(){
          targetVersion = $(this).val()

          url = WINDOW_CONTENTS.slice()
          url[6] = targetVersion
          window.location.href = url.join('/')
        });
      }
    })
  }
}

function populateVersionDropDown(selector, values){
    var select = $(selector);

    $('option', select).remove();

    $.each(values, function(index, text) {
      $('<option/>', { 'value' : text, 'text': text }).appendTo(select);
    });
    select.val(currentVersion());
}

function getPackageUrl(language, package, version){
  return "https://azuresdkdocs.blob.core.windows.net/$web/" + language + "/" + package + "/"+ version + "/index.html"
}

function populateIndexList(selector, packageName)
{
  url = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions"

  httpGetAsync(url, function (responseText){
    if(responseText){
      options = responseText.match(/[^\r\n]+/g)

      for (var i in options){
        $(selector).append('
' + options[i] + '
')
      }
    }
    else {
      $(selector).append('
No discovered versions present in blob storage.
')
    }
  })
}

// language specific
SELECTED_LANGUAGE = 'python'
populateOptions('#versionSelector', ['#versionSelector', '#versionSelectorHeader'])<commit_msg>update the javascript to currectly select the latest version as if we're in the latest folder (#10544)<commit_after>WINDOW_CONTENTS = window.location.href.split('/')

function currentVersion(){
    if (WINDOW_CONTENTS.includes('$web') && WINDOW_CONTENTS.length > 5)
    {
      return WINDOW_CONTENTS[6];
    }
    else {
      return ''
    }
}

function currentPackage(){
    if (WINDOW_CONTENTS.includes('$web') && WINDOW_CONTENTS.length > 5)
    {
      return WINDOW_CONTENTS[5];
    }
    else {
      return ''
    }
}

function httpGetAsync(targetUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
          callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", targetUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

function showSelectors(selectors){
  selectors.forEach(function(item, index){
    $(item).show()
  })
}

function hideSelectors(selectors){
  selectors.forEach(function(item, index){
    $(item).hide()
  })
}

function populateOptions(optionSelector, otherSelectors){
  if(currentPackage()){
    var versionRequestUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + currentPackage() + "/versioning/versions"

    httpGetAsync(versionRequestUrl, function(responseText){
      if(responseText){
        options = responseText.match(/[^\r\n]+/g)

        populateVersionDropDown(optionSelector, options)
        showSelectors(otherSelectors)

        $(optionSelector).change(function(){
          targetVersion = $(this).val()

          url = WINDOW_CONTENTS.slice()
          url[6] = targetVersion
          window.location.href = url.join('/')
        });
      }
    })
  }
}

function populateVersionDropDown(selector, values){
    var select = $(selector)

    $('option', select).remove()

    $.each(values, function(index, text) {
      $('<option/>', { 'value' : text, 'text': text }).appendTo(select)
    });

    var version = currentVersion()
    if(version==='latest'){
      select.selectedIndex = 0
    }
    else {
      select.val(version)
    }
}

function getPackageUrl(language, package, version){
  return "https://azuresdkdocs.blob.core.windows.net/$web/" + language + "/" + package + "/"+ version + "/index.html"
}

function populateIndexList(selector, packageName)
{
  url = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions"

  httpGetAsync(url, function (responseText){
    if(responseText){
      options = responseText.match(/[^\r\n]+/g)

      for (var i in options){
        $(selector).append('
' + options[i] + '
')
      }
    }
    else {
      $(selector).append('
No discovered versions present in blob storage.
')
    }
  })
}

// language specific
SELECTED_LANGUAGE = 'python'
populateOptions('#versionSelector', ['#versionSelector', '#versionSelectorHeader'])<|endoftext|>


<commit_before>var _ = require('lodash');
var log = require('winston');
var path = require('canonical-path');

module.exports = {
  name: 'error-docs',
  description: 'Compute the various fields for docs in the Error area',
  runAfter: ['tags-extracted'],
  init: function(config, injectables) {
    injectables.value('errorNamespaces', {});

    var minerrInfoPath = config.get('processing.errors.minerrInfoPath');
    if ( !minerrInfoPath ) {
      throw new Error('Error in configuration: Please provide a path to the minerr info file (errors.json) ' +
        'in the `config.processing.errors.minerrInfoPath` property');
    }
    injectables.value('minerrInfo', require(minerrInfoPath));
  },
  process: function(docs, partialNames, errorNamespaces, minerrInfo) {

    // Create error namespace docs and attach error docs to each
    _.forEach(docs, function(doc) {
      if ( doc.docType === 'error' ) {

        var namespaceDoc = errorNamespaces[doc.namespace];
        if ( !namespaceDoc ) {
          // First time we came across this namespace, so create a new one
          namespaceDoc = errorNamespaces[doc.namespace] = {
            area: doc.area,
            name: doc.namespace,
            errors: [],
            path: path.dirname(doc.path),
            outputPath: path.dirname(doc.outputPath) + '.html',
            docType: 'errorNamespace'
          };
        }

        // Add this error to the namespace
        namespaceDoc.errors.push(doc);
        doc.namespace = namespaceDoc;

        doc.formattedErrorMessage = minerrInfo.errors[doc.namespace.name][doc.name];

      }

    });

    return docs.concat(_.values(errorNamespaces));
  }
};<commit_msg>chore(doc-gen): fix error-doc processor<commit_after>var _ = require('lodash');
var log = require('winston');
var path = require('canonical-path');

module.exports = {
  name: 'error-docs',
  description: 'Compute the various fields for docs in the Error area',
  runAfter: ['tags-extracted'],
  init: function(config, injectables) {
    injectables.value('errorNamespaces', {});

    var minerrInfoPath = config.get('processing.errors.minerrInfoPath');
    if ( !minerrInfoPath ) {
      throw new Error('Error in configuration: Please provide a path to the minerr info file (errors.json) ' +
        'in the `config.processing.errors.minerrInfoPath` property');
    }
    injectables.value('minerrInfo', require(minerrInfoPath));
  },
  process: function(docs, partialNames, errorNamespaces, minerrInfo) {

    // Create error namespace docs and attach error docs to each
    _.forEach(docs, function(doc) {
      if ( doc.docType === 'error' ) {

        // Parse out the error info from the id
        parts = doc.name.split(':');
        doc.namespace = parts[0];
        doc.name = parts[1];

        var namespaceDoc = errorNamespaces[doc.namespace];
        if ( !namespaceDoc ) {
          // First time we came across this namespace, so create a new one
          namespaceDoc = errorNamespaces[doc.namespace] = {
            area: doc.area,
            name: doc.namespace,
            errors: [],
            path: path.dirname(doc.path),
            outputPath: path.dirname(doc.outputPath) + '.html',
            docType: 'errorNamespace'
          };
        }

        // Add this error to the namespace
        namespaceDoc.errors.push(doc);
        doc.namespace = namespaceDoc;

        doc.formattedErrorMessage = minerrInfo.errors[doc.namespace.name][doc.name];

      }

    });

    return docs.concat(_.values(errorNamespaces));
  }
};<|endoftext|>


<commit_before>"use strict";

// ----------------------------------------------------------------------------

const ccxt = require ('../../ccxt.js')

// ----------------------------------------------------------------------------

;(async () => {

    const exchange = new ccxt.bittrex ({
        'apiKey': 'YOUR_API_KEY',
        'secret': 'YOUR_SECRET_KEY',
        'verbose': false, // set to true to see more debugging output
        'timeout': 60000,
        'enableRateLimit': true, // add this
    })

    // try to load markets first, retry on request timeouts until it succeeds:

    while (true) {

        try {

            await exchange.loadMarkets ();
            break;

        } catch (e) {

            if (e instanceof ccxt.RequestTimeout)
                console.log (Date.now (), e.constructor.name, e.message)
        }
    }

    const symbol = 'ETH/BTC'
    const orderType = 'limit'
    const side = 'sell'
    const amount = 0.321;
    const price = 0.123;

    // try just one attempt to create an order

    try {

        const response = await exchange.createOrder (symbol, orderType, side, amount, price);
        console.log (response);
        console.log ('Succeeded');

    } catch (e) {

        console.log (Date.now(), e.constructor.name, e.message)
        console.log ('Failed');

    }

}) ()
<commit_msg>minor edits to examples/js/create-order-handle-errors.js for human-readable timestamps #1956<commit_after>"use strict";

// ----------------------------------------------------------------------------

const ccxt = require ('../../ccxt.js')

// ----------------------------------------------------------------------------

;(async () => {

    const exchange = new ccxt.bittrex ({
        'apiKey': 'YOUR_API_KEY',
        'secret': 'YOUR_SECRET_KEY',
        'verbose': false, // set to true to see more debugging output
        'timeout': 60000,
        'enableRateLimit': true, // add this
    })

    // try to load markets first, retry on request timeouts until it succeeds:

    while (true) {

        try {

            await exchange.loadMarkets ();
            break;

        } catch (e) {

            if (e instanceof ccxt.RequestTimeout)
                console.log (exchange.iso8601 (Date.now ()), e.constructor.name, e.message)
        }
    }

    const symbol = 'ETH/BTC'
    const orderType = 'limit'
    const side = 'sell'
    const amount = 0.321;
    const price = 0.123;

    // try just one attempt to create an order

    try {

        const response = await exchange.createOrder (symbol, orderType, side, amount, price);
        console.log (response);
        console.log ('Succeeded');

    } catch (e) {

        console.log (exchange.iso8601 (Date.now ()), e.constructor.name, e.message)
        console.log ('Failed');

    }

}) ()
<|endoftext|>


<commit_before>

function PitchStairCase() {

    this.Stairs = [];

    this.makeStairs = function (start) {

        if(start === -1) {
            start = 0;
        } else {
            for (var j = start; j < this.Stairs.length-1; j++) {
                console.log(j);
                console.log(docById("playStairTable" + j));
                 docById("playStairTable" + j).remove();
                docById("stairTable"+ j).remove();
            }
        }
        var thisStair = this;
        var iconSize = Math.floor(this.cellScale * 24);

        var StairDiv = docById('pitchstaircase');
        var StairDivPosition = StairDiv.getBoundingClientRect();

        var playPitchDiv = docById('playPitch');
        var playPitchDivPosition = playPitchDiv.getBoundingClientRect();

        for (var i = start; i < thisStair.Stairs.length; i++) {

            var playTable = document.createElement('TABLE');
            playTable.setAttribute('id', 'playStairTable' + i);
            playTable.style.textAlign = 'center';
            playTable.style.borderCollapse = 'collapse';
            playTable.cellSpacing = 0;
            playTable.cellPadding = 0;
            playPitchDiv.appendChild(playTable);

            var header = playTable.createTHead();
            var playrow = header.insertRow(-1);
            playrow.style.left = Math.floor(playPitchDivPosition.left) + 'px';
            playrow.style.top = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
            playrow.setAttribute('id', "playStair" + i);

            var playcell = playrow.insertCell(-1);
            playcell.style.width = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
            playcell.innerHTML = '    ';
            playcell.style.minWidth = playcell.style.width;
            playcell.style.maxWidth = playcell.style.width;
            playcell.style.height = Math.floor(RHYTHMRULERHEIGHT * this.cellScale) + 'px';
            playcell.style.backgroundColor = MATRIXBUTTONCOLOR;

            playcell.onclick = function() {
                console.log(playcell.parentNode.id);
                thisStair.PlayOne(playcell.parentNode.id[9]);
            };

            var StairTable = document.createElement('TABLE');
            StairTable.setAttribute('id', 'stairTable' + i);
            StairTable.style.textAlign = 'center';
            StairTable.style.borderCollapse = 'collapse';
            StairTable.cellSpacing = 0;
            StairTable.cellPadding = 0;
            StairDiv.appendChild(StairTable);

            var header = StairTable.createTHead();
            var row = header.insertRow(-1);
            row.style.left = Math.floor(StairDivPosition.left) + 'px';
            row.style.top = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
            row.setAttribute('id','stair' + i)

            var solfege = this.Stairs[i][0];
            var octave = this.Stairs[i][1];

            var solfegetonote = this.logo.getNote(solfege, octave, 0, this.logo.keySignature[this.logoturtle])[0];

            var cell = row.insertCell(-1);
            cell.style.width = (StairDivPosition.width)* parseFloat(this.Stairs[0][2]/this.Stairs[i][2]) * this.cellScale/2 + 'px';
            cell.innerHTML = thisStair.Stairs[i][0] + thisStair.Stairs[i][1] + " "  + Math.floor(thisStair.Stairs[i][2]);
            cell.style.minWidth = cell.style.width;
            cell.style.maxWidth = cell.style.width;
            cell.style.height = Math.floor(RHYTHMRULERHEIGHT * this.cellScale) + 'px';
            cell.style.lineHeight = 60 + '%';
            cell.style.backgroundColor = MATRIXNOTECELLCOLOR;

            cell.addEventListener('click', function(event) {
                thisStair.dissectStair(event);
            });
        }
    }

    this.dissectStair = function(event) {
        var that = this;

        var inputNum = prompt(_('Divide By:'), "3 2");

      //  if(!isInt(inputNum)) {
     //       alert(_('Please Input a Integer'));
     //       inputNum = prompt(_('Divide By:'), 2);
     //   }

        var arr = inputNum.split(" ");
        console.log(arr);

        inputNum = parseFloat(arr[1]/arr[0]);

        if(inputNum === null) {
            return ;
        }
        var oldcell = event.target;
        var frequency = that.Stairs[oldcell.parentNode.id[5]][2];
        var obj = frequencyToPitch(parseFloat(frequency)/inputNum);

        var flag = 0;

        for (var i=0 ; i < this.Stairs.length; i++) {

            if (this.Stairs[i][2] < parseFloat(frequency)/inputNum) {
                this.Stairs.splice(i, 0, [obj[0], obj[1], parseFloat(frequency)/inputNum]);
                flag = 1;
                break;
            }
        }
        if(flag === 0) {
            this.Stairs.push([obj[0], obj[1], parseFloat(frequency)/inputNum]);
        }
        this.makeStairs(i);
    };

    this.PlayOne = function(stairno) {
        var pitchnotes = [];
        console.log(this.Stairs[stairno]);
        var note = this.Stairs[stairno][0] + this.Stairs[stairno][1];
        pitchnotes.push(note.replace(/♭/g, 'b').replace(/♯/g, '#'));
        console.log(pitchnotes);
        this.logo.synth.trigger(pitchnotes, 0.125, 'poly');
    }

    this.playAll = function() {
        var pitchnotes = [];
        var note = this.Stairs[this.Stairs.length-1][0] + this.Stairs[this.Stairs.length-1][1];
        pitchnotes.push(note.replace(/♭/g, 'b').replace(/♯/g, '#'));
        var laststair = this.Stairs.length - 1;
        console.log("Playing stair " + laststair);
        var row = docById('stair' + laststair);
        console.log(row.cells[0]);
        row.cells[0].style.backgroundColor = MATRIXBUTTONCOLOR;
        console.log(row.cells[0]);
        this.logo.synth.trigger(pitchnotes, 1, 'poly');
        this.playAllStairs(this.Stairs.length-2);
    }

    this.playAllStairs = function(stairno) {
        var that = this;
        setTimeout(function () {
            if(stairno > -1) {
                var pitchnotes = [];
                console.log("Playing stair " + stairno);
                var note = that.Stairs[stairno][0] + that.Stairs[stairno][1];
                pitchnotes.push(note.replace(/♭/g, 'b').replace(/♯/g, '#'));
                var row = docById('stair' + stairno);
                console.log(row.cells[0]);
                row.cells[0].style.backgroundColor = MATRIXBUTTONCOLOR;
                console.log(row.cells[0]);
                that.logo.synth.trigger(pitchnotes, 1, 'poly');
                that.playAllStairs(stairno-1);
            } else {
                for(var i = 0; i < that.Stairs.length; i++) {
                    var row = docById('stair' + i);
                    row.cells[0].style.backgroundColor = MATRIXNOTECELLCOLOR;
                }
            }
        }, 1000 + that.logo.turtleDelay);
    }

	this.init = function(logo) {

        console.log(this.Stairs);

		console.log("init PitchStairCase");
		this.logo = logo;

		docById('pitchstaircase').style.display = 'inline';
        console.log('setting PitchStairCase visible');
        docById('pitchstaircase').style.visibility = 'visible';
        docById('pitchstaircase').style.border = 2;

        docById('playPitch').style.display = 'inline';
        docById('playPitch').style.visibility = 'visible';
        docById('playPitch').style.border = 2;

        var w = window.innerWidth;
        this.cellScale = w / 1200;
        docById('pitchstaircase').style.width = Math.floor(w / 2) + 'px';
        docById('pitchstaircase').style.overflowX = 'auto';

    		var thisStair = this;

        var tables = document.getElementsByTagName('TABLE');

      //  console.log(tables);

        var noofTables = tables.length

        for (var i = 0; i < noofTables; i++) {
                tables[0].parentNode.removeChild(tables[0]);
        }

        var iconSize = Math.floor(this.cellScale * 24);

        var x = document.createElement('TABLE');
        x.setAttribute('id', 'buttonTable');
        x.style.textAlign = 'center';
        x.style.borderCollapse = 'collapse';
        x.cellSpacing = 0;
        x.cellPadding = 0;

        var StairDiv = docById('pitchstaircase');
        StairDiv.style.paddingTop = 0 + 'px';
        StairDiv.style.paddingLeft = 0 + 'px';
        StairDiv.appendChild(x);
        StairDivPosition = StairDiv.getBoundingClientRect();

        var x = document.createElement('TABLE');
        x.setAttribute('id', 'playAllStairTable');
        x.style.textAlign = 'center';
        x.style.borderCollapse = 'collapse';
        x.cellSpacing = 0;
        x.cellPadding = 0;

        var playPitchDiv = docById('playPitch');
        playPitchDiv.style.paddingTop = 0 + 'px';
        playPitchDiv.style.paddingLeft = 0 + 'px';
        playPitchDiv.appendChild(x);
        playPitchDivPosition = playPitchDiv.getBoundingClientRect();

        var table = docById('playAllStairTable');
        var header = table.createTHead();
        var row = header.insertRow(-1);
        row.style.left = Math.floor(playPitchDivPosition.left) + 'px';
        row.style.top = Math.floor(playPitchDivPosition.top) + 'px';
        row.setAttribute('id', 'playAllStair');

        var cell = row.insertCell(-1);
        cell.innerHTML = '    ';
        cell.style.width = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.minWidth = cell.style.width;
        cell.style.maxWidth = cell.style.width;
        cell.style.height = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.backgroundColor = MATRIXBUTTONCOLOR;
        cell.onclick = function() {
            thisStair.playAll();
        }

        var table = docById('buttonTable');
        var header = table.createTHead();
        var row = header.insertRow(0);
        row.style.left = Math.floor(StairDivPosition.left) + 'px';
        row.style.top = Math.floor(StairDivPosition.top) + 'px';

        var cell = row.insertCell(-1);
        cell.innerHTML = '    ';
        cell.style.width = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.minWidth = cell.style.width;
        cell.style.maxWidth = cell.style.width;
        cell.style.height = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.backgroundColor = MATRIXBUTTONCOLOR;

        cell.onclick=function() {
            docById('pitchstaircase').style.visibility = 'hidden';
            docById('playPitch').style.visibility = 'hidden';
        };

        cell.onmouseover=function() {
            this.style.backgroundColor = MATRIXBUTTONCOLORHOVER;
        };

        cell.onmouseout=function() {
            this.style.backgroundColor = MATRIXBUTTONCOLOR;
        };

        this.makeStairs(-1);
	};

};<commit_msg>save feature added<commit_after>

function PitchStairCase() {

    this.Stairs = [];

    this.makeStairs = function (start) {

        if(start === -1) {
            start = 0;
        } else {
            for (var j = start; j < this.Stairs.length-1; j++) {
                console.log(j);
                console.log(docById("playStairTable" + j));
                 docById("playStairTable" + j).remove();
                docById("stairTable"+ j).remove();
            }
        }
        var thisStair = this;
        var iconSize = Math.floor(this.cellScale * 24);

        var StairDiv = docById('pitchstaircase');
        var StairDivPosition = StairDiv.getBoundingClientRect();

        var playPitchDiv = docById('playPitch');
        var playPitchDivPosition = playPitchDiv.getBoundingClientRect();

        for (var i = start; i < thisStair.Stairs.length; i++) {

            var playTable = document.createElement('TABLE');
            playTable.setAttribute('id', 'playStairTable' + i);
            playTable.style.textAlign = 'center';
            playTable.style.borderCollapse = 'collapse';
            playTable.cellSpacing = 0;
            playTable.cellPadding = 0;
            playPitchDiv.appendChild(playTable);

            var header = playTable.createTHead();
            var playrow = header.insertRow(-1);
            playrow.style.left = Math.floor(playPitchDivPosition.left) + 'px';
            playrow.style.top = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
            playrow.setAttribute('id', "playStair" + i);

            var playcell = playrow.insertCell(-1);
            playcell.style.width = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
            playcell.innerHTML = '    ';
            playcell.style.minWidth = playcell.style.width;
            playcell.style.maxWidth = playcell.style.width;
            playcell.style.height = Math.floor(RHYTHMRULERHEIGHT * this.cellScale) + 'px';
            playcell.style.backgroundColor = MATRIXBUTTONCOLOR;

            playcell.onclick = function() {
                console.log(playcell.parentNode.id);
                thisStair.PlayOne(playcell.parentNode.id[9]);
            };

            var StairTable = document.createElement('TABLE');
            StairTable.setAttribute('id', 'stairTable' + i);
            StairTable.style.textAlign = 'center';
            StairTable.style.borderCollapse = 'collapse';
            StairTable.cellSpacing = 0;
            StairTable.cellPadding = 0;
            StairDiv.appendChild(StairTable);

            var header = StairTable.createTHead();
            var row = header.insertRow(-1);
            row.style.left = Math.floor(StairDivPosition.left) + 'px';
            row.style.top = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
            row.setAttribute('id','stair' + i)

            var solfege = this.Stairs[i][0];
            var octave = this.Stairs[i][1];

            var solfegetonote = this.logo.getNote(solfege, octave, 0, this.logo.keySignature[this.logoturtle])[0];

            var cell = row.insertCell(-1);
            cell.style.width = (StairDivPosition.width)* parseFloat(this.Stairs[0][2]/this.Stairs[i][2]) * this.cellScale/2 + 'px';
            cell.innerHTML = thisStair.Stairs[i][0] + thisStair.Stairs[i][1] + " "  + Math.floor(thisStair.Stairs[i][2]);
            cell.style.minWidth = cell.style.width;
            cell.style.maxWidth = cell.style.width;
            cell.style.height = Math.floor(RHYTHMRULERHEIGHT * this.cellScale) + 'px';
            cell.style.lineHeight = 60 + '%';
            cell.style.backgroundColor = MATRIXNOTECELLCOLOR;

            cell.addEventListener('click', function(event) {
                thisStair.dissectStair(event);
            });
        }
    }

    this.dissectStair = function(event) {
        var that = this;

        var inputNum = prompt(_('Divide By:'), "3 2");

      //  if(!isInt(inputNum)) {
     //       alert(_('Please Input a Integer'));
     //       inputNum = prompt(_('Divide By:'), 2);
     //   }

        var arr = inputNum.split(" ");
        console.log(arr);

        inputNum = parseFloat(arr[1]/arr[0]);

        if(inputNum === null) {
            return ;
        }
        var oldcell = event.target;
        var frequency = that.Stairs[oldcell.parentNode.id[5]][2];
        var obj = frequencyToPitch(parseFloat(frequency)/inputNum);

        var flag = 0;

        for (var i=0 ; i < this.Stairs.length; i++) {

            if (this.Stairs[i][2] < parseFloat(frequency)/inputNum) {
                this.Stairs.splice(i, 0, [obj[0], obj[1], parseFloat(frequency)/inputNum]);
                flag = 1;
                break;
            }
        }
        if(flag === 0) {
            this.Stairs.push([obj[0], obj[1], parseFloat(frequency)/inputNum]);
        }
        this.makeStairs(i);
    };

    this.PlayOne = function(stairno) {
        var pitchnotes = [];
        console.log(this.Stairs[stairno]);
        var note = this.Stairs[stairno][0] + this.Stairs[stairno][1];
        pitchnotes.push(note.replace(/♭/g, 'b').replace(/♯/g, '#'));
        console.log(pitchnotes);
        this.logo.synth.trigger(pitchnotes, 0.125, 'poly');
    }

    this.playAll = function() {
        var pitchnotes = [];
        var note = this.Stairs[this.Stairs.length-1][0] + this.Stairs[this.Stairs.length-1][1];
        pitchnotes.push(note.replace(/♭/g, 'b').replace(/♯/g, '#'));
        var laststair = this.Stairs.length - 1;
        console.log("Playing stair " + laststair);
        var row = docById('stair' + laststair);
        console.log(row.cells[0]);
        row.cells[0].style.backgroundColor = MATRIXBUTTONCOLOR;
        console.log(row.cells[0]);
        this.logo.synth.trigger(pitchnotes, 1, 'poly');
        this.playAllStairs(this.Stairs.length-2);
    }

    this.playAllStairs = function(stairno) {
        var that = this;
        setTimeout(function () {
            if(stairno > -1) {
                var pitchnotes = [];
                console.log("Playing stair " + stairno);
                var note = that.Stairs[stairno][0] + that.Stairs[stairno][1];
                pitchnotes.push(note.replace(/♭/g, 'b').replace(/♯/g, '#'));
                var row = docById('stair' + stairno);
                console.log(row.cells[0]);
                row.cells[0].style.backgroundColor = MATRIXBUTTONCOLOR;
                console.log(row.cells[0]);
                that.logo.synth.trigger(pitchnotes, 1, 'poly');
                that.playAllStairs(stairno-1);
            } else {
                for(var i = 0; i < that.Stairs.length; i++) {
                    var row = docById('stair' + i);
                    row.cells[0].style.backgroundColor = MATRIXNOTECELLCOLOR;
                }
            }
        }, 1000 + that.logo.turtleDelay);
    }

    this.save = function (stairno) {
        var that = this;
        for (var name in this.logo.blocks.palettes.dict) {
            this.logo.blocks.palettes.dict[name].hideMenu(true);
        }

        this.logo.refreshCanvas();

        setTimeout(function() {
       //     var stair = docById('stair' + stairno);
            var noteobj = frequencyToPitch(that.Stairs[stairno][2]);
            console.log(noteobj);
            var note  = that.Stairs[stairno][0];
            var octave = that.Stairs[stairno][1];

            var newStack = [[0, ['action', {'collapsed': false}], 100, 100, [null, 1, 2, null]], [1, ['text', {'value': 'stair'}], 0, 0, [0]]];
            var endOfStackIdx = 0;
            var previousBlock = 0;

            var pitchblockidx = newStack.length;
            var noteidx = pitchblockidx + 1;
            var octaveidx = pitchblockidx + 2;
            var hiddenidx = pitchblockidx + 3;

            newStack.push([pitchblockidx, 'pitch', 0, 0, [previousBlock, noteidx, octaveidx, hiddenidx]]);
            newStack.push([noteidx, ['text', {'value': note}], 0, 0, [pitchblockidx]]);
            newStack.push([octaveidx, ['number', {'value': octave}], 0, 0, [pitchblockidx]]);
            newStack.push([hiddenidx, 'hidden', 0, 0, [pitchblockidx, null]]);

            var previousBlock = hiddenidx;

            that.logo.blocks.loadNewBlocks(newStack);
            if (stairno > that.Stairs.length - 2) {
                return;
            } else {
                that.save(stairno+1);
            }
        }, 500);
    }

	this.init = function(logo) {

        console.log(this.Stairs);

		console.log("init PitchStairCase");
		this.logo = logo;

		docById('pitchstaircase').style.display = 'inline';
        console.log('setting PitchStairCase visible');
        docById('pitchstaircase').style.visibility = 'visible';
        docById('pitchstaircase').style.border = 2;

        docById('playPitch').style.display = 'inline';
        docById('playPitch').style.visibility = 'visible';
        docById('playPitch').style.border = 2;

        var w = window.innerWidth;
        this.cellScale = w / 1200;
        docById('pitchstaircase').style.width = Math.floor(w / 2) + 'px';
        docById('pitchstaircase').style.overflowX = 'auto';

    		var thisStair = this;

        var tables = document.getElementsByTagName('TABLE');

      //  console.log(tables);

        var noofTables = tables.length

        for (var i = 0; i < noofTables; i++) {
                tables[0].parentNode.removeChild(tables[0]);
        }

        var iconSize = Math.floor(this.cellScale * 24);

        var x = document.createElement('TABLE');
        x.setAttribute('id', 'buttonTable');
        x.style.textAlign = 'center';
        x.style.borderCollapse = 'collapse';
        x.cellSpacing = 0;
        x.cellPadding = 0;

        var StairDiv = docById('pitchstaircase');
        StairDiv.style.paddingTop = 0 + 'px';
        StairDiv.style.paddingLeft = 0 + 'px';
        StairDiv.appendChild(x);
        StairDivPosition = StairDiv.getBoundingClientRect();

        var x = document.createElement('TABLE');
        x.setAttribute('id', 'playAllStairTable');
        x.style.textAlign = 'center';
        x.style.borderCollapse = 'collapse';
        x.cellSpacing = 0;
        x.cellPadding = 0;

        var playPitchDiv = docById('playPitch');
        playPitchDiv.style.paddingTop = 0 + 'px';
        playPitchDiv.style.paddingLeft = 0 + 'px';
        playPitchDiv.appendChild(x);
        playPitchDivPosition = playPitchDiv.getBoundingClientRect();

        var table = docById('playAllStairTable');
        var header = table.createTHead();
        var row = header.insertRow(-1);
        row.style.left = Math.floor(playPitchDivPosition.left) + 'px';
        row.style.top = Math.floor(playPitchDivPosition.top) + 'px';
        row.setAttribute('id', 'playAllStair');

        var cell = row.insertCell(-1);
        cell.innerHTML = '    ';
        cell.style.width = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.minWidth = cell.style.width;
        cell.style.maxWidth = cell.style.width;
        cell.style.height = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.backgroundColor = MATRIXBUTTONCOLOR;
        cell.onclick = function() {
            thisStair.playAll();
        }

        var table = docById('buttonTable');
        var header = table.createTHead();
        var row = header.insertRow(0);
        row.style.left = Math.floor(StairDivPosition.left) + 'px';
        row.style.top = Math.floor(StairDivPosition.top) + 'px';

        var cell = row.insertCell(-1);
        cell.innerHTML = '    ';
        cell.style.width = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.minWidth = cell.style.width;
        cell.style.maxWidth = cell.style.width;
        cell.style.height = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.backgroundColor = MATRIXBUTTONCOLOR;

        cell.onclick=function() {
            thisStair.save(0);
        };

        cell.onmouseover=function() {
            this.style.backgroundColor = MATRIXBUTTONCOLORHOVER;
        };

        cell.onmouseout=function() {
            this.style.backgroundColor = MATRIXBUTTONCOLOR;
        };

        var cell = row.insertCell(1);
        cell.innerHTML = '    ';
        cell.style.width = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.minWidth = cell.style.width;
        cell.style.maxWidth = cell.style.width;
        cell.style.height = Math.floor(MATRIXBUTTONHEIGHT * this.cellScale) + 'px';
        cell.style.backgroundColor = MATRIXBUTTONCOLOR;

        cell.onclick=function() {
            docById('pitchstaircase').style.visibility = 'hidden';
            docById('playPitch').style.visibility = 'hidden';
        };

        cell.onmouseover=function() {
            this.style.backgroundColor = MATRIXBUTTONCOLORHOVER;
        };

        cell.onmouseout=function() {
            this.style.backgroundColor = MATRIXBUTTONCOLOR;
        };

        this.makeStairs(-1);
	};

};<|endoftext|>


<commit_before>const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

const asyncValidate = (values /*, dispatch */) => {
  return sleep(1000).then(() => {
    // simulate server latency
    if (['foo@foo.com', 'bar@bar.com'].includes(values.email)) {
      throw {email: 'Email already Exists'}
    }
  })
}

export default asyncValidate
<commit_msg>disabled no-throw-literal eslint rule on a single line<commit_after>const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

const asyncValidate = (values /*, dispatch */) => {
  return sleep(1000).then(() => {
    // simulate server latency
    if (['foo@foo.com', 'bar@bar.com'].includes(values.email)) {
      // eslint-disable-next-line no-throw-literal
      throw { email: 'Email already Exists' }
    }
  })
}

export default asyncValidate
<|endoftext|>