<commit_before>async function(args) {
/*
created_timestamp(-1)
base_component_id("app_editor_3")
is_app(true)
display_name("Editor App V3")
description("This will return the editor app V3")
logo_url("https://2.bp.blogspot.com/-6Hdixw3dFxk/WfSQOnB9lDI/AAAAAAAAFFc/84DRGgcwOpYBOgknkHQ-qmgxvFv1D-iHACLcBGAs/s1600/BracketsDarks.PNG")
load_once_from_file(true)
*/
    //
    // Hack city!!! Turn off the component cache so that we can enable hot reloading of components
    //
    isStaticHtmlPageApp = false
    //
    //
    //

    await loadV2("appEmbed")

    Vue.component("app_editor_3",
    {
      props: ['app_id', 'card_index'],
      template: `

{{app_component_name?"" + app_component_name.substring(0,30):""}}{{(app_component_name && ((app_component_name.length > 30))?"...":"")}}

                        <input  class='caption' style='display: inline-block;' v-if='edit_name' v-model='new_name'></input>
                        <button type=button class='btn btn-primary' style='margin-left: 10px' v-if='edit_name' v-on:click='(async function(){await rename(new_name)})()'>Save new name</button>

                            <button  type=button class='btn btn-primary'      v-on:click='chooseApp()'  >App</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='chooseCode()' >Code</button>
                            <button  type=button class=' btn btn-info'        v-on:click='chooseBoth()' >Both</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='copyAppMethod(base_component_id,null)' >Copy app</button>
                            <button  type=button class=' btn btn-info'        v-on:click='embedApp(base_component_id)' >Embed app</button>
                            <button  v-if='(editor_component != "editor_component") && (!read_only)' type=button class=' btn btn-secondary'   v-on:click='editAsText()' >Edit as text</button>

                        <appEmbed v-bind:base_component_id_arg='base_component_id'></appEmbed>

                          <component  v-bind:is="editor_component" v-if="editor_loaded" ref="editorComponentRef">
                                          <button v-if='!read_only'
                                                  v-bind:style="'visibility: ' + ((app_shown && code_shown)?'':'hidden')"
                                                  slot-scope="editor_component"
                                                  v-on:click='setTimeout(async function(){await save(base_component_id, code_id,null)},100)'
                                                  type="button" class="btn btn-primary btn-sm">

                                                      Save changes
                                         </button>
                          </component>

                                    {{show_new_tab_tooltip?"Open page in new browser tab (shareable :)":""}}
                                    {{show_open_app_tooltip?"Download as HTML app (emailable :)":""}}

                                ← → ↻
                                ❏

                                    <input  readonly size="40" style='font-size: 13px;'
                                        v-bind:value='"http://" + location.hostname + ":" + location.port + "/app/" + base_component_id + ".html"'></input>

                                ♨

                          <component  v-bind:is="app_component_name" v-if="app_loaded">
                            APP HERE
                          </component>

       `
       ,
       data: function() {
           return {
               editor_loaded:       false,
               selected_app:        '',
               editor_component:    null,
               app_loaded:          false,
               app_component_name:  null,
               base_component_id:   null,
               code_id:            "...",
               version: 0,
               app_width:           "33%",
               code_width:          "63%",
               app_shown:           true,
               code_shown:          true,
               read_only:           false,
               mode:                "edit",
               show_name:           true,
               edit_name:           false,
               new_name:            "",
               show_new_tab_tooltip:false,
               show_open_app_tooltip:false
           }
       }
       ,

       methods: {
            // ---------------------------------------------------------------
            //                         chooseApp
            //
            // This is called when the end user selects "app"
            // ---------------------------------------------------------------
            chooseApp: async function() {
                var mm = this
                this.code_width = "0%"
                this.code_shown = false

                this.app_width = "95%"
                this.app_shown = true

                this.mode      = "edit"

                var text = await this.$refs.editorComponentRef.getText()

                //
                // there may be a problem here - we have to make sure that we saved
                // the correct code_id which is supposed to be the parent code id, so we
                // have to make sure that we save it every time we save code
                //
                await this.save( this.base_component_id, this.code_id, text )
            },

            chooseCode: async function() {
                var mm = this
                this.code_width = "95%"
                this.code_shown = true

                this.app_width = "0%"
                this.app_shown = false

                this.mode      = "edit"

                await mm.load_app( this.base_component_id )
            },

            chooseBoth: async function() {
                var mm = this
                this.code_width = "63%"
                this.code_shown = true

                this.app_width = "33%"
                this.app_shown = true

                this.mode      = "edit"
            },

            rename: async function(nn) {
                this.edit_name = false
                this.show_name = true

                nn = nn.replace(/[\W_]+/g,"_");
                await this.copyAppMethod( this.base_component_id , nn)
                this.new_name = ""
            },

            editAsText: async function() {
                var mm = this

                var text = await this.$refs.editorComponentRef.getText()

                var eds = saveHelper.getValueOfCodeString(text, "editors")
                if (eds) {
                    text = saveHelper.deleteCodeString(text, "editors")
                    text = saveHelper.insertCodeString(text, "editors_old",eds)
                }

                await mm.save(   this.base_component_id,   this.code_id,   text   )

                await mm.load_new_app( this.base_component_id )
            },

            embedApp: function(x) {
                var mm = this
                this.mode = "embed"
            }
            ,

            copyAppMethod: async function( appId , newAppId) {
                var mm = this
                var result = await callFunction(
                                    {
                                        driver_name: "copyApp",
                                        method_name: "copyAppshareApp"  }
                                        ,{
                                              base_component_id:    appId,
                                              new_app_id:           newAppId   })
                await mm.load_new_app( result.value.base_component_id )
                mm.$root.$emit('message', {
                                                type:               "insert_app_at",
                                                base_component_id:   result.value.base_component_id,
                                                card_index:          mm.card_index
                                            })

            }
            ,

           // ---------------------------------------------------------------
           //                           save
           //
           // This is called to save the currently edited code
           // ---------------------------------------------------------------
           save: async function( base_component_id, code_id , textIn) {

               var text =  textIn
               if (text == null) {
                    text = await this.$refs.editorComponentRef.getText()
               }

               var mm = this
               if (mm.read_only) {
                    return
               }

               var results = await callFunction(
               {
                   driver_name:     "appEditorV2SaveCode",
                   method_name:     "saveCode"
               },
                   {
                        base_component_id:      base_component_id,
                        code_id:                code_id,
                        code:                   text,
                        options:                {
                                                    sub_components: Object.keys(dev_app_component_loaded),
                                                    save_html:              true
                                                }
                   })

               await mm.load_app( mm.base_component_id )
           },

           load_new_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
               dev_app_component_loaded = new Object()
               this.editor_loaded = false
               await this.load_app(baseComponentId)
           }
           ,

           // ---------------------------------------------------------------
           //                           load_app
           //
           // This loads the latest version of the code stream marked with
           // 'baseComponentId'
           // ---------------------------------------------------------------
           load_app: async function ( baseComponentId ) {

                //
                // make sure that we reference an app
                //
                var mm = this
                if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
                }

               //
               // set up vars
               //
               mm.selected_app          = ""
               //mm.app_loaded            = false
               mm.base_component_id     = baseComponentId
               mm.app_component_name    = null

               //
               // read the code for the component that we are editing
               //
               var sql =    `select
                                id, cast(code as text)  as  code, editors
                             from
                                system_code
                             where
                                    base_component_id = '${baseComponentId}'
                                       and
                                    code_tag = 'LATEST' `

               var results = await callApp(
                   {
                        driver_name:    "systemFunctions2",
                        method_name:    "sql"
                   }
                   ,
                   {
                       sql: sql
                   })

               if (results) {
                   if (results.length > 0) {

                        //
                        // find the editor
                        //
                        var editors2 = results[0].editors
                        var newEditor = null
                        if (editors2) {
                            var edd = eval("(" + editors2 + ")")
                            newEditor = edd[0]
                        }

                        //
                        // find the code
                        //
                        var code = results[0].code
                        var codeId = results[0].id
                        if (mm.editor_loaded && (mm.code != code)) {
                            mm.code = code
                            mm.code_id = codeId
                        }

                        //
                        // load the editor
                        //
                        if ( !mm.editor_loaded ) {
                            var editorName = "editor_component"
                            if (newEditor) {
                                 editorName = newEditor
                            }

                            await loadV2( editorName, {text: code} )
                            mm.editor_loaded    = true
                            mm.editor_component = editorName
                       }

                       //
                       // set readonly
                       //
                       this.read_only = saveHelper.getValueOfCodeString(code, "read_only")
                   }

                   var results = await callApp( {code_id:    codeId },{})
                   mm.app_loaded = true
                   mm.baseComponentId = baseComponentId

                   setTimeout(async function() {
                       mm.app_component_name = baseComponentId
                       mm.$refs.editorComponentRef.setText(code)
                   },500)
               }
           }
       },

            mounted: async function () {
                var mm = this

                if (args && args.app_id){
                    this.app_id = args.app_id
                }

                //
                // make sure we load the component for this app
                //
                if (mm.app_id) {
                    component_loaded[this.app_id]           = false
                    dev_app_component_loaded[this.app_id]   = false
                    component_cache[this.app_id]            = null

                    await this.load_app(this.app_id)
                }
           }
       })
       return {name: "app_editor"}

}
<commit_msg>Don't pass app ID as an arg into the editor<commit_after>async function(args) {
/*
created_timestamp(-1)
base_component_id("app_editor_3")
is_app(true)
display_name("Editor App V3")
description("This will return the editor app V3")
logo_url("https://2.bp.blogspot.com/-6Hdixw3dFxk/WfSQOnB9lDI/AAAAAAAAFFc/84DRGgcwOpYBOgknkHQ-qmgxvFv1D-iHACLcBGAs/s1600/BracketsDarks.PNG")
load_once_from_file(true)
*/
    //
    // Hack city!!! Turn off the component cache so that we can enable hot reloading of components
    //
    isStaticHtmlPageApp = false
    //
    //
    //

    await loadV2("appEmbed")

    Vue.component("app_editor_3",
    {
      props: ['app_id', 'card_index'],
      template: `

{{app_component_name?"" + app_component_name.substring(0,30):""}}{{(app_component_name && ((app_component_name.length > 30))?"...":"")}}

                        <input  class='caption' style='display: inline-block;' v-if='edit_name' v-model='new_name'></input>
                        <button type=button class='btn btn-primary' style='margin-left: 10px' v-if='edit_name' v-on:click='(async function(){await rename(new_name)})()'>Save new name</button>

                            <button  type=button class='btn btn-primary'      v-on:click='chooseApp()'  >App</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='chooseCode()' >Code</button>
                            <button  type=button class=' btn btn-info'        v-on:click='chooseBoth()' >Both</button>
                            <button  type=button class=' btn btn-secondary'   v-on:click='copyAppMethod(base_component_id,null)' >Copy app</button>
                            <button  type=button class=' btn btn-info'        v-on:click='embedApp(base_component_id)' >Embed app</button>
                            <button  v-if='(editor_component != "editor_component") && (!read_only)' type=button class=' btn btn-secondary'   v-on:click='editAsText()' >Edit as text</button>

                        <appEmbed v-bind:base_component_id_arg='base_component_id'></appEmbed>

                          <component  v-bind:is="editor_component" v-if="editor_loaded" ref="editorComponentRef">
                                          <button v-if='!read_only'
                                                  v-bind:style="'visibility: ' + ((app_shown && code_shown)?'':'hidden')"
                                                  slot-scope="editor_component"
                                                  v-on:click='setTimeout(async function(){await save(base_component_id, code_id,null)},100)'
                                                  type="button" class="btn btn-primary btn-sm">

                                                      Save changes
                                         </button>
                          </component>

                                    {{show_new_tab_tooltip?"Open page in new browser tab (shareable :)":""}}
                                    {{show_open_app_tooltip?"Download as HTML app (emailable :)":""}}

                                ← → ↻
                                ❏

                                    <input  readonly size="40" style='font-size: 13px;'
                                        v-bind:value='"http://" + location.hostname + ":" + location.port + "/app/" + base_component_id + ".html"'></input>

                                ♨

                          <component  v-bind:is="app_component_name" v-if="app_loaded">
                            APP HERE
                          </component>

       `
       ,
       data: function() {
           return {
               editor_loaded:       false,
               selected_app:        '',
               editor_component:    null,
               app_loaded:          false,
               app_component_name:  null,
               base_component_id:   null,
               code_id:            "...",
               version: 0,
               app_width:           "33%",
               code_width:          "63%",
               app_shown:           true,
               code_shown:          true,
               read_only:           false,
               mode:                "edit",
               show_name:           true,
               edit_name:           false,
               new_name:            "",
               show_new_tab_tooltip:false,
               show_open_app_tooltip:false
           }
       }
       ,

       methods: {
            // ---------------------------------------------------------------
            //                         chooseApp
            //
            // This is called when the end user selects "app"
            // ---------------------------------------------------------------
            chooseApp: async function() {
                var mm = this
                this.code_width = "0%"
                this.code_shown = false

                this.app_width = "95%"
                this.app_shown = true

                this.mode      = "edit"

                var text = await this.$refs.editorComponentRef.getText()

                //
                // there may be a problem here - we have to make sure that we saved
                // the correct code_id which is supposed to be the parent code id, so we
                // have to make sure that we save it every time we save code
                //
                await this.save( this.base_component_id, this.code_id, text )
            },

            chooseCode: async function() {
                var mm = this
                this.code_width = "95%"
                this.code_shown = true

                this.app_width = "0%"
                this.app_shown = false

                this.mode      = "edit"

                await mm.load_app( this.base_component_id )
            },

            chooseBoth: async function() {
                var mm = this
                this.code_width = "63%"
                this.code_shown = true

                this.app_width = "33%"
                this.app_shown = true

                this.mode      = "edit"
            },

            rename: async function(nn) {
                this.edit_name = false
                this.show_name = true

                nn = nn.replace(/[\W_]+/g,"_");
                await this.copyAppMethod( this.base_component_id , nn)
                this.new_name = ""
            },

            editAsText: async function() {
                var mm = this

                var text = await this.$refs.editorComponentRef.getText()

                var eds = saveHelper.getValueOfCodeString(text, "editors")
                if (eds) {
                    text = saveHelper.deleteCodeString(text, "editors")
                    text = saveHelper.insertCodeString(text, "editors_old",eds)
                }

                await mm.save(   this.base_component_id,   this.code_id,   text   )

                await mm.load_new_app( this.base_component_id )
            },

            embedApp: function(x) {
                var mm = this
                this.mode = "embed"
            }
            ,

            copyAppMethod: async function( appId , newAppId) {
                var mm = this
                var result = await callFunction(
                                    {
                                        driver_name: "copyApp",
                                        method_name: "copyAppshareApp"  }
                                        ,{
                                              base_component_id:    appId,
                                              new_app_id:           newAppId   })
                await mm.load_new_app( result.value.base_component_id )
                mm.$root.$emit('message', {
                                                type:               "insert_app_at",
                                                base_component_id:   result.value.base_component_id,
                                                card_index:          mm.card_index
                                            })

            }
            ,

           // ---------------------------------------------------------------
           //                           save
           //
           // This is called to save the currently edited code
           // ---------------------------------------------------------------
           save: async function( base_component_id, code_id , textIn) {

               var text =  textIn
               if (text == null) {
                    text = await this.$refs.editorComponentRef.getText()
               }

               var mm = this
               if (mm.read_only) {
                    return
               }

               var results = await callFunction(
               {
                   driver_name:     "appEditorV2SaveCode",
                   method_name:     "saveCode"
               },
                   {
                        base_component_id:      base_component_id,
                        code_id:                code_id,
                        code:                   text,
                        options:                {
                                                    sub_components: Object.keys(dev_app_component_loaded),
                                                    save_html:              true
                                                }
                   })

               await mm.load_app( mm.base_component_id )
           },

           load_new_app: async function ( baseComponentId ) {
               var mm = this
               if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
               }
               dev_app_component_loaded = new Object()
               this.editor_loaded = false
               await this.load_app(baseComponentId)
           }
           ,

           // ---------------------------------------------------------------
           //                           load_app
           //
           // This loads the latest version of the code stream marked with
           // 'baseComponentId'
           // ---------------------------------------------------------------
           load_app: async function ( baseComponentId ) {

                //
                // make sure that we reference an app
                //
                var mm = this
                if ((!baseComponentId) || (baseComponentId == "") || (!mm)) {
                    return
                }

               //
               // set up vars
               //
               mm.selected_app          = ""
               //mm.app_loaded            = false
               mm.base_component_id     = baseComponentId
               mm.app_component_name    = null

               //
               // read the code for the component that we are editing
               //
               var sql =    `select
                                id, cast(code as text)  as  code, editors
                             from
                                system_code
                             where
                                    base_component_id = '${baseComponentId}'
                                       and
                                    code_tag = 'LATEST' `

               var results = await callApp(
                   {
                        driver_name:    "systemFunctions2",
                        method_name:    "sql"
                   }
                   ,
                   {
                       sql: sql
                   })

               if (results) {
                   if (results.length > 0) {

                        //
                        // find the editor
                        //
                        var editors2 = results[0].editors
                        var newEditor = null
                        if (editors2) {
                            var edd = eval("(" + editors2 + ")")
                            newEditor = edd[0]
                        }

                        //
                        // find the code
                        //
                        var code = results[0].code
                        var codeId = results[0].id
                        if (mm.editor_loaded && (mm.code != code)) {
                            mm.code = code
                            mm.code_id = codeId
                        }

                        //
                        // load the editor
                        //
                        if ( !mm.editor_loaded ) {
                            var editorName = "editor_component"
                            if (newEditor) {
                                 editorName = newEditor
                            }

                            await loadV2( editorName, {text: code} )
                            mm.editor_loaded    = true
                            mm.editor_component = editorName
                       }

                       //
                       // set readonly
                       //
                       this.read_only = saveHelper.getValueOfCodeString(code, "read_only")
                   }

                   var results = await callApp( {code_id:    codeId },{})
                   mm.app_loaded = true
                   mm.baseComponentId = baseComponentId

                   setTimeout(async function() {
                       mm.app_component_name = baseComponentId
                       mm.$refs.editorComponentRef.setText(code)
                   },500)
               }
           }
       },

            mounted: async function () {
                var mm = this

                //
                // make sure we load the component for this app
                //
                if (mm.app_id) {
                    component_loaded[this.app_id]           = false
                    dev_app_component_loaded[this.app_id]   = false
                    component_cache[this.app_id]            = null

                    await this.load_app(this.app_id)

                }
           }
       })
       return {name: "app_editor"}

}
<|endoftext|>


