Affichage des articles dont le libellé est Active questions tagged javascript - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged javascript - Stack Overflow. Afficher tous les articles

mardi 4 août 2015

How do I prevent backbone remove() from removing "el" in a view?

I want remove a view before creating a new one. But my requirement is view.remove() should remove the view but not delete the el element. Having said this, I do not want to set tagName as it crates a new element which is unnecessary. Is there any way to remove a view from the memory leaving the el content cleared?

Why does asm.js deteriorate performance?

Just to see how it performs, I wrote a very short asm.js module by hand, which simulates the 2D wave equation using 32-bit integer math and typed arrays (Int32Array). I have three versions of it, all as similar as possible:

  1. Ordinary (i.e. legible, albeit C-style) JavaScript
  2. Same as 1, with asm.js annotations added so that it passes the validator, according to Firefox and other tools
  3. Same as 2, except with no "use asm"; directive at the top

I left a demo at http://ift.tt/1M8UwwH which lets you switch between modules to see the effects of using each one. All three work, but at different speeds. This is the hotspot (with asm.js annotations):

for (i = 0; ~~i < ~~h; i = (1 + i)|0) {
    for (j = 0; ~~j < ~~w; j = (1 + j)|0) {
        if (~~i == 0) {
            index = (1 + index) | 0;
            continue;
        }
        if (~~(i + 1) == ~~h) {
            index = (1 + index) | 0;
            continue;
        }
        if (~~j == 0) {
            index = (1 + index) | 0;
            continue;
        }
        if (~~(j + 1) == ~~w) {
            index = (1 + index) | 0;
            continue;
        }
        uCen = signedHeap  [((u0_offset + index) << 2) >> 2] | 0;
        uNorth = signedHeap[((u0_offset + index - w) << 2) >> 2] | 0;
        uSouth = signedHeap[((u0_offset + index + w) << 2) >> 2] | 0;
        uWest = signedHeap [((u0_offset + index - 1) << 2) >> 2] | 0;
        uEast = signedHeap [((u0_offset + index + 1) << 2) >> 2] | 0;
        uxx = (((uWest + uEast) >> 1) - uCen) | 0;
        uyy = (((uNorth + uSouth) >> 1) - uCen) | 0;
        vel = signedHeap[((vel_offset + index) << 2) >> 2] | 0;
        vel = vel + (uxx >> 1) | 0;
        vel = applyCap(vel) | 0;
        vel = vel + (uyy >> 1) | 0;
        vel = applyCap(vel) | 0;
        force = signedHeap[((force_offset + index) << 2) >> 2] | 0;
        signedHeap[((u1_offset + index) << 2) >> 2] = applyCap(((applyCap((uCen + vel) | 0) | 0) + force) | 0) | 0;
        force = force - (force >> forceDampingBitShift) | 0;
        signedHeap[((force_offset + index) << 2) >> 2] = force;
        vel = vel - (vel >> velocityDampingBitShift) | 0;
        signedHeap[((vel_offset + index) << 2) >> 2] = vel;
        index = (index + 1)|0;
    }
}

The "ordinary JavaScript" version is structured as above, but without the bitwise operators that asm.js requires (e.g. "x|0", "~~x", "arr[(x<<2)>>2]", etc.)

These are the results for all three modules on my machine, using Firefox (Developer Edition v. 41) and Chrome (version 44), in milliseconds per iteration:

  • FIREFOX (version 41): 20 ms, 35 ms, 60 ms.
  • CHROME (version 44): 25 ms, 150 ms, 75 ms.

So ordinary JavaScript wins in both browsers. The presence of asm.js-required annotations deteriorates performance by a factor of 3 in both. Furthermore, the presence of the "use asm"; directive has an obvious effect- it helps Firefox a bit, and brings Chrome to its knees!

It seems strange that merely adding bitwise operators should introduce a threefold performance degradation that can't be overcome by telling the browser to use asm.js. Also, why does telling the browser to use asm.js only help marginally in Firefox, and completely backfire in Chrome?

d3 function(d) return value from object not from the first index(0)

why d3 function(d) return value from object not from the first index(0)

tr.append('td').html(function(m) { console.log(m.INDEX) ;return m.INDEX; })

from this function i have value from index 1 to m.INDEX.length ?

Can't understand a javascript .call() usage