<commit_before>const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
<commit_msg>Improve Array.prototype.reduce intro example (#1996)<commit_after>const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10
<|endoftext|>


<commit_before>/**
 * JS implementation of an undirected Graph.
 * TODOs: 1. Add weights for the edges.
 *		  2. Add support for loops.
 */
function Graph(vertex) {
	var graph = {};
	_this = this;
	_this.graph = graph;
	_this.graph[vertex] = {};
	_this.getGraph = getGraph;
	_this.addVertex = addVertex;
	_this.numberOfVertices = numberOfVertices;
	_this.numberOfEdges = numberOfEdges;
	_this.addEdge = addEdge;
	_this.adjacentVertices = adjacentVertices;
	_this.getDegree = getDegree;
	_this.maxDegree = maxDegree;
	_this.averageDegree = averageDegree;
	_this.removeEdge = removeEdge;

	/* Returns current graph */
	function getGraph() {
		return _this.graph;
	}

	/* Add a vertex to graph */
	function addVertex(vertex, connectedVerticesArr) {
		_this.graph[vertex] = {};
		if(connectedVerticesArr) {
			connectedVerticesArr.forEach(function(newVertex) {
				if(!_this.graph[newVertex]) {
					_this.graph[newVertex] = {};
				}
				_this.graph[newVertex][vertex] = '';
				_this.graph[vertex][newVertex] = '';
			});
		}
	}

	/* Returns the number of vertices in the graph */
	function numberOfVertices() {
		return Object.keys(_this.graph).length;
	}

	/* Returns the number of edges in the graph */
	function numberOfEdges() {
		var keys = Object.keys(_this.graph);
		var edges = 0;
		keys.forEach(function(key) {
			edges += Object.keys(_this.graph[key]).length;
		});

		return edges/2;
	}

	/* Adds an edge in the graph */
	function addEdge(fromVertex, toVertex) {
		if(!_this.graph[fromVertex] || !_this.graph[toVertex]) {
			console.log('One of the vertices, ' + fromVertex + ' or ' + toVertex + ' does not exist in graph. Please add that vertex first using addVertex method.');
		}
		else {
			_this.graph[fromVertex][toVertex] = '';
			_this.graph[toVertex][fromVertex] = '';
		}
	}

	/* Removes an edge from the graph */
	function removeEdge(fromVertex, toVertex) {
		if(!_this.graph[fromVertex] || !_this.graph[toVertex]) {
			console.log('One of the vertices, ' + fromVertex + ' or ' + toVertex + ' does not exist in graph. Please add that vertex first using addVertex method.');
		}
		else {
			delete _this.graph[fromVertex][toVertex];
			delete _this.graph[toVertex][fromVertex];
		}
	}

	/* Returns an array of edges adjacent to a vertex */
	function adjacentVertices(vertex) {
		return Object.keys(_this.graph[vertex]);
	}

	/* Returns degree of a vertex */
	function getDegree(vertex) {
		return Object.keys(_this.adjacentVertices(vertex)).length;
	}

	/* Returns maximum degree of a graph */
	function maxDegree() {
		var maxDeg = 0;
		var vertices = Object.keys(_this.graph);
		vertices.forEach(function(vertex) {
			var degOfVertex = _this.getDegree(vertex);
			if(degOfVertex > maxDeg) {
				maxDeg = degOfVertex;
			}
		});

		return maxDeg;
	}

	/* Returns average degree of the graph */
	function averageDegree() {
		return _this.numberOfEdges() / _this.numberOfVertices();
	}
}
<commit_msg>Update Graph.js<commit_after>/**
 * JS implementation of an undirected Graph.
 * TODOs: 1. Add weights for the edges.
 *	  2. Add support for loops.
 */
function Graph(vertex) {
	var graph = {};
	_this = this;
	_this.graph = graph;
	_this.graph[vertex] = {};
	_this.getGraph = getGraph;
	_this.addVertex = addVertex;
	_this.numberOfVertices = numberOfVertices;
	_this.numberOfEdges = numberOfEdges;
	_this.addEdge = addEdge;
	_this.adjacentVertices = adjacentVertices;
	_this.getDegree = getDegree;
	_this.maxDegree = maxDegree;
	_this.averageDegree = averageDegree;
	_this.removeEdge = removeEdge;
	_this.isEdge = isEdge;
	_this.depthFirstSearch = depthFirstSearch;

	/* Returns current graph */
	function getGraph() {
		return _this.graph;
	}

	/* Add a vertex to graph */
	function addVertex(vertex, connectedVerticesArr) {
		_this.graph[vertex] = {};
		if(connectedVerticesArr) {
			connectedVerticesArr.forEach(function(newVertex) {
				if(!_this.graph[newVertex]) {
					_this.graph[newVertex] = {};
				}
				_this.graph[newVertex][vertex] = '';
				_this.graph[vertex][newVertex] = '';
			});
		}
	}

	/* Returns the number of vertices in the graph */
	function numberOfVertices() {
		return Object.keys(_this.graph).length;
	}

	/* Returns the number of edges in the graph */
	function numberOfEdges() {
		var keys = Object.keys(_this.graph);
		var edges = 0;
		keys.forEach(function(key) {
			edges += Object.keys(_this.graph[key]).length;
		});

		return edges/2;
	}

	/* Adds an edge in the graph */
	function addEdge(fromVertex, toVertex) {
		if(!_this.graph[fromVertex] || !_this.graph[toVertex]) {
			console.log('One of the vertices, ' + fromVertex + ' or ' + toVertex + ' does not exist in graph. Please add that vertex first using addVertex method.');
		}
		else {
			_this.graph[fromVertex][toVertex] = '';
			_this.graph[toVertex][fromVertex] = '';
		}
	}

	/* Removes an edge from the graph */
	function removeEdge(fromVertex, toVertex) {
		if(!_this.graph[fromVertex] || !_this.graph[toVertex]) {
			console.log('One of the vertices, ' + fromVertex + ' or ' + toVertex + ' does not exist in graph. Please add that vertex first using addVertex method.');
		}
		else {
			delete _this.graph[fromVertex][toVertex];
			delete _this.graph[toVertex][fromVertex];
		}
	}

	/* Returns an array of edges adjacent to a vertex */
	function adjacentVertices(vertex) {
		return Object.keys(_this.graph[vertex]);
	}

	/* Returns degree of a vertex */
	function getDegree(vertex) {
		return Object.keys(_this.adjacentVertices(vertex)).length;
	}

	/* Returns maximum degree of a graph */
	function maxDegree() {
		var maxDeg = 0;
		var vertices = Object.keys(_this.graph);
		vertices.forEach(function(vertex) {
			var degOfVertex = _this.getDegree(vertex);
			if(degOfVertex > maxDeg) {
				maxDeg = degOfVertex;
			}
		});

		return maxDeg;
	}

	/* Returns average degree of the graph */
	function averageDegree() {
		return _this.numberOfEdges() / _this.numberOfVertices();
	}

	/* Function to check if there is an edge between 2 vertices */
	function isEdge(fromVertex, toVertex) {
		var isPresent = false;
		var adjacent = _this.adjacentVertices(fromVertex);
		Object.keys(adjacent).forEach(function(vertex) {
			if(Number(adjacent[vertex]) === toVertex) {
				isPresent = true;
			}
		});

		return isPresent;
	}

	/* Implementation of depth first search. Returns the order in which elements are traversed */
	function depthFirstSearch(vertex) {
		var _isVisited = {};
		var order = [];
		return _dfs(vertex, _isVisited, order);
	}

	function _dfs(vertex, _isVisited, order) {
		_isVisited[vertex] = true;
		order.push(vertex);
		var adjacentNodes = _this.adjacentVertices(vertex);
		Object.keys(adjacentNodes).forEach(function(adjVertex) {
			if(!_isVisited[adjacentNodes[adjVertex]] === true) {
				_dfs(adjacentNodes[adjVertex], _isVisited, order);
			}
		});
		return order;
	}
}
<|endoftext|>


<commit_before>/*jslint browser: true, unparam: true, nomen: true */

(function (tangelo, $, d3) {
    "use strict";

    if (!($ && $.widget && d3)) {
        $.fn.dendrogram = tangelo.unavailable({
            plugin: "dendrogram",
            required: ["JQuery", "JQuery UI", "d3"]
        });
        return;
    }

    $.widget("tangelo.dendrogram", {
        options: {
            label: null,
            distance: null,
            id: null,
            margin: {
                top: 20,
                right: 120,
                bottom: 20,
                left: 120
            },
            nodeLimit: null,
            duration: 750,
            root: null,
            data: null,
            mode: "hide",
            nodesize: 7.5,
            textsize: 10,
            orientation: "horizontal",
            initialize: null
        },

        _missing: {
            label: "",
            distance: 1,
            id: 0
        },

        orientation: {
            abscissa: "y",
            ordinate: "x",
            heightvar: "height",
            widthvar: "width",
            xfunc: function (_, v) {
                return v;
            }
        },

        _create: function () {
            var options,
                that = this;

            if (this.options.orientation === "vertical") {
                this.orientation = {
                    abscissa: "x",
                    ordinate: "y",
                    heightvar: "width",
                    widthvar: "height",
                    xfunc: function (that, v) {
                        return that.width - v;
                    }
                };
            } else if (this.options.orientation !== "horizontal") {
                throw "illegal option for 'orientation': " + this.options.orientation;
            }

            this.tree = d3.layout.partition()
                .value(function () { return 1; })
                .sort(d3.ascending);

            this.line = d3.svg.line()
                .interpolate("step-before")
                .x(function (d) {
                    return this.orientation.xfunc(that, d[that.orientation.abscissa]);
                })
                .y(function (d) {
                    return d[that.orientation.ordinate];
                });

            this.svg = d3.select(this.element.get(0))
                .append("svg")
                .append("g");

            options = $.extend(true, {}, this.options);
            delete options.disabled;
            delete options.create;
            this._setOptions(options);
        },

        _setOption: function (key, value) {
            if (key === "label" || key === "distance" || key === "id") {
                this._super(key, tangelo.accessor(value, this._missing[key]));
            } else {
                this._super(key, value);
            }
        },

        _setOptions: function (options) {
            var that = this;

            $.each(options, function (key, value) {
                that._setOption(key, value);
            });

            this._update();
        },

        _update: function () {
            this.width = 1200 - this.options.margin.right - this.options.margin.left;
            this.height = 800 - this.options.margin.top - this.options.margin.bottom;

            if (!this.options.root) {
                this.options.root = this.options.data;
            }

            if (!this.options.mode) {
                this.options.mode = "hide";
            }

            this.tree.size([this.height, this.width]);

            d3.select(this.element.get(0))
                .select("svg")
                .attr("width", this.width + this.options.margin.right + this.options.margin.left)
                .attr("height", this.height + this.options.margin.top + this.options.margin.bottom)
                .select("g")
                .attr("transform", "translate(" + this.options.margin.left + "," + this.options.margin.top + ")");

            //this.options.root.x0 = this.height / 2;
            this.options.root.x0 = this[this.orientation.heightvar] / 2;
            this.options.root.y0 = 0;

            // Compute the new tree layout.
            var nodes = this.tree.nodes(this.options.root).reverse(),
                links = this.tree.links(nodes),
                source = this.options.source || this.options.root,
                node,
                nodeEnter,
                nodeUpdate,
                nodeExit,
                link,
                maxY,
                visibleLeaves,
                filteredNodes,
                filteredLinks,
                that = this;

            visibleLeaves = 0;
            function setPosition(node, pos) {
                var xSum = 0;
                node.y = pos;
                node.x = node.x + node.dx / 2;
                if (!node.parent) {
                    node.parent = node;
                }
                if (node.children) {
                    node.children.forEach(function (d) {
                        d.parent = node;
                        setPosition(d, pos + 10 * that.options.distance(d));
                        xSum += d.x;
                    });
                    node.x = xSum / node.children.length;
                } else {
                    visibleLeaves += 1;
                }
            }
            setPosition(this.options.root, 0);

            // Normalize Y to fill space
            maxY = d3.extent(nodes, function (d) {
                return d.y;
            })[1];
            nodes.forEach(function (d) {
                d.y = d.y / maxY * (that.width - 150);
            });

            if (this.options.nodeLimit && nodes.length > this.options.nodeLimit) {
                // Filter out everything beyond parent y-position to keep things interactive
                nodes.sort(function (a, b) {
                    return d3.ascending(a.parent.y, b.parent.y);
                });
                nodes.forEach(function (d, i) {
                    d.index = i;
                });
                filteredNodes = nodes.slice(0, this.options.nodeLimit);
                maxY = filteredNodes[filteredNodes.length - 1].parent.y;
                filteredNodes.forEach(function (d) {
                    d.y = d.y > maxY ? maxY : d.y;
                });

                // Filter the links based on visible nodes
                filteredLinks = [];
                links.forEach(function (d) {
                    if (d.source.index < this.options.nodeLimit && d.target.index < this.options.nodeLimit) {
                        filteredLinks.push(d);
                    }
                });
                nodes = filteredNodes;
                links = filteredLinks;
            }

            // Toggle children on click.
            function click(d) {
                if (that.options.mode === "hide") {
                    if (d.children) {
                        d._children = d.children;
                        d.children = null;
                    } else {
                        d.children = d._children;
                        d._children = null;
                    }
                } else if (that.options.mode === "focus") {
                    that.options.root = d;
                } else if (that.options.mode === "label") {
                    d.showLabel = d.showLabel ? false : true;
                }
                //that._update({source: d});
                that._setOptions({source: d});
            }

            function firstChild(d) {
                if (d.children) {
                    return firstChild(d.children[0]);
                }
                if (d._children) {
                    return firstChild(d._children[0]);
                }
                return d;
            }

            function lastChild(d) {
                if (d.children) {
                    return lastChild(d.children[d.children.length - 1]);
                }
                if (d._children) {
                    return lastChild(d._children[d._children.length - 1]);
                }
                return d;
            }

            function leafCount(d) {
                var children = d.children,
                    sum = 0;
                if (!children) {
                    children = d._children;
                }

                // I am an internal node, so total the leaves of the children
                if (children) {
                    children.forEach(function (child) {
                        sum += leafCount(child);
                    });
                    return sum;
                }

                // I am a leaf
                return 1;
            }

            // Update the nodes…
            node = this.svg.selectAll("g.node")
                .data(nodes, function (d) {
                    return that.options.id(d);
                });

            // Enter any new nodes at the parent's previous position.
            nodeEnter = node.enter()
                .append("g")
                .classed("node", true)
                .attr("transform", function () {
                    return "translate(" + source.y0 + "," + source.x0 + ")";
                })
                .on("click", click);

            nodeEnter.append("circle")
                .attr("r", 1e-6)
                .style("stroke", "none")
                .style("opacity", function (d) {
                    return d._children ? 1 : 0;
                })
                .style("fill", function (d) {
                    return d._children ? "lightsteelblue" : "#fff";
                })
                .on("mouseenter", function () {
                    var me = d3.select(this);
                    this.saved_opacity = me.style("opacity");
                    this.saved_fill = me.style("fill");
                    me.style("opacity", 1)
                        .style("fill", "black");
                })
                .on("mouseleave", function () {
                    if (this.saved_opacity) {
                        d3.select(this)
                            .style("opacity", this.saved_opacity);
                        this.saved_opacity = undefined;
                    }
                    if (this.saved_fill) {
                        d3.select(this)
                            .style("fill", this.saved_fill);
                        this.saved_fill = undefined;
                    }
                });

            nodeEnter.append("text")
                .attr("x", 10)
                .attr("dy", ".35em")
                .attr("text-anchor", "start")
                .style("font-size", this.options.textsize + "px")
                .text(this.options.label)
                .style("fill-opacity", 1e-6);

            // Transition nodes to their new position.
            nodeUpdate = node.transition()
                .duration(this.options.duration)
                .attr("transform", function (d) {
                    return "translate(" + that.orientation.xfunc(that, d[that.orientation.abscissa]) + "," + d[that.orientation.ordinate] + ")";
                });

            nodeUpdate.select("circle")
                .attr("r", this.options.nodesize)
                .style("opacity", function (d) {
                    return d._children ? 1 : 0;
                })
                .style("fill", function (d) {
                    return d._children ? "lightsteelblue" : "#fff";
                });

            nodeUpdate.select("text")
                .text(function (d) {
                    var label = that.options.label(d);
                    if (d._children || (d.children && d.showLabel)) {
                        if (label === "") {
                            label = that.options.label(firstChild(d)) + " ... " + that.options.label(lastChild(d));
                        }
                        return label + " (" + leafCount(d) + ")";
                    }
                    if (visibleLeaves < that.height / (0.8 * that.options.textsize)) {
                        return label;
                    }
                    return "";
                })
                .style("fill-opacity", 1);

            // Transition exiting nodes to the parent's new position.
            nodeExit = node
                .exit()
                .transition()
                .duration(this.options.duration)
                .attr("transform", function () {
                    return "translate(" + source.y + "," + source.x + ")";
                })
                .remove();

            nodeExit.select("circle")
                .attr("r", 1e-6);

            nodeExit.select("text")
                .style("fill-opacity", 1e-6);

            // Update the links…
            link = this.svg.selectAll("path.link")
                .data(links, function (d) {
                    return that.options.id(d.target);
                });

            // Enter any new links at the parent's previous position.
            link.enter()
                .insert("path", "g")
                .classed("link", true)
                .style("stroke", "black")
                .style("stroke-width", "1px")
                .style("fill", "none")
                .attr("d", function () {
                    var o = {x: source.x0, y: source.y0};
                    //return diagonal({source: o, target: o});
                    return that.line([o, o]);
                });

            // Transition links to their new position.
            link.transition()
                .duration(this.options.duration)
                .attr("d", function (d) {
                    return that.line([d.source, d.target]);
                });

            // Transition exiting nodes to the parent's new position.
            link.exit()
                .transition()
                .duration(this.options.duration)
                .attr("d", function () {
                    var o = {x: source.x, y: source.y};
                    return that.line([o, o]);
                })
                .remove();

            // Stash the old positions for transition.
            nodes.forEach(function (d) {
                d.x0 = d.x;
                d.y0 = d.y;
            });

            if (this.options.initialize) {
                this.options.initialize(nodeEnter, node, nodeExit);
            }
        },

        download: function (format) {
            var node,
                s,
                d,
                str;

            if (format === "pdf") {
                node = this.svg
                    .selectAll("g.node")
                    .select("circle")
                    .attr("r", function (d) {
                        return d._children ? this.options.nodesize : 0;
                    });
                s = new window.XMLSerializer();
                d = d3.select("svg").node();
                str = s.serializeToString(d);

                // Change back to normal
                node.attr("r", this.options.nodesize);

                d3.json("/service/svg2pdf")
                    .send("POST", str, function (error, data) {
                        window.location = "/service/svg2pdf?id=" + data.result;
                    });
            } else {
                window.alert("Unsupported export format type: " + format);
            }
        },

        reset: function () {
            function unhideAll(d) {
                if (!d.children) {
                    d.children = d._children;
                    d._children = null;
                }
                if (d.children) {
                    d.children.forEach(unhideAll);
                }
            }
            unhideAll(this.options.data);
            this._setOptions({
                root: this.options.data
            });
        }
    });
}(window.tangelo, window.jQuery, window.d3));
<commit_msg>Replaced click with dblclick in tree expand/collapse.<commit_after>/*jslint browser: true, unparam: true, nomen: true */

(function (tangelo, $, d3) {
    "use strict";

    if (!($ && $.widget && d3)) {
        $.fn.dendrogram = tangelo.unavailable({
            plugin: "dendrogram",
            required: ["JQuery", "JQuery UI", "d3"]
        });
        return;
    }

    $.widget("tangelo.dendrogram", {
        options: {
            label: null,
            distance: null,
            id: null,
            margin: {
                top: 20,
                right: 120,
                bottom: 20,
                left: 120
            },
            nodeLimit: null,
            duration: 750,
            root: null,
            data: null,
            mode: "hide",
            nodesize: 7.5,
            textsize: 10,
            orientation: "horizontal",
            initialize: null
        },

        _missing: {
            label: "",
            distance: 1,
            id: 0
        },

        orientation: {
            abscissa: "y",
            ordinate: "x",
            heightvar: "height",
            widthvar: "width",
            xfunc: function (_, v) {
                return v;
            }
        },

        _create: function () {
            var options,
                that = this;

            if (this.options.orientation === "vertical") {
                this.orientation = {
                    abscissa: "x",
                    ordinate: "y",
                    heightvar: "width",
                    widthvar: "height",
                    xfunc: function (that, v) {
                        return that.width - v;
                    }
                };
            } else if (this.options.orientation !== "horizontal") {
                throw "illegal option for 'orientation': " + this.options.orientation;
            }

            this.tree = d3.layout.partition()
                .value(function () { return 1; })
                .sort(d3.ascending);

            this.line = d3.svg.line()
                .interpolate("step-before")
                .x(function (d) {
                    return this.orientation.xfunc(that, d[that.orientation.abscissa]);
                })
                .y(function (d) {
                    return d[that.orientation.ordinate];
                });

            this.svg = d3.select(this.element.get(0))
                .append("svg")
                .append("g");

            options = $.extend(true, {}, this.options);
            delete options.disabled;
            delete options.create;
            this._setOptions(options);
        },

        _setOption: function (key, value) {
            if (key === "label" || key === "distance" || key === "id") {
                this._super(key, tangelo.accessor(value, this._missing[key]));
            } else {
                this._super(key, value);
            }
        },

        _setOptions: function (options) {
            var that = this;

            $.each(options, function (key, value) {
                that._setOption(key, value);
            });

            this._update();
        },

        _update: function () {
            this.width = 1200 - this.options.margin.right - this.options.margin.left;
            this.height = 800 - this.options.margin.top - this.options.margin.bottom;

            if (!this.options.root) {
                this.options.root = this.options.data;
            }

            if (!this.options.mode) {
                this.options.mode = "hide";
            }

            this.tree.size([this.height, this.width]);

            d3.select(this.element.get(0))
                .select("svg")
                .attr("width", this.width + this.options.margin.right + this.options.margin.left)
                .attr("height", this.height + this.options.margin.top + this.options.margin.bottom)
                .select("g")
                .attr("transform", "translate(" + this.options.margin.left + "," + this.options.margin.top + ")");

            //this.options.root.x0 = this.height / 2;
            this.options.root.x0 = this[this.orientation.heightvar] / 2;
            this.options.root.y0 = 0;

            // Compute the new tree layout.
            var nodes = this.tree.nodes(this.options.root).reverse(),
                links = this.tree.links(nodes),
                source = this.options.source || this.options.root,
                node,
                nodeEnter,
                nodeUpdate,
                nodeExit,
                link,
                maxY,
                visibleLeaves,
                filteredNodes,
                filteredLinks,
                that = this;

            visibleLeaves = 0;
            function setPosition(node, pos) {
                var xSum = 0;
                node.y = pos;
                node.x = node.x + node.dx / 2;
                if (!node.parent) {
                    node.parent = node;
                }
                if (node.children) {
                    node.children.forEach(function (d) {
                        d.parent = node;
                        setPosition(d, pos + 10 * that.options.distance(d));
                        xSum += d.x;
                    });
                    node.x = xSum / node.children.length;
                } else {
                    visibleLeaves += 1;
                }
            }
            setPosition(this.options.root, 0);

            // Normalize Y to fill space
            maxY = d3.extent(nodes, function (d) {
                return d.y;
            })[1];
            nodes.forEach(function (d) {
                d.y = d.y / maxY * (that.width - 150);
            });

            if (this.options.nodeLimit && nodes.length > this.options.nodeLimit) {
                // Filter out everything beyond parent y-position to keep things interactive
                nodes.sort(function (a, b) {
                    return d3.ascending(a.parent.y, b.parent.y);
                });
                nodes.forEach(function (d, i) {
                    d.index = i;
                });
                filteredNodes = nodes.slice(0, this.options.nodeLimit);
                maxY = filteredNodes[filteredNodes.length - 1].parent.y;
                filteredNodes.forEach(function (d) {
                    d.y = d.y > maxY ? maxY : d.y;
                });

                // Filter the links based on visible nodes
                filteredLinks = [];
                links.forEach(function (d) {
                    if (d.source.index < this.options.nodeLimit && d.target.index < this.options.nodeLimit) {
                        filteredLinks.push(d);
                    }
                });
                nodes = filteredNodes;
                links = filteredLinks;
            }

            // Toggle children on click.
            function click(d) {
                if (that.options.mode === "hide") {
                    if (d.children) {
                        d._children = d.children;
                        d.children = null;
                    } else {
                        d.children = d._children;
                        d._children = null;
                    }
                } else if (that.options.mode === "focus") {
                    that.options.root = d;
                } else if (that.options.mode === "label") {
                    d.showLabel = d.showLabel ? false : true;
                }
                //that._update({source: d});
                that._setOptions({source: d});
            }

            function firstChild(d) {
                if (d.children) {
                    return firstChild(d.children[0]);
                }
                if (d._children) {
                    return firstChild(d._children[0]);
                }
                return d;
            }

            function lastChild(d) {
                if (d.children) {
                    return lastChild(d.children[d.children.length - 1]);
                }
                if (d._children) {
                    return lastChild(d._children[d._children.length - 1]);
                }
                return d;
            }

            function leafCount(d) {
                var children = d.children,
                    sum = 0;
                if (!children) {
                    children = d._children;
                }

                // I am an internal node, so total the leaves of the children
                if (children) {
                    children.forEach(function (child) {
                        sum += leafCount(child);
                    });
                    return sum;
                }

                // I am a leaf
                return 1;
            }

            // Update the nodes…
            node = this.svg.selectAll("g.node")
                .data(nodes, function (d) {
                    return that.options.id(d);
                });

            // Enter any new nodes at the parent's previous position.
            nodeEnter = node.enter()
                .append("g")
                .classed("node", true)
                .attr("transform", function () {
                    return "translate(" + source.y0 + "," + source.x0 + ")";
                })
                .on("dblclick", click);

            nodeEnter.append("circle")
                .attr("r", 1e-6)
                .style("stroke", "none")
                .style("opacity", function (d) {
                    return d._children ? 1 : 0;
                })
                .style("fill", function (d) {
                    return d._children ? "lightsteelblue" : "#fff";
                })
                .on("mouseenter", function () {
                    var me = d3.select(this);
                    this.saved_opacity = me.style("opacity");
                    this.saved_fill = me.style("fill");
                    me.style("opacity", 1)
                        .style("fill", "black");
                })
                .on("mouseleave", function () {
                    if (this.saved_opacity) {
                        d3.select(this)
                            .style("opacity", this.saved_opacity);
                        this.saved_opacity = undefined;
                    }
                    if (this.saved_fill) {
                        d3.select(this)
                            .style("fill", this.saved_fill);
                        this.saved_fill = undefined;
                    }
                });

            nodeEnter.append("text")
                .attr("x", 10)
                .attr("dy", ".35em")
                .attr("text-anchor", "start")
                .style("font-size", this.options.textsize + "px")
                .text(this.options.label)
                .style("fill-opacity", 1e-6);

            // Transition nodes to their new position.
            nodeUpdate = node.transition()
                .duration(this.options.duration)
                .attr("transform", function (d) {
                    return "translate(" + that.orientation.xfunc(that, d[that.orientation.abscissa]) + "," + d[that.orientation.ordinate] + ")";
                });

            nodeUpdate.select("circle")
                .attr("r", this.options.nodesize)
                .style("opacity", function (d) {
                    return d._children ? 1 : 0;
                })
                .style("fill", function (d) {
                    return d._children ? "lightsteelblue" : "#fff";
                });

            nodeUpdate.select("text")
                .text(function (d) {
                    var label = that.options.label(d);
                    if (d._children || (d.children && d.showLabel)) {
                        if (label === "") {
                            label = that.options.label(firstChild(d)) + " ... " + that.options.label(lastChild(d));
                        }
                        return label + " (" + leafCount(d) + ")";
                    }
                    if (visibleLeaves < that.height / (0.8 * that.options.textsize)) {
                        return label;
                    }
                    return "";
                })
                .style("fill-opacity", 1);

            // Transition exiting nodes to the parent's new position.
            nodeExit = node
                .exit()
                .transition()
                .duration(this.options.duration)
                .attr("transform", function () {
                    return "translate(" + source.y + "," + source.x + ")";
                })
                .remove();

            nodeExit.select("circle")
                .attr("r", 1e-6);

            nodeExit.select("text")
                .style("fill-opacity", 1e-6);

            // Update the links…
            link = this.svg.selectAll("path.link")
                .data(links, function (d) {
                    return that.options.id(d.target);
                });

            // Enter any new links at the parent's previous position.
            link.enter()
                .insert("path", "g")
                .classed("link", true)
                .style("stroke", "black")
                .style("stroke-width", "1px")
                .style("fill", "none")
                .attr("d", function () {
                    var o = {x: source.x0, y: source.y0};
                    //return diagonal({source: o, target: o});
                    return that.line([o, o]);
                });

            // Transition links to their new position.
            link.transition()
                .duration(this.options.duration)
                .attr("d", function (d) {
                    return that.line([d.source, d.target]);
                });

            // Transition exiting nodes to the parent's new position.
            link.exit()
                .transition()
                .duration(this.options.duration)
                .attr("d", function () {
                    var o = {x: source.x, y: source.y};
                    return that.line([o, o]);
                })
                .remove();

            // Stash the old positions for transition.
            nodes.forEach(function (d) {
                d.x0 = d.x;
                d.y0 = d.y;
            });

            if (this.options.initialize) {
                this.options.initialize(nodeEnter, node, nodeExit);
            }
        },

        download: function (format) {
            var node,
                s,
                d,
                str;

            if (format === "pdf") {
                node = this.svg
                    .selectAll("g.node")
                    .select("circle")
                    .attr("r", function (d) {
                        return d._children ? this.options.nodesize : 0;
                    });
                s = new window.XMLSerializer();
                d = d3.select("svg").node();
                str = s.serializeToString(d);

                // Change back to normal
                node.attr("r", this.options.nodesize);

                d3.json("/service/svg2pdf")
                    .send("POST", str, function (error, data) {
                        window.location = "/service/svg2pdf?id=" + data.result;
                    });
            } else {
                window.alert("Unsupported export format type: " + format);
            }
        },

        reset: function () {
            function unhideAll(d) {
                if (!d.children) {
                    d.children = d._children;
                    d._children = null;
                }
                if (d.children) {
                    d.children.forEach(unhideAll);
                }
            }
            unhideAll(this.options.data);
            this._setOptions({
                root: this.options.data
            });
        }
    });
}(window.tangelo, window.jQuery, window.d3));
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 Robert Fotino.
 *
 * A modules that defines a weapon powerup that the user can pick up.
 */

var $ = require('../../lib/jquery/jquery.js');
var physics = require('../physics.js');
var LaserWeapon = require('./LaserWeapon.js');
var Powerup = require('./Powerup.js');

/**
 * A constructor for weapon powerup objects.
 */
var WeaponPowerup = function(props) {
    props = props || {};
    props.type = 'ammo';
    Powerup.prototype.constructor.call(this, props);
    this.weapon = props.weapon || new LaserWeapon();
    this.radius = props.radius || 20;
    // Get a bullet to draw without losing any ammo in this.weapon. A bit of
    // a hack, should probably be replaced at some point to improve portability
    // between weapon types
    var ammo = this.weapon.ammo;
    var cooldownTimer = this.weapon.cooldownTimer;
    this._bullet = this.weapon.getBullet({ x: 1, y: 2 }, this);
    this.weapon.cooldownTimer = cooldownTimer;
    this.weapon.ammo = ammo;

};

// Extend Powerup
WeaponPowerup.prototype = Object.create(Powerup.prototype);
WeaponPowerup.prototype.constructor = WeaponPowerup;

/**
 * @override {Powerup}
 * @param {Player} player
 */
WeaponPowerup.prototype.applyTo = function(player) {
    for (var i = 0; i < player.weapons.length; i++) {
        var playerWeapon = player.weapons[i];
        if (playerWeapon.name === this.weapon.name) {
            if (null !== playerWeapon.ammo) {
                playerWeapon.ammo += this.weapon.ammo;
            }
            return;
        }
    }
    player.weapons.push(this.weapon);
};

/**
 * @override {Powerup}
 * @return {Object}
 */
WeaponPowerup.prototype.getObj = function() {
    var obj = Powerup.prototype.getObj.call(this);
    return $.extend(obj, {
        weapon: this.weapon
    });
};

/**
 * @override {GameObject}
 * @param {CanvasRenderingContext2D} ctx
 */
WeaponPowerup.prototype.draw = function(ctx) {
    ctx.save();
    ctx.fillStyle = '#666';
    ctx.strokeStyle = '#aaa';
    ctx.lineWidth = this.radius / 15;
    ctx.beginPath();
    ctx.arc(0, 0, this.radius - (ctx.lineWidth / 2), 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    // Get the scale at which to draw the bullet
    var bulletBounds = this._bullet.bounds();
    var bulletDiameter = physics.dist(bulletBounds,
                                      physics.sum(bulletBounds,
                                                  { x: bulletBounds.width,
                                                    y: bulletBounds.height }));
    var padding = this.radius / 5;
    var scale = ((this.radius - ctx.lineWidth - padding) * 2) / bulletDiameter;
    ctx.scale(scale, scale);
    ctx.rotate(this._bullet.pos.angular);
    this._bullet.draw(ctx);
    ctx.restore();
};

module.exports = WeaponPowerup;
<commit_msg>Fixes information leak in WeaponPowerup.<commit_after>/**
 * Copyright (c) 2016 Robert Fotino.
 *
 * A modules that defines a weapon powerup that the user can pick up.
 */

var $ = require('../../lib/jquery/jquery.js');
var physics = require('../physics.js');
var LaserWeapon = require('./LaserWeapon.js');
var Powerup = require('./Powerup.js');

/**
 * A constructor for weapon powerup objects.
 */
var WeaponPowerup = function(props) {
    props = props || {};
    props.type = 'ammo';
    Powerup.prototype.constructor.call(this, props);
    this.weapon = props.weapon || new LaserWeapon();
    this.radius = props.radius || 20;
    // Get a bullet to draw without losing any ammo in this.weapon. A bit of
    // a hack, should probably be replaced at some point to improve portability
    // between weapon types
    var ammo = this.weapon.ammo;
    var cooldownTimer = this.weapon.cooldownTimer;
    this._bullet = this.weapon.getBullet({ x: 1, y: 2 }, this);
    this.weapon.cooldownTimer = cooldownTimer;
    this.weapon.ammo = ammo;

};

// Extend Powerup
WeaponPowerup.prototype = Object.create(Powerup.prototype);
WeaponPowerup.prototype.constructor = WeaponPowerup;

/**
 * @override {Powerup}
 * @param {Player} player
 */
WeaponPowerup.prototype.applyTo = function(player) {
    for (var i = 0; i < player.weapons.length; i++) {
        var playerWeapon = player.weapons[i];
        if (playerWeapon.name === this.weapon.name) {
            if (null !== playerWeapon.ammo) {
                playerWeapon.ammo += this.weapon.ammo;
            }
            return;
        }
    }
    player.weapons.push(this.weapon);
};

/**
 * @override {Powerup}
 * @return {Object}
 */
WeaponPowerup.prototype.getObj = function() {
    var obj = Powerup.prototype.getObj.call(this);
    return $.extend(obj, {
        weapon: this.weapon.getObj()
    });
};

/**
 * @override {GameObject}
 * @param {CanvasRenderingContext2D} ctx
 */
WeaponPowerup.prototype.draw = function(ctx) {
    ctx.save();
    ctx.fillStyle = '#666';
    ctx.strokeStyle = '#aaa';
    ctx.lineWidth = this.radius / 15;
    ctx.beginPath();
    ctx.arc(0, 0, this.radius - (ctx.lineWidth / 2), 0, Math.PI * 2);
    ctx.fill();
    ctx.stroke();
    // Get the scale at which to draw the bullet
    var bulletBounds = this._bullet.bounds();
    var bulletDiameter = physics.dist(bulletBounds,
                                      physics.sum(bulletBounds,
                                                  { x: bulletBounds.width,
                                                    y: bulletBounds.height }));
    var padding = this.radius / 5;
    var scale = ((this.radius - ctx.lineWidth - padding) * 2) / bulletDiameter;
    ctx.scale(scale, scale);
    ctx.rotate(this._bullet.pos.angular);
    this._bullet.draw(ctx);
    ctx.restore();
};

module.exports = WeaponPowerup;
<|endoftext|>


<commit_before>'use strict';
let express = require('express');
let touristSitesController = require('./../../controllers/tourist-sites-controller');
let identity = require('./../../common/identity');

module.exports = function(app) {
  let router = express.Router();

  router
    .post('/', touristSitesController.addTouristSite);

  app.use('/api/tourist-sites', router);
};
<commit_msg>Added authentication check for adding new tourist site.<commit_after>'use strict';
let express = require('express');
let touristSitesController = require('./../../controllers/tourist-sites-controller');
let identity = require('./../../common/identity');

module.exports = function(app) {
  let router = express.Router();

  router
    .post('/', identity.requiresAuthentication(), touristSitesController.addTouristSite);

  app.use('/api/tourist-sites', router);
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 * Mode of operation
 * - check result accuracy
 *   - get a url, and a local path for the same content
 *   - do request on the url and on the local file, and check the result are the same
 * - load test
 *   - get an url on a static content
 *   - just hammer the server with random request
 *
 * TODO
 * - put the oload tester in contrib/
*/

// system dependancies
var sys		= require('sys');
var fs		= require('fs');
// local dependancies
var cmp_digest	= require('./accuracy_test').cmp_digest;
var http_get	= require('../vendor/node-helpers/ez_http').http_get;
var ezhttp	= require('../vendor/node-helpers/ez_http');
var ttyc	= require('../vendor/node-helpers/ez_tty_color');
var strutils	= require('../vendor/node-helpers/strutils');

sys.puts( strutils.string_to_size('300') );
sys.puts( strutils.string_to_size('300b') );
sys.puts( strutils.string_to_size('300k') );
process.exit();
//var url		= "http://localhost/~jerome/Videos/Fearless.avi";
//var url	= "http://localhost:4550/http://127.0.0.1/~jerome/Videos/Fearless.avi";
//var ref_fname	= '/home/jerome/Videos/Fearless.avi';
//var ref_fname	= null;
var url		= process.argv[2];
var ref_fname	= process.argv[3];

// make that tunable via cmdline options
var range_len_base	= null;
var range_len_rand	= null;
var nb_concurent	= 1;

//////////////////////////////////////////////////////////////////////////////////
//	parse cmdline								//
//////////////////////////////////////////////////////////////////////////////////
var optind	= 2;
for(;optind < process.argv.length; optind){
	var key	= process.argv[optind];
	var val	= process.argv[optind+1];
	if( key == "-c" || key == "--concurent" ){
		nb_concurent	= parseInt(val);
		optind		+= 1;
	}else if( key == "-l" || key == "--req_length_base" ){
		range_len_base	= parseInt(val);
		optind		+= 1;
	}else if( key == "-r" || key == "--req_length_rand" ){
		range_len_rand	= parseInt(val);
		optind		+= 1;
	}else if( key == "-h" || key == "--help" ){
		sys.puts("usage: oload_stress_test [-c ncnx] [-l nbytes] [-r nbytes] URL [filename]");
		sys.puts(" - If <filename> is present, an accuracy test is performed. AKA data are loaded from");
		sys.puts("   the reference file and from the <URL> and both are checked to be equal.");
		sys.puts(" - If <filename> is not present, a stress test is performed. AKA data are loaded from");
		sys.puts("   the url as fast as possible.");
		sys.puts("");
		sys.puts("-c|--concurent ncnx\t\tDetermine the number of concurent connections during the tests.");
		sys.puts("-l|--req_length_base nbytes\tThe base length of the request to make");
		sys.puts("-r|--req_length_rand nbytes\tThe randomized length of the request to make");
		process.exit(0);
	}else{
		// if the option doesnt exist, consider it is the first non-option parameters
		break;
	}
}

//////////////////////////////////////////////////////////////////////////////////
//	accuracy test								//
//////////////////////////////////////////////////////////////////////////////////

function do_test_accuracy()
{
	var filesize	= fs.statSync(ref_fname).size
	// set default range_len_base/range_len_rand
	range_len_base	= range_len_base || (filesize / 20.0);
	range_len_rand	= range_len_rand || (range_len_base / 2.0);
	// clamp range_len_base/range_len_rand
	range_len_base	= Math.min(range_len_base, filesize);
	range_len_rand	= Math.min(range_len_rand, range_len_base);

	var cmp_digest_multiple	= function(){
		var range_len	= range_len_base - range_len_rand + Math.floor(Math.random()*range_len_rand*2);
		var range_beg	= Math.floor(Math.random()*(filesize - range_len));

		cmp_digest(url, ref_fname, range_beg, range_len, function(err, succeed){
			if( succeed )	sys.print(".");
			else		sys.puts("accuracy: beg="+range_beg+" len="+range_len+" succeed="+succeed);
			cmp_digest_multiple();
		})
	}

	// display informations headers
	sys.log("Check accuracy between url "+url);
	sys.log("and file "+ ref_fname);
	sys.log("using "+nb_concurent+" concurent requests");
	sys.log("of "+range_len_base+"-bytes +/- "+range_len_rand+"-bytes");

	for(var i = 0; i < nb_concurent; i++ ){
		cmp_digest_multiple();
	}
}

//////////////////////////////////////////////////////////////////////////////////
//	stress	test								//
//////////////////////////////////////////////////////////////////////////////////

function do_test_stress()
{
	var http_request_multiple	= function(){
		var range_len	= range_len_base - range_len_rand + Math.floor(Math.random()*range_len_rand*2);
		var range_beg	= Math.floor(Math.random()*(filesize - range_len));

		http_get(url, range_beg, range_len, function(error, data){
			//sys.puts("stress: beg="+range_beg+" len="+range_len+" error="+error);
			if( error === null )	sys.print(".");
			else			sys.log("beg="+range_beg+" len="+range_len+" error="+error);
			http_request_multiple();
		})
	}

	var callback	= function(error, headers){
		//sys.puts('HEADERS: ' + sys.inspect(headers));
		filesize	= parseInt(headers['content-length'], 10);
		// set default range_len_base/range_len_rand
		range_len_base	= range_len_base || Math.floor(filesize / 20);
		range_len_rand	= range_len_rand || Math.floor(range_len_base / 2);
		// clamp range_len_base/range_len_rand
		range_len_base	= Math.min(range_len_base, filesize);
		range_len_rand	= Math.min(range_len_rand, range_len_base);

		// display informations headers
		sys.log("Stress server at url "+url);
		sys.log("Total content length "+filesize);
		sys.log("using "+nb_concurent+" concurent requests");
		sys.log("of "+range_len_base+"-bytes +/- "+range_len_rand+"-bytes");

		for(var i = 0; i < nb_concurent; i++ ){
			http_request_multiple();
		}
	}

	ezhttp.http_resp_headers(url, callback);
}

if( ref_fname !== undefined )	do_test_accuracy();
else				do_test_stress();

<commit_msg>oload_stress_test: support for string_to_size in range cmdline option 	modified:   contrib/oload_stress_test/oload_stress_test.js<commit_after>#!/usr/bin/env node
/**
 * Mode of operation
 * - check result accuracy
 *   - get a url, and a local path for the same content
 *   - do request on the url and on the local file, and check the result are the same
 * - load test
 *   - get an url on a static content
 *   - just hammer the server with random request
 *
 * TODO
 * - put the oload tester in contrib/
*/

// system dependancies
var sys		= require('sys');
var fs		= require('fs');
// local dependancies
var cmp_digest	= require('./accuracy_test').cmp_digest;
var http_get	= require('../vendor/node-helpers/ez_http').http_get;
var ezhttp	= require('../vendor/node-helpers/ez_http');
var ttyc	= require('../vendor/node-helpers/ez_tty_color');
var strutils	= require('../vendor/node-helpers/strutils');

sys.puts( strutils.string_to_size('300') );
sys.puts( strutils.string_to_size('300b') );
sys.puts( strutils.string_to_size('300k') );
process.exit();
//var url		= "http://localhost/~jerome/Videos/Fearless.avi";
//var url	= "http://localhost:4550/http://127.0.0.1/~jerome/Videos/Fearless.avi";
//var ref_fname	= '/home/jerome/Videos/Fearless.avi';
//var ref_fname	= null;
var url		= process.argv[2];
var ref_fname	= process.argv[3];

// make that tunable via cmdline options
var range_len_base	= null;
var range_len_rand	= null;
var nb_concurent	= 1;

//////////////////////////////////////////////////////////////////////////////////
//	parse cmdline								//
//////////////////////////////////////////////////////////////////////////////////
var optind	= 2;
for(;optind < process.argv.length; optind){
	var key	= process.argv[optind];
	var val	= process.argv[optind+1];
	if( key == "-c" || key == "--concurent" ){
		nb_concurent	= parseInt(val);
		optind		+= 1;
	}else if( key == "-l" || key == "--req_length_base" ){
		range_len_base	= strutils.string_to_size(val);
		optind		+= 1;
	}else if( key == "-r" || key == "--req_length_rand" ){
		range_len_rand	= strutils.string_to_size(val);
		optind		+= 1;
	}else if( key == "-h" || key == "--help" ){
		sys.puts("usage: oload_stress_test [-c ncnx] [-l nbytes] [-r nbytes] URL [filename]");
		sys.puts(" - If <filename> is present, an accuracy test is performed. AKA data are loaded from");
		sys.puts("   the reference file and from the <URL> and both are checked to be equal.");
		sys.puts(" - If <filename> is not present, a stress test is performed. AKA data are loaded from");
		sys.puts("   the url as fast as possible.");
		sys.puts("");
		sys.puts("-c|--concurent ncnx\t\tDetermine the number of concurent connections during the tests.");
		sys.puts("-l|--req_length_base nbytes\tThe base length of the request to make");
		sys.puts("-r|--req_length_rand nbytes\tThe randomized length of the request to make");
		process.exit(0);
	}else{
		// if the option doesnt exist, consider it is the first non-option parameters
		break;
	}
}

//////////////////////////////////////////////////////////////////////////////////
//	accuracy test								//
//////////////////////////////////////////////////////////////////////////////////

function do_test_accuracy()
{
	var filesize	= fs.statSync(ref_fname).size
	// set default range_len_base/range_len_rand
	range_len_base	= range_len_base || (filesize / 20.0);
	range_len_rand	= range_len_rand || (range_len_base / 2.0);
	// clamp range_len_base/range_len_rand
	range_len_base	= Math.min(range_len_base, filesize);
	range_len_rand	= Math.min(range_len_rand, range_len_base);

	var cmp_digest_multiple	= function(){
		var range_len	= range_len_base - range_len_rand + Math.floor(Math.random()*range_len_rand*2);
		var range_beg	= Math.floor(Math.random()*(filesize - range_len));

		cmp_digest(url, ref_fname, range_beg, range_len, function(err, succeed){
			if( succeed )	sys.print(".");
			else		sys.puts("accuracy: beg="+range_beg+" len="+range_len+" succeed="+succeed);
			cmp_digest_multiple();
		})
	}

	// display informations headers
	sys.log("Check accuracy between url "+url);
	sys.log("and file "+ ref_fname);
	sys.log("using "+nb_concurent+" concurent requests");
	sys.log("of "+range_len_base+"-bytes +/- "+range_len_rand+"-bytes");

	for(var i = 0; i < nb_concurent; i++ ){
		cmp_digest_multiple();
	}
}

//////////////////////////////////////////////////////////////////////////////////
//	stress	test								//
//////////////////////////////////////////////////////////////////////////////////

function do_test_stress()
{
	var http_request_multiple	= function(){
		var range_len	= range_len_base - range_len_rand + Math.floor(Math.random()*range_len_rand*2);
		var range_beg	= Math.floor(Math.random()*(filesize - range_len));

		http_get(url, range_beg, range_len, function(error, data){
			//sys.puts("stress: beg="+range_beg+" len="+range_len+" error="+error);
			if( error === null )	sys.print(".");
			else			sys.log("beg="+range_beg+" len="+range_len+" error="+error);
			http_request_multiple();
		})
	}

	var callback	= function(error, headers){
		//sys.puts('HEADERS: ' + sys.inspect(headers));
		filesize	= parseInt(headers['content-length'], 10);
		// set default range_len_base/range_len_rand
		range_len_base	= range_len_base || Math.floor(filesize / 20);
		range_len_rand	= range_len_rand || Math.floor(range_len_base / 2);
		// clamp range_len_base/range_len_rand
		range_len_base	= Math.min(range_len_base, filesize);
		range_len_rand	= Math.min(range_len_rand, range_len_base);

		// display informations headers
		sys.log("Stress server at url "+url);
		sys.log("Total content length "+filesize);
		sys.log("using "+nb_concurent+" concurent requests");
		sys.log("of "+range_len_base+"-bytes +/- "+range_len_rand+"-bytes");

		for(var i = 0; i < nb_concurent; i++ ){
			http_request_multiple();
		}
	}

	ezhttp.http_resp_headers(url, callback);
}

if( ref_fname !== undefined )	do_test_accuracy();
else				do_test_stress();

<|endoftext|>


<commit_before>$(document).ready(function() {
	/*$('div').mouseenter(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
		});
	$('div').mouseleave(function() {
  		$(this).animate({height: "57px", width: "57px", position: 'relative'});
	});
	$('div').click(function() {
			$(this).effect("bounce", "slow");
	});*/
	$("#box1").mouseenter(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
		});
	$("#box1").mouseleave(function() {
  		$(this).animate({height: "57px", width: "57px", position: 'relative'});
	});
	$("#box1").click(function() {
			$(this).effect("bounce", "slow");
	});
	$("#box2").mouseenter(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
		});
	$("#box2").mouseleave(function() {
  		$(this).animate({height: "57px", width: "57px", position: 'relative'});
	});
	$("#box2").click(function() {
			$(this).effect("bounce", "slow");
	});
	$("#box3").mouseenter(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
		});
	$("#box3").mouseleave(function() {
  		$(this).animate({height: "57px", width: "57px", position: 'relative'});
	});
	$("#box3").click(function() {
			$(this).effect("bounce", "slow");
	});
	$("#box4").mouseenter(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
		});
	$("#box4").mouseleave(function() {
  		$(this).animate({height: "57px", width: "57px", position: 'relative'});
	});
	$("#box4").click(function() {
			$(this).effect("bounce", "slow");
	});
	$("#box5").mouseenter(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
		});
	$("#box5").mouseleave(function() {
  		$(this).animate({height: "57px", width: "57px", position: 'relative'});
	});
	$("#box5").click(function() {
			$(this).effect("bounce", "slow");
	});

	/*$('div').hover(function() {
			$(this).effect("bounce","fast");
		});*/
/*
    $('div').mouseenter(function() {
		$(this).fadeTo(function() {
    	$(this).width(200);
		});
	});
	$('div').mouseleave(function() {
    	$(this).fadeTo(function() {
			$(this).width(100);
		});
	}); */

});<commit_msg>mod jquery on divs<commit_after>$(document).ready(function() {
	$("#box1").mouseenter(function() {
  		$(this).animate({height: "125px", width: "125px", position: 'relative'});
		});
	$("#box1").mouseleave(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
	});
	$("#box1").click(function() {
			$(this).effect("bounce", "slow");
	});
	$("#box2").mouseenter(function() {
  		$(this).animate({height: "125px", width: "125px", position: 'relative'});
		});
	$("#box2").mouseleave(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
	});
	$("#box2").click(function() {
			$(this).effect("bounce", "slow");
	});
	$("#box3").mouseenter(function() {
  		$(this).animate({height: "125px", width: "125px", position: 'relative'});
		});
	$("#box3").mouseleave(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
	});
	$("#box3").click(function() {
			$(this).effect("bounce", "slow");
	});
	$("#box4").mouseenter(function() {
  		$(this).animate({height: "125px", width: "125px", position: 'relative'});
		});
	$("#box4").mouseleave(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
	});
	$("#box4").click(function() {
			$(this).effect("bounce", "slow");
	});
	$("#box5").mouseenter(function() {
  		$(this).animate({height: "125px", width: "125px", position: 'relative'});
		});
	$("#box5").mouseleave(function() {
  		$(this).animate({height: "100px", width: "100px", position: 'relative'});
	});
	$("#box5").click(function() {
			$(this).effect("bounce", "slow");
	});

});<|endoftext|>