I'm trying to learn the three.js library by reading the "WebGL Up And Running" book and the problem for me is that the author made his own javascript framework called 'sim.js' which is a "higher-level set of reusable objects build upon three.js that wraps the more repetitive Three.js tasks" as he said but for a beginner like me i'd prefer more experiencing the raw three.js first.. So now i have to understand what his framwork does to understand what happens under the hood.

this is the sim.js

// Sim.js - A Simple Simulator for WebGL (based on Three.js)

Sim = {};

// Sim.Publisher - base class for event publishers
Sim.Publisher = function() {
    this.messageTypes = {};
}

Sim.Publisher.prototype.subscribe = function(message, subscriber, callback) {
    var subscribers = this.messageTypes[message];
    if (subscribers)
    {
        if (this.findSubscriber(subscribers, subscriber) != -1)
        {
            return;
        }
    }
    else
    {
        subscribers = [];
        this.messageTypes[message] = subscribers;
    }

    subscribers.push({ subscriber : subscriber, callback : callback });
}

Sim.Publisher.prototype.unsubscribe =  function(message, subscriber, callback) {
    if (subscriber)
    {
        var subscribers = this.messageTypes[message];

        if (subscribers)
        {
            var i = this.findSubscriber(subscribers, subscriber, callback);
            if (i != -1)
            {
                this.messageTypes[message].splice(i, 1);
            }
        }
    }
    else
    {
        delete this.messageTypes[message];
    }
}

Sim.Publisher.prototype.publish = function(message) {
    var subscribers = this.messageTypes[message];

    if (subscribers)
    {
        for (var i = 0; i < subscribers.length; i++)
        {
            var args = [];
            for (var j = 0; j < arguments.length - 1; j++)
            {
                args.push(arguments[j + 1]);
            }
            subscribers[i].callback.apply(subscribers[i].subscriber, args);
        }
    }
}

Sim.Publisher.prototype.findSubscriber = function (subscribers, subscriber) {
    for (var i = 0; i < subscribers.length; i++)
    {
        if (subscribers[i] == subscriber)
        {
            return i;
        }
    }

    return -1;
}

// Sim.App - application class (singleton)
Sim.App = function()
{
    Sim.Publisher.call(this);

    this.renderer = null;
    this.scene = null;
    this.camera = null;
    this.objects = [];
}

Sim.App.prototype = new Sim.Publisher;

Sim.App.prototype.init = function(param)
{
    param = param || {};    
    var container = param.container;
    var canvas = param.canvas;

    // Create the Three.js renderer, add it to our div
    var renderer = new THREE.WebGLRenderer( { antialias: true, canvas: canvas } );
    renderer.setSize(container.offsetWidth, container.offsetHeight);
    container.appendChild( renderer.domElement );

    // Create a new Three.js scene
    var scene = new THREE.Scene();
    scene.add( new THREE.AmbientLight( 0x505050 ) );
    scene.data = this;

    // Put in a camera at a good default location
    camera = new THREE.PerspectiveCamera( 45, container.offsetWidth / container.offsetHeight, 1, 10000 );
    camera.position.set( 0, 0, 3.3333 );

    scene.add(camera);

    // Create a root object to contain all other scene objects
    var root = new THREE.Object3D();
    scene.add(root);

    // Create a projector to handle picking
    var projector = new THREE.Projector();

    // Save away a few things
    this.container = container;
    this.renderer = renderer;
    this.scene = scene;
    this.camera = camera;
    this.projector = projector;
    this.root = root;

    // Set up event handlers
    this.initMouse();
    this.initKeyboard();
    this.addDomHandlers();
}

//Core run loop
Sim.App.prototype.run = function()
{
    this.update();
    this.renderer.render( this.scene, this.camera );
    var that = this;
    requestAnimationFrame(function() { that.run(); });  
}

// Update method - called once per tick
Sim.App.prototype.update = function()
{
    var i, len;
    len = this.objects.length;
    for (i = 0; i < len; i++)
    {
        this.objects[i].update();
    }
}

// Add/remove objects
Sim.App.prototype.addObject = function(obj)
{
    this.objects.push(obj);

    // If this is a renderable object, add it to the root scene
    if (obj.object3D)
    {
        this.root.add(obj.object3D);
    }
}

Sim.App.prototype.removeObject = function(obj)
{
    var index = this.objects.indexOf(obj);
    if (index != -1)
    {
        this.objects.splice(index, 1);
        // If this is a renderable object, remove it from the root scene
        if (obj.object3D)
        {
            this.root.remove(obj.object3D);
        }
    }
}

// Event handling
Sim.App.prototype.initMouse = function()
{
    var dom = this.renderer.domElement;

    var that = this;
    dom.addEventListener( 'mousemove', 
            function(e) { that.onDocumentMouseMove(e); }, false );
    dom.addEventListener( 'mousedown', 
            function(e) { that.onDocumentMouseDown(e); }, false );
    dom.addEventListener( 'mouseup', 
            function(e) { that.onDocumentMouseUp(e); }, false );

    $(dom).mousewheel(
            function(e, delta) {
                that.onDocumentMouseScroll(e, delta);
            }
        );

    this.overObject = null;
    this.clickedObject = null;
}

Sim.App.prototype.initKeyboard = function()
{
    var dom = this.renderer.domElement;

    var that = this;
    dom.addEventListener( 'keydown', 
            function(e) { that.onKeyDown(e); }, false );
    dom.addEventListener( 'keyup', 
            function(e) { that.onKeyUp(e); }, false );
    dom.addEventListener( 'keypress', 
            function(e) { that.onKeyPress(e); }, false );

    // so it can take focus
    dom.setAttribute("tabindex", 1);
    dom.style.outline='none';
}

Sim.App.prototype.addDomHandlers = function()
{
    var that = this;
    window.addEventListener( 'resize', function(event) { that.onWindowResize(event); }, false );
}

Sim.App.prototype.onDocumentMouseMove = function(event)
{
    event.preventDefault();

    if (this.clickedObject && this.clickedObject.handleMouseMove)
    {
        var hitpoint = null, hitnormal = null;
        var intersected = this.objectFromMouse(event.pageX, event.pageY);
        if (intersected.object == this.clickedObject)
        {
            hitpoint = intersected.point;
            hitnormal = intersected.normal;
        }
        this.clickedObject.handleMouseMove(event.pageX, event.pageY, hitpoint, hitnormal);
    }
    else
    {
        var handled = false;

        var oldObj = this.overObject;
        var intersected = this.objectFromMouse(event.pageX, event.pageY);
        this.overObject = intersected.object;

        if (this.overObject != oldObj)
        {
            if (oldObj)
            {
                this.container.style.cursor = 'auto';

                if (oldObj.handleMouseOut)
                {
                    oldObj.handleMouseOut(event.pageX, event.pageY);
                }
            }

            if (this.overObject)
            {
                if (this.overObject.overCursor)
                {
                    this.container.style.cursor = this.overObject.overCursor;
                }

                if (this.overObject.handleMouseOver)
                {
                    this.overObject.handleMouseOver(event.pageX, event.pageY);
                }
            }

            handled = true;
        }

        if (!handled && this.handleMouseMove)
        {
            this.handleMouseMove(event.pageX, event.pageY);
        }
    }
}

Sim.App.prototype.onDocumentMouseDown = function(event)
{
    event.preventDefault();

    var handled = false;

    var intersected = this.objectFromMouse(event.pageX, event.pageY);
    if (intersected.object)
    {
        if (intersected.object.handleMouseDown)
        {
            intersected.object.handleMouseDown(event.pageX, event.pageY, intersected.point, intersected.normal);
            this.clickedObject = intersected.object;
            handled = true;
        }
    }

    if (!handled && this.handleMouseDown)
    {
        this.handleMouseDown(event.pageX, event.pageY);
    }
}

Sim.App.prototype.onDocumentMouseUp = function(event)
{
    event.preventDefault();

    var handled = false;

    var intersected = this.objectFromMouse(event.pageX, event.pageY);
    if (intersected.object)
    {
        if (intersected.object.handleMouseUp)
        {
            intersected.object.handleMouseUp(event.pageX, event.pageY, intersected.point, intersected.normal);
            handled = true;
        }
    }

    if (!handled && this.handleMouseUp)
    {
        this.handleMouseUp(event.pageX, event.pageY);
    }

    this.clickedObject = null;
}

Sim.App.prototype.onDocumentMouseScroll = function(event, delta)
{
    event.preventDefault();

    if (this.handleMouseScroll)
    {
        this.handleMouseScroll(delta);
    }
}

Sim.App.prototype.objectFromMouse = function(pagex, pagey)
{
    // Translate page coords to element coords
    var offset = $(this.renderer.domElement).offset();  
    var eltx = pagex - offset.left;
    var elty = pagey - offset.top;

    // Translate client coords into viewport x,y
    var vpx = ( eltx / this.container.offsetWidth ) * 2 - 1;
    var vpy = - ( elty / this.container.offsetHeight ) * 2 + 1;

    var vector = new THREE.Vector3( vpx, vpy, 0.5 );

    this.projector.unprojectVector( vector, this.camera );

    var ray = new THREE.Ray( this.camera.position, vector.subSelf( this.camera.position ).normalize() );

    var intersects = ray.intersectScene( this.scene );

    if ( intersects.length > 0 ) {      

        var i = 0;
        while(!intersects[i].object.visible)
        {
            i++;
        }

        var intersected = intersects[i];
        var mat = new THREE.Matrix4().getInverse(intersected.object.matrixWorld);
        var point = mat.multiplyVector3(intersected.point);

        return (this.findObjectFromIntersected(intersected.object, intersected.point, intersected.face.normal));                                                 
    }
    else
    {
        return { object : null, point : null, normal : null };
    }
}

Sim.App.prototype.findObjectFromIntersected = function(object, point, normal)
{
    if (object.data)
    {
        return { object: object.data, point: point, normal: normal };
    }
    else if (object.parent)
    {
        return this.findObjectFromIntersected(object.parent, point, normal);
    }
    else
    {
        return { object : null, point : null, normal : null };
    }
}


Sim.App.prototype.onKeyDown = function(event)
{
    // N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
    event.preventDefault();

    if (this.handleKeyDown)
    {
        this.handleKeyDown(event.keyCode, event.charCode);
    }
}

Sim.App.prototype.onKeyUp = function(event)
{
    // N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
    event.preventDefault();

    if (this.handleKeyUp)
    {
        this.handleKeyUp(event.keyCode, event.charCode);
    }
}

Sim.App.prototype.onKeyPress = function(event)
{
    // N.B.: Chrome doesn't deliver keyPress if we don't bubble... keep an eye on this
    event.preventDefault();

    if (this.handleKeyPress)
    {
        this.handleKeyPress(event.keyCode, event.charCode);
    }
}

Sim.App.prototype.onWindowResize = function(event) {

    this.renderer.setSize(this.container.offsetWidth, this.container.offsetHeight);

    this.camera.aspect = this.container.offsetWidth / this.container.offsetHeight;
    this.camera.updateProjectionMatrix();

}

Sim.App.prototype.focus = function()
{
    if (this.renderer && this.renderer.domElement)
    {
        this.renderer.domElement.focus();
    }
}


// Sim.Object - base class for all objects in our simulation
Sim.Object = function()
{
    Sim.Publisher.call(this);

    this.object3D = null;
    this.children = [];
}

Sim.Object.prototype = new Sim.Publisher;

Sim.Object.prototype.init = function()
{
}

Sim.Object.prototype.update = function()
{
    this.updateChildren();
}

// setPosition - move the object to a new position
Sim.Object.prototype.setPosition = function(x, y, z)
{
    if (this.object3D)
    {
        this.object3D.position.set(x, y, z);
    }
}

//setScale - scale the object
Sim.Object.prototype.setScale = function(x, y, z)
{
    if (this.object3D)
    {
        this.object3D.scale.set(x, y, z);
    }
}

//setScale - scale the object
Sim.Object.prototype.setVisible = function(visible)
{
    function setVisible(obj, visible)
    {
        obj.visible = visible;
        var i, len = obj.children.length;
        for (i = 0; i < len; i++)
        {
            setVisible(obj.children[i], visible);
        }
    }

    if (this.object3D)
    {
        setVisible(this.object3D, visible);
    }
}

// updateChildren - update all child objects
Sim.Object.prototype.update = function()
{
    var i, len;
    len = this.children.length;
    for (i = 0; i < len; i++)
    {
        this.children[i].update();
    }
}

Sim.Object.prototype.setObject3D = function(object3D)
{
    object3D.data = this;
    this.object3D = object3D;
}

//Add/remove children
Sim.Object.prototype.addChild = function(child)
{
    this.children.push(child);

    // If this is a renderable object, add its object3D as a child of mine
    if (child.object3D)
    {
        this.object3D.add(child.object3D);
    }
}

Sim.Object.prototype.removeChild = function(child)
{
    var index = this.children.indexOf(child);
    if (index != -1)
    {
        this.children.splice(index, 1);
        // If this is a renderable object, remove its object3D as a child of mine
        if (child.object3D)
        {
            this.object3D.remove(child.object3D);
        }
    }
}

// Some utility methods
Sim.Object.prototype.getScene = function()
{
    var scene = null;
    if (this.object3D)
    {
        var obj = this.object3D;
        while (obj.parent)
        {
            obj = obj.parent;
        }

        scene = obj;
    }

    return scene;
}

Sim.Object.prototype.getApp = function()
{
    var scene = this.getScene();
    return scene ? scene.data : null;
}

// Some constants

/* key codes
37: left
38: up
39: right
40: down
*/
Sim.KeyCodes = {};
Sim.KeyCodes.KEY_LEFT  = 37;
Sim.KeyCodes.KEY_UP  = 38;
Sim.KeyCodes.KEY_RIGHT  = 39;
Sim.KeyCodes.KEY_DOWN  = 40;

in another script he wrote a new class called earth-basic based on the sim class so, the begining of the earth-basic.js script looks as the following :

// Constructor
EarthApp = function()
{
    Sim.App.call(this);
}

// Subclass Sim.App
EarthApp.prototype = new Sim.App();

// Our custom initializer
EarthApp.prototype.init = function(param)
{
    // Call superclass init code to set up scene, renderer, default camera
    Sim.App.prototype.init.call(this, param);

    // Create the Earth and add it to our sim
    var earth = new Earth();
    earth.init();
    this.addObject(earth);
}

// Custom Earth class
Earth = function()
{
    Sim.Object.call(this);
}

Earth.prototype = new Sim.Object();

1) what does the function call in the line "Sim.App.call(this);" written in the constructor (by passing "this" as parameter which i suppose is referring to the EarthApp variable)? all what i can guess is that EarthApp will inherit the Sim.App properties (the renderer, the camera ...). The same "technique" was used inside the "Sim.App" function itself by calling "Sim.Publisher.call(this);"

2) in 1) i supposed he just used the sim.App class as a super-Class but then all of a sudden, i found he added a new instance of sim.App() to the EarthApp's prototype by writting "EarthApp.prototype = new Sim.App();" PLease guys tell me what the heck is going on in there.

Using AJAX response in Javascript Array? [duplicate]

This question already has an answer here:

I'm not entirely sure if this is possible but I am trying to use an ajax response in a javascript array in my page.

this is what I have:

var interval = 5000;
function doAjax() {
    jQuery.ajax({
            type: 'POST',
            url: 've.php',
            dataType : 'json',
            success: function (data) {


            //var arr = data.split('|');
                    jQuery('#counterint').html(data);

                    var res = $.parseJSON(data);   



//test: simulated ajax

var testLocs = {

<<<<<<<<<<<<<< I NEED TO USE THE "data" HERE >>>>>>>>>>>>>>>>>

    };


setMarkers(testLocs); 

The ajax response looks like this when I outputs it on my page in the browser:

1: { info: '1. rooz', lat: 51.5033630, lng: -0.1276250 },2: { info: '1. Rooz555', lat: 51.5033567, lng: -0.1276444 },3: { info: '1. david', lat: 51.5033777, lng: -0.1276777 },4: { info: '1. sam', lat: 51.5033555, lng: -0.1276543 },

any help would be appreciated.

Most efficient way to restructure complex array of objects in javascript?

I have a large set of data that looks similar to this:

var original = [
  { country : 'us', date : '2014-10-29', cost : 45.3 },
  { country : 'africa', date : '2014-10-29', cost : 60.5 },
  { country : 'south_america', date : '2014-10-30', cost : 10 },
  { country : 'us', date : '2014-10-30', cost : 30 }
];

I need to rearrange this data so that it looks more like this:

var newData = [
  { date : '2014-10-29', us : 45.3, africa : 60.5, south_america : 0 },
  { date : '2014-10-30', us : 30, africa : 0, south_america : 10 }
]

I'm new to dealing with datasets like this and I'm struggling to find any efficient way to handle this... The only thing I can come up with uses multiple for loops and just looks gross. Does anyone have any ideas or suggestions?

jQuery - end setinterval after X rund

I have a little slider im working on which is almost there im jsut having some trouble with me jQuery.


So first off: I want my slider to reset after the interval has run x amount of times. It was my understanding that the following would work but it doesn't seem to take. 6000, slides, function() { homesliderend();

so lets say slides = 2 set interval should call homesliderend(); but it doesn't the interval just keeps running.


Second Issue: I'm also trying to get it to add 100% to lengther every 6 seconds. But instead of adding 100 each time its just setting it to 100 its not multiplying.

jQuery(document).ready(function($) {
  "use strict";

  function homesliderend() {
    $(".lengther").animate({
      left: "0%"
    }, 500);
  }

  function homeslider() {
    var slides = $(".slide.t-align").length,
      lwidth = slides * 100,
      n = 0;

    $(".lengther").css("width", lwidth + "%");

    setInterval(function() {
      var tn = n + 100;
      $(".lengther").animate({
        left: "-" + tn + "%"
      }, 500);
    }, 6000, slides, function() {
      homesliderend();
    });


  }
  homeslider();
});

how to populate select box with jquery?

i have a requirement in which when i click on a element of a list , the element gets shown as a selected option in the select box

i need to use native select box only , not to mention the elements in the list are present in the select dropdown

<button class="quick">QuickLink</button>

<div class="list">
<ul class="apps">
    <li>CAPM</li>
    <li>GCS</li>
    <li>GRS</li>
</ul>
</div>

<select class="xyz">
<option>CAPM</option>
<option>GRS</option>
<option>BDS</option>
<option>CCAS</option>
<option>WEDAT</option>
<option>SDP</option>
</select>

jsfiddle link --> http://ift.tt/1JJS2mI

Pass ng-model as argument in directive angualjrs

I am writing a directive in angularjs and I want to pass ng-model as argument.

<div class="col-md-7"><time-picker></time-picker></div>

Directive is ,

    app.directive('timePicker', function () {
    return {
        restrict: 'E',
        replace: true,
        template: '<input type="text" class="form-control time-picker" ng-model="emp.signin">',
        link: function ($scope, element, form) {
            $(element).timepicker({'timeFormat': 'H:i:s'});
        }
    }
})

It is working find, and here ng-model is emp.signin and I put this directly. I want able to pass this ng-model dynamically as argument

how it is possible?

Highcharts with DHTMLX menu appearance

I use dhtmlx menu on my charts. (legendItemClick event). It was working well when i use highcharts 3.0.1 . Today, I upgraded to 4.1.7 but dhtmlx menu's legendMenu_<?=$id?>.showContextMenu(x,y) function does not work like old one.

When i inspect the menu element on firebug, i see display: "none". I tried to change it manually. However, Id is randomly generated.

legendMenu_<?=$id?> = new dhtmlXMenuObject();
legendMenu_<?=$id?>.renderAsContextMenu();

How can i fix?

NodeJS best practices with Promises

I am developing a new library above amqp.node (amqplib), basically we dont need all the RabbitMQ functionality. So, I am creating a simple library that facilitates the usage specifically for our project.

This new library will return Promises. So, for example, subscribing to a queue will return a Promise about Ok and Error. But, what should I do with later issues? Disconnect, reconnect, Queue deleted, etc, etc? This will happen after the promise has been resolve. Should my new class emit his own errors? Is this a good way of working with promises?

How to structure Protractor promises

In this example I'm testing whether an element is located at the bottom of the page. I'm using the promises in Protractor/Webdriver, but I think I'm using it wrong because I don't think it's supposed to look this messy.

describe('Element', function(){
    it('should be placed at bottom', function(){
        element(by.id('page').getSize().then(function(dimP){
            element(by.id('element').getLocation().then(function(locE){
                element(by.id('element').getSize().then(function(dimE){
                    expect(locE.y + dimE.height).toEqual(dimP.height);
                })
            });
        });
    })
});

How can I do this in a cleaner way? I'm using Protractor version 2.1.0.

I have tried to do like this:

expect(element(by.id('page').getSize().height).toEqual(1000);

But it says Expected undefined to equal 1000. So it seems like I can't use return values as explained here: http://ift.tt/1sOZ9jh

(I am using a page object in my actual test, so the variables are not as ugly as in the example.)

In AngularJS how do I substitute minified javascript files with non-minified files in my development environment?

What is the best way to handle this in AngularJS?

I have an AngularJS app that includes concatenated/minified javascript files, however in my development environment I want to load the non-concatented/non-minified versions of the file. I want this because it is easier to debug the code with non-minified files.

<!-- production -->
<script src="js/all.min.js"></script> <!-- contains all concatenated/minified code -->

<!-- dev -->
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/directives.js"></script>

I am not sure how to do this since in AngularJS I couldn't find a conditional mechanism that is suitable. I had thought about using a directive on the each script tag?

I am using Gulp to concat and uglify the files, but I couldn't find a method to accomplish this with Gulp.

PHP is the server-side language.

Any help will be greatly appreciated.

How to display different pages in iframes for different time intervals dynamically

I have 2 Iframes having the ids demo and demo1. I have a list of 5 html files (promo1,promo2,promo3,promo4,promo5) which have to be displayed in both Iframes, one after the other, repeatedly. Each html page has a different time intervals for which it should be displayed in the frame

Here is my JavaScript code in which the dict represents each html and the time for which it should be displayed.

the following code makes the browser crash and fill up the memory. i know its because of the reccurrsion. please help me

;(function($){

"use strict";

var index=1,
  dict={"promo1":70000,"promo2":46500,"promo3":18000,"promo4":93000,"promo5":86000},

var $firstFrame = $("#demo"),
  $secondFrame = $("#demo1");

$(function (){

  function demo(frameId,index){

    frameId.attr("src","static/promo" + index + ".html");
    frameId.load(function(){
      if(a){

        a.clearTimeout();
      }
      if(index < 5){

        a = setTimeout(demo(frameId , index + 1),dict["promo"+index]);
      }
      else if(index = 5){
        var a = setTimeout(demo(frameId , 1),dict["promo"+index]);
      }

    });
    index += 1;

      if(index > 5){

        index = 1;
      }

 }
 demo($firstFrame , 1);
 });
}(window.jQuery));

Checkbox doesn't work

I have a simple code with a javascript checkbox. You can see the frontend in this website:
englishforyou.ir
When you check the check box the total price should show the new figure but it doesn't.
All my code is in one page:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<div>
<div>    

 <?php
$title= "pen" ;
$penprice= 7 ;

?>
<form id="formpayment"  action="<?php echo  $urlname?>"  method="post"  > 
<p style="color:blue; font:11px">
 <input type="checkbox" id="check"  name="kol" />Please add the eraser (Add 5$)
 <br>
 </p>
  <table border="0" >
  <tr>
  <td><?php echo $title; ?>
  </td>
  <td ><input style="width: 60px; padding: 2px; border: 0px "  class="txt"  type="text" name="priceofpen" id="priceofpen" value="<?php echo $penprice ;?>   
  " readonly/>&nbsp$ 
  </td>
  <td>
  </td>
  </TR>
 <tr>
  <td><?php echo "Eraser price"; ?>   
  </td>
  <td  >  <input style="width: 50px; padding: 2px; border: 0px "  name="priceoferaser" class="txt" id="priceoferaser" value="0"  readonly="readonly" />  &nbsp; &nbsp;$
  </td>
  <td> 
  </td>
  </TR> 
  <tr>
  <td colspan="3"> <hr />    
  </td>
    </TR>
  <tr id="summation">
  <td>  Total:
  </td>
  <td>
  <input  style="width: 60px; padding: 2px; border: 0px " type=number name="total" id="total" value="<?php echo $penprice;?>"  readonly="readonly">$
  </td>
  <td>
  </td>
  </TR>
   </table>
    </p><br />
 </form>
  </div>
 </div>
 <script>
 $('#check').on('change',function(){
     var eraserprice = "5"

     var c=parseFloat(eraserprice)+ parseFloat(<?php echo $penprice;?>);
    if(this.checked)
     $('#total').val(    c     )&& $('#priceoferaser').val(   parseFloat(5000)    )  ) 

    else

        $('#total').val( <?php echo $penprice;?>)&& $('#priceoferaser').val(   parseFloat(0)    )

})
 </script>
</div>
</body>
</html>

jQuery data() value conversion

I like the fact that $('element').data() converts values to integer, float, array etc.

If I use the dataset property I only get strings.

But the problem is that jQuery.data does not update the values if I alter the data attributes on the element.

Can I use dataset but also be able to convert the values like jQuery.data() does ?

For example data-num="5" should be integer, data-bool="false" should be boolean, data-arr="[1,2]" should be array etc.

Unit test nodeJS RESTful api

As its begining of my journey with unit test I have specific question about 'should that be unit tested or not'. Ive read few articles but not everything is clear for me - I guess particular decision need practice.

Situation more or less sees like this:

I have NodeJS service appplication with RESTful api. As you can guess it allows us to consume endpoints with proper headers/body/parameters.

Headers are kind of complicated - I mean, it contains authorization field and couple more. Ive figure out that I have to make a few 'worker' oraz 'factories' however we call it to provide those things.

So pseudo-code would looks like this:

DataCreator.js - is responsible for providing the whole object passed to endpoint(example below)

function PostData(schema) {

return {
    data: CreatorWorker.dataForPost(someParamsToEvaluate),
    headers: Headers.PostHeader(),
    timeout: Config.GetTimeoutInMs();
 };
}

We could use this one as:

SomeFileWithServer.js (UrlCreator is another piece of program responsible for.. of course providing proper URL)

rest.post(UrlCreator.SetPostUrl(), DataCreator.PostData())

My question is : how would unit test of DataCreator look like? What do we test here? Presence of data, headers, timeout fields? We should mock/stub all used methods (dataForPost, PostHeader...) and after that check if provided values are assign to proper fields? - or maybe both.

Going deeper.. for instance CreatorWorker.dataForPost(someParamsToEvaluate) providing body for reuqest, so inside we just check if its created in good way with proper 'someParamsToEvaluate'. --> So this situation is clear for me, one method.. it does a thing so we should check it if its done right.

So the question is, should we in such situations link particular method (e.g Headers.PostHeader) to field (headers) ? Its a good practice? Maybe we should just check if its get called? Or as I mention before we should stub it and check if headers value equals that (thats the 'linking').

Ive imagined situation when we want to refractor names of those methods, then we will have to maintain those tests.. There's plenty situations like that so I'd like to know good pattern for that.

I hope its explained clearly!

How to make a BIG stage with drag & flick inside a canvas using Pixi.js?

I am learning a PixiJS to make an animation like this: http://ift.tt/1S5a96N.

I have already created a project environment. But I am struggling with making a big stage and having a drag / flick interaction in it like the one in the website mentioned above.

How should I make a BIG stage with drag & flick inside a canvas created using PixiJS?

Here is my JavaScript code so far:

var screen_width = $(window).innerWidth();
var screen_height = $(window).innerHeight();
var renderer = PIXI.autoDetectRenderer(screen_width, screen_height, {backgroundColor: 0xcccccc});
var stage = new PIXI.Container();
var texture = new PIXI.Texture.fromImage('images/pixel.jpg');
var bg = new PIXI.Sprite(texture);

$('body').append(renderer.view);
bg.position.x = 0;
bg.position.y = 0;
stage.addChild(bg);

function animate() {
    requestAnimationFrame(animate);
    renderer.render(stage);
}

animate();

I do not know how to:

  • draw a 1:1 size background image. This image is more than 1920x1800 in dimensions.
  • implement the drag & flick interactions if the image exceeds the viewport / screen size.

Thanks. Hopefully someone will provide me with some references.

how to make use fake ui permanent in chrome?

I have made an application to record a video by following this steps : http://ift.tt/1vdZW0w,

I want access to allow the camera always 'allow', i've tried bypass the allow permission in popup allow webcam use start chrome --use--fake-ui--for--media-stream and it's work for me, but when i closed my chrome and then i opened chrome again , the popup permission allow webcam still showing, what's the solution?

How can I stop my function from returning "Reference error: (...) is not defined"

I've got this code and it's returning that reference error, but I have no idea why, I've seen lots of Q&As about reference errors, but I still can't find it. Any help is appreciated.

Thanks in advance and may the force be with you.

My code:

 var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"node2","id":6,"children":[{"name":"child3","id":7}]},{"name":"child1","id":2}]}]';

 var dadSon = [];

 (function printDadSon(data, parent) {
   if (!data) return;
   for (var i = 0; i < (data.length); i++) {
     if (parent && parent != 'undefined') {
       console.log('Dad: ' + parent + ' & Son: ' + data[i].id);
       dadSon += ('Dad: ' + parent + ' & Son: ' + data[i].id);
     }

     printDadSon(data[i].children, data[i].id);

   }
 })(JSON.parse(data));

 printDadSon(data);