text:
Q: WebGL drawing 2D image with depth map to achieve pseudo-3D effect I'm learning WebGL, done that with the help of WebGLFundamentals page, which helped me pretty much to understand how buffers, shaders and all that stuff works.
But now I want to achieve a certain effect which I saw here: https://tympanus.net/Tutorials/HeatDistortionEffect/index3.html
  I know how to make the heat distortion effect, the effect I want to achieve is the DEPTH on the image. This demo has a tutorial but it doesnt really explain how to do it, it says I must have a grayscale map, in which the white parts are the closest ones and the black parts the farest. But I really cant understand how it works, here is my shader's code:
var vertexShaderText = [
     "attribute vec2 a_position;",
     "attribute vec2 a_texCoord;",
     "uniform vec2 u_resolution;",
     "varying vec2 v_texCoord;",
     "void main() {",
     "  vec2 zeroToOne = a_position / u_resolution;",
     "  vec2 zeroToTwo = zeroToOne * 2.0;",
     "  vec2 clipSpace = zeroToTwo - 1.0;",
     "  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);",
     "  v_texCoord = a_texCoord;",
     "}"
  ].join("\n")

  var fragShaderText = [
     "precision mediump float;",
     "uniform sampler2D u_image;",
     "uniform sampler2D u_depthMap;",
     "uniform vec2 mouse;",
     "varying vec2 v_texCoord;",
     "void main() {",
     "  float frequency=100.0;",
     "  float amplitude=0.010;",
     "  float distortion=sin(v_texCoord.y*frequency)*amplitude;",
     "  float map=texture2D(u_depthMap,v_texCoord).r;",
     "  vec4 color=texture2D(u_image,vec2(v_texCoord.x+distortion*map, v_texCoord.y));",
     "  gl_FragColor = color;",
     "}"
  ].join("\n")

What I want is when I move the mouse, the image would respond to the shader to distort like in the link I showed above. But I really have no idea on how to do it on the javascript part.
Thanks

A: Following the image processing tutorials from that same site shows how to load multiple images. The sample you linked to and the tutorial make it pretty clear how it works
First you need the original image

and you then apply a sine wave distortion.

"use strict";

function main() {
  // Get A WebGL context
  /** @type {HTMLCanvasElement} */
  const canvas = document.getElementById("canvas");
  const gl = canvas.getContext("webgl");
  if (!gl) {
    return;
  }

  let originalImage = { width: 1, height: 1 }; // replaced after loading
  const originalTexture = twgl.createTexture(gl, {
    src: "https://i.imgur.com/xKYRSwu.jpg", crossOrigin: '',
  }, (err, texture, source) => {
    originalImage = source;
  });

  // compile shaders, link program, lookup location
  const programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);

  // calls gl.createBuffer, gl.bindBuffer, gl.bufferData for a quad
  const bufferInfo = twgl.primitives.createXYQuadBufferInfo(gl);

  requestAnimationFrame(render);

  function render(time) {
    time *= 0.001;  // seconds

    twgl.resizeCanvasToDisplaySize(gl.canvas);

    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    gl.clearColor(0, 0, 0, 0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    gl.useProgram(programInfo.program);

    // calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
    twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);

    const canvasAspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
    const imageAspect = originalImage.width / originalImage.height;
    const mat = m3.scaling(imageAspect / canvasAspect, -1);

    // calls gl.activeTexture, gl.bindTexture, gl.uniformXXX
    twgl.setUniforms(programInfo, {
      u_matrix: mat,
      u_originalImage: originalTexture,
      u_distortionAmount: 0.003,  // .3%
      u_distortionRange: 100,
      u_time: time * 10,
    });

    // calls gl.drawArrays or gl.drawElements
    twgl.drawBufferInfo(gl, bufferInfo);

    requestAnimationFrame(render);
  }
}

main();
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<script src="https://twgljs.org/dist/3.x/twgl-full.min.js"></script>
<canvas id="canvas"></canvas>

<!-- vertex shader -->
<script id="vs" type="f">
attribute vec2 position;
attribute vec2 texcoord;

uniform mat3 u_matrix;

varying vec2 v_texcoord;

void main() {
   gl_Position = vec4((u_matrix * vec3(position, 1)).xy, 0, 1);
   v_texcoord = texcoord;
}
</script>
<!-- fragment shader -->
<script id="fs" type="x-shader/x-fragment">
precision mediump float;

uniform float u_time;
uniform float u_distortionAmount;
uniform float u_distortionRange;

// our textures
uniform sampler2D u_originalImage;

// the texcoords passed in from the vertex shader.
varying vec2 v_texcoord;

void main() {
   vec2 distortion = vec2(
      sin(u_time + v_texcoord.y * u_distortionRange), 0) * u_distortionAmount;
   vec4 original = texture2D(u_originalImage, v_texcoord + distortion);
   gl_FragColor = original;
}
</script>
<script src="https://webglfundamentals.org/webgl/resources/m3.js"></script>

Then they also load a texture of multiple maps. This texture was created by hand in photoshop (or other image editing program). The green channel is how much to multiply the distortion by. The greener the more distortion.

"use strict";

function main() {
  // Get A WebGL context
  /** @type {HTMLCanvasElement} */
  const canvas = document.getElementById("canvas");
  const gl = canvas.getContext("webgl");
  if (!gl) {
    return;
  }

  let originalImage = { width: 1, height: 1 }; // replaced after loading
  const originalTexture = twgl.createTexture(gl, {
    src: "https://i.imgur.com/xKYRSwu.jpg",
    crossOrigin: '',
  }, (err, texture, source) => {
    originalImage = source;
  });

  const mapTexture = twgl.createTexture(gl, {
    src: "https://i.imgur.com/W9QazjL.jpg", crossOrigin: '',
  });

  // compile shaders, link program, lookup location
  const programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);

  // calls gl.createBuffer, gl.bindBuffer, gl.bufferData for a quad
  const bufferInfo = twgl.primitives.createXYQuadBufferInfo(gl);

  requestAnimationFrame(render);

  function render(time) {
    time *= 0.001;  // seconds

    twgl.resizeCanvasToDisplaySize(gl.canvas);

    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    gl.clearColor(0, 0, 0, 0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    gl.useProgram(programInfo.program);

    // calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
    twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);

    const canvasAspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
    const imageAspect = originalImage.width / originalImage.height;
    const mat = m3.scaling(imageAspect / canvasAspect, -1);

    // calls gl.activeTexture, gl.bindTexture, gl.uniformXXX
    twgl.setUniforms(programInfo, {
      u_matrix: mat,
      u_originalImage: originalTexture,
      u_mapImage: mapTexture,
      u_distortionAmount: 0.003,  // .3%
      u_distortionRange: 100,
      u_time: time * 10,
    });

    // calls gl.drawArrays or gl.drawElements
    twgl.drawBufferInfo(gl, bufferInfo);

    requestAnimationFrame(render);
  }
}

main();
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<canvas id="canvas"></canvas>

<script id="vs" type="f">
attribute vec2 position;
attribute vec2 texcoord;

uniform mat3 u_matrix;

varying vec2 v_texcoord;

void main() {
   gl_Position = vec4(u_matrix * vec3(position, 1), 1);
   v_texcoord = texcoord;
}
</script>
<script id="fs" type="f">
precision mediump float;

uniform float u_time;
uniform float u_distortionAmount;
uniform float u_distortionRange;

// our textures
uniform sampler2D u_originalImage;
uniform sampler2D u_mapImage;

// the texcoords passed in from the vertex shader.
varying vec2 v_texcoord;

void main() {
   vec4 depthDistortion = texture2D(u_mapImage, v_texcoord);
   float distortionMult = depthDistortion.g;  // just green channel

   vec2 distortion = vec2(
      sin(u_time + v_texcoord.y * u_distortionRange), 0) * u_distortionAmount;
   vec4 color0 = texture2D(u_originalImage, v_texcoord + distortion * distortionMult);
   gl_FragColor = color0;
}
</script>
<script src="https://twgljs.org/dist/3.x/twgl-full.min.js"></script>
<script src="https://webglfundamentals.org/webgl/resources/m3.js"></script>

Next there's an offset for the mouse multplied by another hand drawn map. This map is the red channel of the image above where the more red it is the more the mouse offset is applied. The map kind of represents depth. Since we need stuff in the front to move opposite of stuff in the back we need to convert that channel from 0 to 1 to -.5 to +.5 in the shader

"use strict";

function main() {
  // Get A WebGL context
  /** @type {HTMLCanvasElement} */
  const canvas = document.getElementById("canvas");
  const gl = canvas.getContext("webgl");
  if (!gl) {
    return;
  }

  let originalImage = { width: 1, height: 1 }; // replaced after loading
  const originalTexture = twgl.createTexture(gl, {
    src: "https://i.imgur.com/xKYRSwu.jpg",
    crossOrigin: '',
  }, (err, texture, source) => {
    originalImage = source;
  });

  const mapTexture = twgl.createTexture(gl, {
    src: "https://i.imgur.com/W9QazjL.jpg", crossOrigin: '',
  });

  // compile shaders, link program, lookup location
  const programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);

  // calls gl.createBuffer, gl.bindBuffer, gl.bufferData for a quad
  const bufferInfo = twgl.primitives.createXYQuadBufferInfo(gl);

  const mouse = [0, 0];
  document.addEventListener('mousemove', (event) => {
    mouse[0] = (event.clientX / gl.canvas.clientWidth  * 2 - 1) * 0.05;
    mouse[1] = (event.clientY / gl.canvas.clientHeight * 2 - 1) * 0.05;
  });

  requestAnimationFrame(render);

  function render(time) {
    time *= 0.001;  // seconds

    twgl.resizeCanvasToDisplaySize(gl.canvas);

    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    gl.clearColor(0, 0, 0, 0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    gl.useProgram(programInfo.program);

    // calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
    twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);

    const canvasAspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
    const imageAspect = originalImage.width / originalImage.height;
    const mat = m3.scaling(imageAspect / canvasAspect, -1);

    // calls gl.activeTexture, gl.bindTexture, gl.uniformXXX
    twgl.setUniforms(programInfo, {
      u_matrix: mat,
      u_originalImage: originalTexture,
      u_mapImage: mapTexture,
      u_distortionAmount: 0.003,  // .3%
      u_distortionRange: 100,
      u_time: time * 10,
      u_mouse: mouse,
    });

    // calls gl.drawArrays or gl.drawElements
    twgl.drawBufferInfo(gl, bufferInfo);

    requestAnimationFrame(render);
  }
}

main();
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<canvas id="canvas"></canvas>

<!-- vertex shader -->
<script id="vs" type="f">
attribute vec2 position;
attribute vec2 texcoord;

uniform mat3 u_matrix;

varying vec2 v_texcoord;

void main() {
   gl_Position = vec4(u_matrix * vec3(position, 1), 1);
   v_texcoord = texcoord;
}
</script>
<!-- fragment shader -->
<script id="fs" type="f">
precision mediump float;

uniform float u_time;
uniform float u_distortionAmount;
uniform float u_distortionRange;
uniform vec2 u_mouse;

// our textures
uniform sampler2D u_originalImage;
uniform sampler2D u_mapImage;

// the texcoords passed in from the vertex shader.
varying vec2 v_texcoord;

void main() {
   vec4 depthDistortion = texture2D(u_mapImage, v_texcoord);
   float distortionMult = depthDistortion.g;     // just green channel
   float parallaxMult = 0.5 - depthDistortion.r; // just red channel

   vec2 distortion = vec2(
      sin(u_time + v_texcoord.y * u_distortionRange), 0) * u_distortionAmount  * distortionMult;
   vec2 parallax = u_mouse * parallaxMult;

   vec4 color0 = texture2D(u_originalImage, v_texcoord + distortion + parallax);
   gl_FragColor = color0;
}
</script>
<script src="https://twgljs.org/dist/3.x/twgl-full.min.js"></script>
<script src="https://webglfundamentals.org/webgl/resources/m3.js"></script>

Finally, (not in the tutorial but in the sample) it loads a blurred version of the original image (blurred in some image editing program like photoshop)

It might be hard to see it's blurred since the blurring is subtle.
The sample then uses the blurred image the more distorted things are

"use strict";

function main() {
  // Get A WebGL context
  /** @type {HTMLCanvasElement} */
  const canvas = document.getElementById("canvas");
  const gl = canvas.getContext("webgl");
  if (!gl) {
    return;
  }

  let originalImage = { width: 1, height: 1 }; // replaced after loading
  const originalTexture = twgl.createTexture(gl, {
    src: "https://i.imgur.com/xKYRSwu.jpg",
    crossOrigin: '',
  }, (err, texture, source) => {
    originalImage = source;
  });

  const mapTexture = twgl.createTexture(gl, {
    src: "https://i.imgur.com/W9QazjL.jpg", crossOrigin: '',
  });

  const blurredTexture = twgl.createTexture(gl, {
    src: "https://i.imgur.com/Zw7mMLX.jpg", crossOrigin: '',
  });

  // compile shaders, link program, lookup location
  const programInfo = twgl.createProgramInfo(gl, ["vs", "fs"]);

  // calls gl.createBuffer, gl.bindBuffer, gl.bufferData for a quad
  const bufferInfo = twgl.primitives.createXYQuadBufferInfo(gl);

  const mouse = [0, 0];
  document.addEventListener('mousemove', (event) => {
    mouse[0] = (event.clientX / gl.canvas.clientWidth  * 2 - 1) * 0.05;
    mouse[1] = (event.clientY / gl.canvas.clientHeight * 2 - 1) * 0.05;
  });

  requestAnimationFrame(render);

  function render(time) {
    time *= 0.001;  // seconds

    twgl.resizeCanvasToDisplaySize(gl.canvas);

    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    gl.clearColor(0, 0, 0, 0);
    gl.clear(gl.COLOR_BUFFER_BIT);

    gl.useProgram(programInfo.program);

    // calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
    twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);

    const canvasAspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
    const imageAspect = originalImage.width / originalImage.height;
    const mat = m3.scaling(imageAspect / canvasAspect, -1);

    // calls gl.activeTexture, gl.bindTexture, gl.uniformXXX
    twgl.setUniforms(programInfo, {
      u_matrix: mat,
      u_originalImage: originalTexture,
      u_mapImage: mapTexture,
      u_blurredImage: blurredTexture,
      u_distortionAmount: 0.003,  // .3%
      u_distortionRange: 100,
      u_time: time * 10,
      u_mouse: mouse,
    });

    // calls gl.drawArrays or gl.drawElements
    twgl.drawBufferInfo(gl, bufferInfo);

    requestAnimationFrame(render);
  }
}

main();
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<canvas id="canvas"></canvas>

<!-- vertex shader -->
<script id="vs" type="f">
attribute vec2 position;
attribute vec2 texcoord;

uniform mat3 u_matrix;

varying vec2 v_texcoord;

void main() {
   gl_Position = vec4(u_matrix * vec3(position, 1), 1);
   v_texcoord = texcoord;
}
</script>
<!-- fragment shader -->
<script id="fs" type="f">
precision mediump float;

uniform float u_time;
uniform float u_distortionAmount;
uniform float u_distortionRange;
uniform vec2 u_mouse;

// our textures
uniform sampler2D u_originalImage;
uniform sampler2D u_blurredImage;
uniform sampler2D u_mapImage;

// the texcoords passed in from the vertex shader.
varying vec2 v_texcoord;

void main() {
   vec4 depthDistortion = texture2D(u_mapImage, v_texcoord);
   float distortionMult = depthDistortion.g;     // just green channel
   float parallaxMult = 0.5 - depthDistortion.r; // just red channel

   vec2 distortion = vec2(
      sin(u_time + v_texcoord.y * u_distortionRange), 0) * u_distortionAmount  * distortionMult;
   vec2 parallax = u_mouse * parallaxMult;

   vec2 uv = v_texcoord + distortion + parallax;
   vec4 original = texture2D(u_originalImage, uv);
   vec4 blurred = texture2D(u_blurredImage, uv);
   gl_FragColor = mix(original, blurred, length(distortion) / u_distortionAmount);
}
</script>
<script src="https://twgljs.org/dist/3.x/twgl-full.min.js"></script>
<script src="https://webglfundamentals.org/webgl/resources/m3.js"></script>

The finally big difference is rather than use a simple sine wave for distortion the shader on that sample is computing something slight more complicated.
cover
The code above uses a 2 unit quad that goes from -1 to +1 in X and Y. If you passed in an identiy matrix (or a 1,1 scale matrix which is the same thing) it would cover the canvas. Instead we want the image to not be distorted. To do that we had this code
const canvasAspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const imageAspect = originalImage.width / originalImage.height;
const mat = m3.scaling(imageAspect / canvasAspect, -1);

This just effectively says make it fill the canvas vertically and scale it in whatever it neesd to be to match the original image's aspect. The -1 is to flip the quad since otherwise the image is upside down.
To implement cover we just need to check if scale is < 1. If so it's not going to fill the canvas so we set the horizontal scale to 1 and adjust the vertical scale
// this assumes we want to fill vertically
let horizontalDrawAspect = imageAspect / canvasAspect;
let verticalDrawAspect = -1;
// does it fill horizontally?
if (horizontalDrawAspect < 1) {
  // no it does not so scale so we fill horizontally and
  // adjust vertical to match
  verticalDrawAspect /= horizontalDrawAspect;
  horizontalDrawAspect = 1;
}
const mat = m3.scaling(horizontalDrawAspect, verticalDrawAspect);


text:
Q: Using javascript on the new widget preview / customizer page Widget customizer has just become core in WordPress 3.9. I'm trying out the beta version hoping to get widgets working on the customize screen in the same way I have on the ordinary widgets page. Some of my widgets use javascript, like a select element transformed using a jQuery plugin - called tokenInput.
I need to be able to initialise the javascript on the new customizer screen where I can add / edit widgets.

*

*I can already initialise javascript on page load

*I can't reinitialise javascript on widget add, or on widget save.

So basically when I click on a widget to add it, or when I save it, I lose the jquery plugin and it goes back to a normal select element.
I solved this for the ordinary widgets page using something like this:
jQuery(document).ready(function() {

        // -------------------------------------------
        // On page load
        // -------------------------------------------
        input.tokenInput("/search-posts.php");

        // ---------------------------------------------
        // On new widget dropped in the sort area
        // ---------------------------------------------

        jQuery(".widgets-sortables").on("sortreceive", function(event, ui) {

            setTimeout(function() {

                jQuery("#widgets-right .select_news_post:not(.token)").each(function(){

                    var input = jQuery(this);
                    input.addClass('token');
                    select = input.next('select');

                    input.tokenInput("/search-posts.php");
                });
            }, 500)
        });

        // ---------------------------------------------
        // On widget save
        // ---------------------------------------------

        jQuery(document).ajaxSuccess(function(e, xhr, settings) {

            var widget_id_base = 'news-post';
            if (settings.data !== "undefined") {

                if (settings.data.search('action=save-widget') != - 1 && settings.data.search('id_base=' + widget_id_base) != - 1) {

                    // jQuery Tokeniser
                    jQuery("#widgets-right .select_news_post:not(.token)").each(function(){

                        var input = jQuery(this);
                        input.addClass('token');

                        input.tokenInput("/search-posts.php");
                    })
                }
            }
        }
}

Does anyone have any idea what I would use on the widget customizer page to make it reinitialise the javascript on add new widget and save widget?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass variable from JavaScript to Objective-C - JSON?
Possible Duplicate:
How pass a value from javascript to objective-C

I want to pass a text variable from JavaScript to an Objective-C variable.
My HTML file looks like this:

Bitte tragen Sie die Document ID ein:

<form action="">

      Document ID:
      <input name="DocumentID" type="text" size="30" maxlength="30" value="35060e6242160705744ffd8e280005b9">

      Formular:

        <input type="button" NAME ="button" value=" Absenden " onClick="testResults(this.form)">
        <input type="reset" value=" Abbrechen">

</form>

This is the Objective-C code:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    if([request.URL.relativeString isEqualToString:@"http://localhost:8888/"])
    //if([request.URL.relativeString rangeOfString:@"http://localhost:8888/"].location)
    {
        //self.URL
        [self loadData];

        return true;
    }
   return true;
}

Can somebody give me a hint? Thanks!

A: In javascript, make it so that the form submission sets a variable in javascript and then loads a dummy url.
You capture that url in Obj-C like you have done above and then call a function in javascript to return the variable.
NSString *script = [NSString stringWithFormat:@"myfunc('%@')", html];
NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:script];

So myfunc in javascript returns the form variable.


text:
Q: How to store username and password in one application and retrieve values in another application nativescript angular2 I just want to save user name and password in one nativescript application. Then in Second nativescript application, I have to retrieve the saved username and password.
I don't know how to achieve this in nativescript angular2. Any help is appreciated.thanks.

A: Try using LDAP server to store username and password .
Access these information in Webserver using any of server side languages using LDAP protocol .
Expose this functionality using known protocol like HTTP. Then Angular can access user information using any  REST Api call .

A: I know one way for passing secure data between application which might be helpful for now.
You can store the encrypted username and password in the local storage of the browser and than retrieve these encrypted username and password from local storage for further processing.
For encryption, you can use RSA-128 with timestamp.


text:
Q: How do I do an inverted LIKE query in NHibernate? I'm trying to run the following query with NHibernate without using Raw SQL.
SELECT *
FROM myTable
WHERE 'value1 value2 value3' like '%' + MyColumn + '%'

Is there any way to do it?
Thanks,

A: You can extend NHibernate's linq provider easily to have that support. Here's a tutorial about how you do it:
http://fabiomaulo.blogspot.com.tr/2010/07/nhibernate-linq-provider-extension.html


text:
Q: ng-options and unique filter not displaying angular.js In my javascript I have an array
$scope.quoteList =
    [
        {
            select: false,
            laymansDescription: "Nathan",
            quoteNumber: "ING-70440-21",
            version: "02",
            quoteDate: "Feb 5,2013",
            expirationDate: "Aug 5,2013",
            internalNotes: "This quote is using test data",
        },
        {
            select: false,
            laymansDescription: "Mitch",
            quoteNumber: "ING-70440-01",
            version: "02",
            quoteDate: "Feb 5,2013",
            expirationDate: "Aug 5,2013",
            internalNotes: "This quote is using test data",
        },
        {
            select: false,
            laymansDescription: "Stephen",
            quoteNumber: "ING-70440-01",
            version: "02",
            quoteDate: "Feb 5,2013",
            expirationDate: "Aug 5,2013",
            internalNotes: "This quote is using test data",
        }
    ];

And I am trying to make a selector that will only show unique quoteNumbers ie. ING-70440-21 and ING-70440-01. However when I try to use the 'unique' option in angular, nothing is showing up.
<select class="form-control" ng-options="quote.quoteNumber for quote in quoteList | unique:'quoteNumber'" ng-model="quoteModel1" />

It works fine without the unique tag. What am I doing wrong? I pretty new to angular so it might be something really simple.

A: You should check angular-filter module and use the uniqFilter
EXAMPLE:
JS:
function MainController ($scope) {
  $scope.orders = [
    { id:1, customer: { name: 'John',    id: 10 } },
    { id:2, customer: { name: 'William', id: 20 } },
    { id:3, customer: { name: 'John',    id: 10 } },
    { id:4, customer: { name: 'William', id: 20 } },
    { id:5, customer: { name: 'Clive',   id: 30 } }
  ];
}

HTML:
Customer list:

    {{ order.customer.name }} , {{ order.customer.id }}


text:
Q: Changing SQL Server2000 settings after converting to VM? We have migrated a SQL 2000 server to VM and I am wondering what changes will need to be made on the VM?
After the VM migration an SSIS package that transferred data from the 2000Server to a 2008Server will not connect. Nothing changed on the 2008Server but none the less the SSIS connection fails to authenticate. I can log in remotely from the 2008Server to the 2000Server using the credentials in the SSIS package.
So, is there anything that needs to be configured on the VM side that should be configured? I have checked services, account privileges, etc. The two servers can communicate, ports are open, osql -L and sqlcmd -L see the servers. Nothing on the VM server has changed from the physical server configuration wise.


text:
Q: Capture stdout to a string and output it back to stdout in C C language is used. I have a function that writes to stdout.
I would like to capture that output, modify it a bit (replacing some strings). And than output it again to the stdout. So I want to start with:
char huge_string_buf[MASSIVE_SIZE];
freopen("NUL", "a", stdout); -OR- freopen("/dev/null", "a", stdout);
setbuf(stdout, huge_string_buffer);
/* modify huge_string_buffer */

The question is now, how do I output the huge_string_buffer back to the original stdout?

A: One idea is to mimic the functionality of the standard Unix utility tee, but to do so entirely within your program, without relying on outside redirection.
So I've written a simple function, mytee(), which seems to work. It uses shmget(), pipe(), fork(), and dup2():
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/shm.h>

static char *mytee(int size) {
   int shmid = shmget(IPC_PRIVATE, size + 1, 0660 | IPC_CREAT);
   int pipe_fds[2];
   pipe(pipe_fds);

   switch (fork()) {
      case -1:                      // = error
         perror("fork");
         exit(EXIT_FAILURE);
      case 0: {                     // = child
         char *out = shmat(shmid, 0, 0), c;
         int i = 0;
         out[0] = 0;
         dup2(pipe_fds[0], 0);      // redirect pipe to child's stdin
         setvbuf(stdout, 0, _IONBF, 0);
         while (read(0, &c, 1) == 1 && i < size) {
            printf("<%c>", c);      // pass parent's stdout to real stdout,
            out[i++] = c;           // and then buffer in mycapture buffer
            out[i] = 0;             // (the extra <> are just for clarity)
         }
         _exit(EXIT_SUCCESS);
      }
      default:                      // = parent
         dup2(pipe_fds[1], 1);      // replace stdout with output to child
         setvbuf(stdout, 0, _IONBF, 0);
         return shmat(shmid, 0, 0); // return the child's capture buffer
   }
}

My test program is:
int main(void) {
   char *mycapture = mytee(100);    // capture first 100 bytes
   printf("Hello World");           // sample test string
   sleep(1);
   fprintf(stderr, "\nCaptured: <%s>\n", mycapture);
   return 0;
}

The output is:

<H><e><l><l><o>< ><W><o><r><l><d>
Captured: <Hello World>

To use this in your application, in mytee() you'll need to replace the test statement printf("<%c>", c) with just write(1, &c, 1).  And you may need to handle signals in the call to read. And after each of the two dup2()'s, you may want to add:
  close(pipe_fds[0]);
  close(pipe_fds[1]);

For a reference on this sort of stuff, see for example the excellent and short 27-year-old 220-page O'Reilly book Using C on the Unix System by Dave Curry.

A: The Unix way to do this is really to just write a little program that does the input processing you need, and then pipe the output of that other program to it on the command line.
If you insist on keeping it all in your C program, what I'd do instead is rewrite that function to have it send its output to a given char buffer (preferably returning the buffer's char *), so that it can be sent to stdout or processed as the client desires.
For example, the old way:
void usage () {
    printf ("usage: frob sourcefile [-options]\n");
}

...and the new way:
char * usage(char * buffer) {
    strcpy (buffer, "usage: frob sourcefile [-options]\n");
    return buffer;
}

A: I really don't like tricky games with file descriptors.  Can't you modify the function so that it returns its data some other way than by writing to stdout?
If you don't have access to the source code, and you can't do that, then I would suggest breaking out the code that writes to stdout into a small separate program, and run that as another process.  It is easy and clean to redirect output from a process (maybe through a named pipe), and then you will have no problem with outputting to stdout from the process that receives the data.
Also, depending on the sort of editing you wish to do, you might be better off using a high-level language like Python to edit the data.

A: char huge_string_buf[MASSIVE_SIZE];
FILE stdout_ori=fdopen(stdout,"a");
freopen("NUL", "a", stdout); -OR- freopen("/dev/null", "a", stdout);
setbuf(stdout, huge_string_buffer);
/* modify huge_string_buffer */
//Write to stdout_fdopen

A: If you are on a unix system, you can use pipes (you don't need to use fork). I'll try to thoroughly comment the code below so it doesn't look like I am doing any "magic."
#include <stdio.h>
#include <unistd.h>

int main()
{
    // Flush stdout first if you've previously printed something
    fflush(stdout);

    // Save stdout so it can be restored later
    int temp_stdout;
    temp_stdout = dup(fileno(stdout));

    // Redirect stdout to a new pipe
    int pipes[2];
    pipe(pipes);
    dup2(pipes[1], fileno(stdout));

    // Do whatever here. stdout will be captured.
    func_that_prints_something();

    // Terminate captured output with a zero
    write(pipes[1], "", 1);

    // Restore stdout
    fflush(stdout);
    dup2(temp_stdout, fileno(stdout));

    // Print the captured output
    while (1)
    {
        char c;
        read(pipes[0], &c, 1);

        if (c == 0)
            break;

        putc(c, stdout);
    }

    // Alternatively, because the output is zero terminated, you could
    // print using printf. You just need to make sure you read enough
    // from the captured output
    const int buffer_size = 1024;
    char buffer[buffer_size];
    read(pipes[0], buffer, buffer_size);
    printf(buffer);

    return 0;
}


text:
Q: FindByIdentity failing with PricipalOperationException in ASP.NET webapp I'm struggling with an issue in utilizing System.DirectoryServices.AccountManagement in my internal web application. The error is not very descriptive, but here's what's going on:
When I attempt to validate that a provided user id exists in the AD, I do so with the following code:
private bool IsWindowsIDValid(string strWindowsID)
{
var context = new PrincipalContext(ContextType.Domain, "DOMAINSERVER", "DC=DOMAINNAME,DC=net");
var userPrincipal = UserPrincipal.FindByIdentity(context, strWindowsID);
return (userPrincipal != null);
}

However, an exception is throw at the second line, where FindByIdentity is called. Here are the exception details:
Message:
"An operations error occurred."
Stack trace:
at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, String identityValue)
at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue)
at *****.IsWindowsIDValid(String strWindowsID) in *****.ascx.cs:line 193
This same error occurs if I attempt to examine the ConnectedServer property of the PrincipalContext as well. However, I can attempt to validate credentials against the context (using context.ValidateCredentials()), and it will pass just fine.
Any ideas as to what may be going on? I can run this code just fine in a stand alone console script on my machine - this is occurring in my local development environment, inside VisualStudio, when I attempt to debug the webapp. Is this a permissions issue or something else perhaps? I'm pretty lost at this point.
I appreciate any help!
-Patrick

A: An old question, but I had this same error.  For me, the problem is that PrincipalContext doesn't work without a username and password in its constructor... I get the exact same error message whenever I call any method or property of the UserPrincipal (or on the PrincipalContext for that matter).
If you specify a username and password of a domain user with Active Directory permissions to the container you're specifying, the call to FindByIdentity should succeed:
var context = new PrincipalContext(ContextType.Domain, "DOMAINSERVER",
                                   "DC=DOMAINNAME,DC=net", userName, pw);
var userPrincipal = UserPrincipal.FindByIdentity(context, strWindowsID);

For me, this isn't a solution, because I won't have those two parameters.  But that's why you're getting the error you're getting.
According to Microsoft's help, doing it your way should run under the credentials of the calling process... but no matter who I'm running under (and I've verified the impersonation) calls to a UserPrincipal object without specifying a username and pw on its PrincipalContext just won't work.
Hope that belatedly helps,
James

A: Another belated answer to an old question but, this article helped me troubleshoot it in my case:  http://support.microsoft.com/kb/329986
I was getting the "operations error" similar to the one in this post.
The clue was the suggestion to test it outside your web app.  So I created a console app, added a reference to System.DirectoryServices.AccountManagement, and entered the following code:
private static void Main(string[] args)
    {

        var adGroups = new List<string>();

        using (var principalContext = new PrincipalContext(ContextType.Domain))
        {
            using (var user = UserPrincipal.FindByIdentity(principalContext, @"MYDOMAIN\MYUSERNAME"))
            {
                if (user == null) return;

                var groups = user.GetAuthorizationGroups();
                adGroups.AddRange(from @group in groups
                                  where @group.Name.ToUpper().Contains("SOME-STRING-COMMON-TO-ALL-THE-AD-GROUPS-PERTINENT-TO-MY-MVC-APP")
                                  select @group.Name);
            }
        }
    }

That worked, so I was then convinced my problem was the "double hop" issue described in the MS article.
The solution was to ensure impersonation was turned on in my web.config file.  (It's an intranet app, so I've got Windows authentication mode turned on, and impersonation turned on; that solved it).
<system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="true" targetFramework="4.5" />
    <authentication mode="Windows" />
    <identity impersonate="true" />
    <authorization>
            <deny users="?" />
    </authorization>


text:
Q: How to convert Chinese punctuation into English for the list elements? I tried to check the Unicode but, doesn't work properly.
Then I tried to remove punctuation so, I can merge them at the end.
def remove_punctuations(text):
    for punctuation in string.punctuation:
    text = str(text).replace(punctuation, '')
    return textlst_1  =lst_1.apply(remove_punctuations)

lst_1= lst1.str.replace(r'[^\x00-\x7F]+', '')
lst_1 = ['SRS ????','NAT ????', 'Ins ??','SRS 檢視試針',
   'NAT 酒精清洗', 'Ins 目測']


text:
Q: Form2 changes does not reflect the changes in Form1 I have a problem with datagridview.
Form 1 : populating data with datagridview ...(when i click on the datagrid view row the corresponding row values are transferred to another form)
Form 2 : i have text buttons with save button
when i click on the datagrid view row the values are transferred to another form this is working fine.....
in form 2 i have done some changes with that data but this changes does not reflect in the form 1 datagrid view ...
How can i solve this problem.....

A: To answer this question we have to know how you are passing the values of the selected GridRow to the controls of the other form.
if your grid is bound to a dataset/datatable for example, once you select a row in the UI and another form is shown with the fields of that DataGridRow being exploded into different controls, what objects do you pass to the other form?
I would for example pass the DataRow linked to the selected row in the grid, this way in the second form you still have a reference to the datarow and when somebody changes a value in the textbox ( for example ) you could manually update the datarow column's value with the new value entered by the user.
in this way if in the previous form you refresh the grid you will see the changes.
Please note this can be done in many different ways and I would not probably use exactly this approach if I could write the whole logic from scratch, but you are telling too little so can't suggest anything more for now.

A: There are few options for you. Passing the Form1 instance to the Form2 and refresh the Form1 DataGridView dataSource from Form2 is one option.
For example. Form2 constructor can be like below
Form1 myForm1;

public Form2(Form1 form1)
{
    myForm1 = form1;
}

private void SaveButtonClicked()
{
    //Refresh the Form1.DataGridView DataSource.
}

Method2
You can call a method to refresh the Form1 DataGridView in Form1 by creating an event in Form2.

A: If you are showing Form2 using ShowDialog() method then this call will pause Form1 until Form2 is NOT closed.
This is the simplest approach. E.g.
Form1 {
    UpdateRowMethod() {
      DataRow Row = GetSelectedRow()
      Form2 frm;
      frm = new Form2(Row.Field1, Row.Field2, Row.Field3)
      if frm.ShowDialog() = OK {
         Row.Field1 = frm.Property1
         Row.Field2 = frm.Property2
         Row.Field3 = frm.Property3
         DataGridView1.InvalidateSelectedRow()
      }
   }
}

And as you can see Form2 is accepting the Field Values of Row as parameters of its constructor. And Form2 is returning back the updated data through its properties.
And If you are using Show() method then you need to implement events/delegates in order to notify Form1 that data has been changed.

A: Create a BindingSource in Form1, use that to fill DataGridView in Form1. Pass the BindingSource to Form2, before invoking it. All your changes will get automatically wired in/out. You will not need to expose any property in Form2 other than the BindingSouce Property (if you don't want to pass it through its Constructor).


text:
Q: Configuring Warden for use in RSpec controller specs I was able to use Devise's sign_in method to log in a user in my controller specs. But now that I'm removing Devise from my application, I'm not quite sure how to get similar functionality working with just Warden on its own.
How should I go about setting up spec/spec_helper.rb and related spec/support/*.rb files to get Warden running within controller specs sufficiently?
I've tried setting up a file at spec/support/warden.rb with these contents:
RSpec.configure do |config|
  config.include Warden::Test::Helpers

  config.after do
    Warden.test_reset!
  end
end

Then I have before calls similar to this to authenticate a user factory:
before { login_as FactoryGirl.create(:user) }

But here is the error that I keep seeing:
NameError:
  undefined method `user' for nil:NilClass

This error traces back to my authenticate_user! method in the controller:
def authenticate_user!
  redirect_to login_path, notice: "You need to sign in or sign up before continuing." if env['warden'].user.nil?
end

I'd appreciate any guidance that anyone could provide.

A: I didn't think that this question applied to my situation, but it does: Stubbing Warden on Controller Tests
As it turns out, Warden does not get included into RSpec controller specs, so you need to do some magic to finagle it in.
Kentaro Imai's Controller test helpers for Warden blog post was particularly helpful. Here's how I got it working for RSpec.
Step 1: Create spec/spec_helper/warden.rb and paste in these contents, which Kentaro derived from Devise:
module Warden
  # Warden::Test::ControllerHelpers provides a facility to test controllers in isolation
  # Most of the code was extracted from Devise's Devise::TestHelpers.
  module Test
    module ControllerHelpers
      def self.included(base)
        base.class_eval do
          setup :setup_controller_for_warden, :warden if respond_to?(:setup)
        end
      end

      # Override process to consider warden.
      def process(*)
        # Make sure we always return @response, a la ActionController::TestCase::Behavior#process, even if warden interrupts
        _catch_warden {super} || @response
      end

      # We need to setup the environment variables and the response in the controller
      def setup_controller_for_warden
        @request.env['action_controller.instance'] = @controller
      end

      # Quick access to Warden::Proxy.
      def warden
        @warden ||= begin
          manager = Warden::Manager.new(nil, &Rails.application.config.middleware.detect{|m| m.name == 'Warden::Manager'}.block)
          @request.env['warden'] = Warden::Proxy.new(@request.env, manager)
        end
      end

      protected

      # Catch warden continuations and handle like the middleware would.
      # Returns nil when interrupted, otherwise the normal result of the block.
      def _catch_warden(&block)
        result = catch(:warden, &block)

        if result.is_a?(Hash) && !warden.custom_failure? && !@controller.send(:performed?)
          result[:action] ||= :unauthenticated

          env = @controller.request.env
          env['PATH_INFO'] = "/#{result[:action]}"
          env['warden.options'] = result
          Warden::Manager._run_callbacks(:before_failure, env, result)

          status, headers, body = warden.config[:failure_app].call(env).to_a
          @controller.send :render, :status => status, :text => body,
            :content_type => headers['Content-Type'], :location => headers['Location']

          nil
        else
          result
        end
      end
    end
  end
end

Step 2: In spec/spec_helper.rb, within the RSpec.configure block, add this line to include the new module:
config.include Warden::Test::ControllerHelpers, type: :controller

Step 3: To log in a user in a before block, use syntax similar to this:
before { warden.set_user FactoryGirl.create(:user) }

Step 4: Make sure that you reference request.env['warden'] in your controllers, not env['warden']. The latter will not work in controller specs in the test environment.
Hat tip to Kentaro Imai, whom I owe a beer one day (or in another life)!

A: There is a basic problem with what you are trying to do. Warden is a Rack middleware, but RSpec controller specs don't even include Rack, as these types of specs are not meant to run your full application stack, but only your controller code. You can test your middleware with separate tests just for those, but in this case, I don't think it makes sense to test that Warden itself works.
To test that you have Warden configured correctly, you should use request specs or integration specs (cucumber, capybara or similar).
Although it is technically possible to mock out Warden in controller specs, I think it is not providing you much benefit while increasing the complexity of your test code significantly. Keep in mind that Rack middleware is meant to operate in a transparent way so that it is easy to swap middleware in and out as you like. Your controller should not be directly dependent on Warden at all (except perhaps for ApplicationController), actually, so having a test dependency on Warden for your controller is a sign of broken encapsulation.
I ran into this same issue recently so I hope this comment will be useful.


text:
Q: Jquery event seems to append data to variable within the callback function In a JQuery event (on click), I declare a variable inside that event and every time I hit the related event the data gets appended to the variable
$('select').on('blur', function () {
    let otherd = $('option:selected').text();
    if (otherd === 'Bank holidays' && otherd !== 'Sat' || otherd !== 'Sun') {
        nbrOfBankHolidays.push(1);
        console.log(otherd);
    }
 });

This is not an issue but I'm curious about the behavior because I wasn't expecting that it would work this way... i.e. every time I would hit that event I thought the variable would be reset with the new value and not appended to the previous value. It seems to stay in memory... I have a print screen of a debug where we see the actual result:
enter image description here

A: I recommend using the .val() of the selected <option> instead of the .text().


text:
Q: ¿Como inicio mi programa de java? Estoy empezando en java, y estoy intentando ejecutar un programa que imprima un texto. es este:
public class Test {
    public static void main(String[] args) {
        System.out.println("Yass");
    }
}

Pero me sale esto:

C:Users/miusuario/Desktop/miusuario/testing.java:1: error: class Test is public, should be declared in a file called Test.java

Pero ahí está el problema: No se como hacer el archivo Test.java para correr el codigo

A: Los archivos que contiene código Java, deben guardarse con el mismo nombre que el que declaras en su clase, de hecho eso es lo que te indica el error.
Entocnes tu archivo debe llamarse
Test.java

Asegurate de respetar el uso de mayúscula y minúsculas, posterior el código interno debe ser el mismo
public class Test {
    public static void main(String[] args) {
        System.out.println("Yass");
    }
}

Siempre debes tener presente que estes o no trabajando con un IDE
  tu archivo .java debe tener el mismo nombre que utilices para
  declarar tu clase


text:
Q: Does Rift Herald change Baron? Since the latest patch, they've introduced the 'Rift Herald' that spawns before Baron. I'm a support main so I'm rarely in top jungle, and usually the top lane takes it anyway. What exactly does killing it grant, and does it influence Baron at all? In addition, do whatever buffs it grants only apply to whoever kills it?

A: According to Rift Herald,

Slaying the Rift Herald grants the slayer the Doom's Eve buff.

The buff gives movement speed, increased damage, improved recall and the minion aura.
It's a tuned down Hand of Baron buff basically. Only the killer gets it and the bonuses are lessen (except movement speed which Baron does not provide).

A: Although some of these points are addressed in the other answer, the question leads me to think that he is wondering about the baron/rift herald interaction and possibly the interaction between the buffs granted, as it is possible to take baron while having rift herald buff, so I have compiled all info I can find on the Rift Herald.
As of patch 7.9,
After killing the Rift Herald, you may pick up the relic left behind, which will grant you the "Eye of the Void" which temporarily replaces their trinket.
This grants Empowered Recall when held, and allows for summoning of the Rift Herald after a 3.5 second charge time.
Note: Lasts for 4 minutes (or until used) and is retained even if slain, and can be held even if you have baron buff, though you do not get a doubly Empowered Recall.  Also, if Rift Herald has not been killed at 19:45 it will immediately return to the void(despawn) if not in combat. If in combat, it will despawn at 19:55 after it is killed, or despawns, it will not return for the rest of the game.


text:
Q: C# - Copy pasting of image into outlook set it as twice attachment files I am currently working on an addin project for outlook in visual studio 2013.
When I copy paste an image into outlook and send mail through it,it considers the same image twice in the html attachment.How can I allow to show only one image in the attachment? Or how can remove the second  attachment?
Copy Pasted one Image to outlook:

Outlool.MailItem.Attachments look like:

Got two Attachments when I pasted one Image.
Please help. Thanks

A: Instead, can you try to get a picture from the local? Just test the problem and see if there will be such a problem.
Also, I found a way to add attachments from locally saved files to the mail and display them in HTML to the body. For your reference:
newMail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
Outlook.Attachment attachment = newMail.Attachments.Add(@"path.imageformat", Outlook.OlAttachmentType.olEmbeddeditem, null, $"someTitle");
string imagecid = "whatever";
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3613041E", imagecid);
newMail.HTMLBody = String.Format("", imageCid);


text:
Q: Vue - Resource interpreted as Stylesheet but transferred with MIME type text/html I've deployed two Vue JS Apps on production (Apache2 server), one with lazy-load components and the other without lazy load.
When I try to directly open a different URL (route) from the base url / the project without lazy-load works fine, however, the app with lazy load don't work as expected, it shows this error on the console:
Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://my.exampleapp/css/app.e5de818b.css".

Resource interpreted as Stylesheet but transferred with MIME type text/html: "https://my.exampleapp/css/chunk-vendors.54e65764.css".

Generated HTML:
<link href=/css/app.e5de818b.css rel=preload as=style>
<link href=/css/chunk-vendors.54e65764.css rel=preload as=style>

Is there any configuration I need to add on apache2 or it is something to configure on my Vue App?


text:
Q: Calculating event / stimulus triggered averages efficiently in Python I would like to calculate event / stimulus triggered averages computationally efficient.
Assuming I have got a signal, e.g.
signal = [random.random() for i in xrange(0, 1000)]

with n_signal datapoints
n_signal = len(signal)

I know that this signal is sampled with a rate of
Fs = 25000 # Hz

In this case I know that the total time of the signal
T_sec = n_signal / float(Fs)

At specific times, certain events occur, e.g.
t_events = [0.01, 0.017, 0.018, 0.022, 0.034, 0.0345, 0.03456]

Now I would like to find the signal from a certain time before these events, e.g.
t_bef = 0.001

until a certain time after these events, e.g.
t_aft = 0.002

And once I have got all of these chunks of the signal, I would like to average these.
In the past I would have created the time vector of the signal
t_signal = numpy.linspace(0, T_sec, n_signal)

and looked for all of the indices for t_events in t_signal e.g. using numpy.serachsorted
(Link)
Since I know the sampling rate of the signal, these can be done much quicker, like
indices = [int(i * Fs) for i in t_events]

This saves me the memory for t_signal and I do not have to go through the whole signal to find my indices.
Next, I would determine how many data samples t_bef and t_aft are corresponding to
nsamples_t_bef = int(t_bef * Fs)
nsamples_t_aft = int(t_aft * Fs)

and I would save the signal chunks in a list
signal_chunks = list()
for i in xrange(0, len(t_events)):
    signal_chunks.append(signal[indices[i] - nsamples_t_bef : indices[i] + nsamples_t_aft])

And finally I am averaging these
event_triggered_average = numpy.mean(signal_chunks, axis = 0)

If I am interested in the time vector, I am calculating it with
t_event_triggered_average = numpy.linspace(-t_signal[nsamples_t_bef], t_signal[nsamples_t_aft], nsamples_t_bef + nsamples_t_aft)

Now my questions: Is there a computational more efficient way to do this? If I have got a signal with many data points and many events, this computation can take a while. Is a list the best data structure to save these chunks in? Do you know how to get the chunks of data quicker? Maybe using buffer?
Thanks in advance for your comments and advice.
Minimum working example
import numpy
import random

random.seed(0)
signal = [random.random() for i in xrange(0, 1000)]

# sampling rate
Fs = 25000 # Hz

# total time of the signal
n_signal = len(signal)
T_sec = n_signal / float(Fs)

# time of events of interest
t_events = [0.01, 0.017, 0.018, 0.022, 0.034, 0.0345, 0.03456]

# and their corresponding indices
indices = [int(i * Fs) for i in t_events]

# define the time window of interest around each event
t_bef = 0.001
t_aft = 0.002

# and the corresponding index offset
nsamples_t_bef = int(t_bef * Fs)
nsamples_t_aft = int(t_aft * Fs)

# vector of signal times
t_signal = numpy.linspace(0, T_sec, n_signal)

signal_chunks = list()
for i in xrange(0, len(t_events)):
    signal_chunks.append(signal[indices[i] - nsamples_t_bef : indices[i] + nsamples_t_aft])

# average signal value across chunks
event_triggered_average = numpy.mean(signal_chunks, axis = 0)

# not sure what's going on here
t_event_triggered_average = numpy.linspace(-t_signal[nsamples_t_bef],
                                            t_signal[nsamples_t_aft],
                                            nsamples_t_bef + nsamples_t_aft)

A: Since your signal is defined on a regular grid, you could do some arithmetic to find indices for all the samples that you require. Then you can construct the array with chunks using a single indexing operation.
import numpy as np

# Making some test data
n_signal = 1000
signal = np.random.rand(n_signal)
Fs = 25000 # Hz
t_events = np.array([0.01, 0.017, 0.018, 0.022, 0.034, 0.0345, 0.03456])

# Preferences
t_bef = 0.001
t_aft = 0.002

# The number of samples in a chunk
nsamples = int((t_bef+t_aft) * Fs)

# Create a vector from 0 up to nsamples
sample_idx = np.arange(nsamples)

# Calculate the index of the first sample for each chunk
# Require integers, because it will be used for indexing
start_idx = ((t_events - t_bef) * Fs).astype(int)

# Use broadcasting to create an array with indices
# Each row contains consecutive indices for each chunk
idx = start_idx[:, None] + sample_idx[None, :]

# Get all the chunks using fancy indexing
signal_chunks = signal[idx]

# Calculate the average like you did earlier
event_triggered_average = signal_chunks.mean(axis=0)

Note, the line with .astype(int) does not round to nearest integer, but rounds towards zero.


text:
Q: radio button in gridview template field I am making a exam web application in ASP.NET. I am using grid-view for showing question and the possible answers. I set size of grid view is 1 so it display only one question on a page-index. I am using radio button for multiple choice option.
When I select a radio button and going to next question or next page index of grid-view and come again previous question then I see that the radio button which I selected previously is not selected. What should I do for this?

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
                        AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1"
                        GridLines="None" Height="380px"
                        onpageindexchanging="GridView1_PageIndexChanging"
                        onprerender="GridView1_PreRender" onrowcommand="GridView1_RowCommand"
                        OnRowDataBound="GridView1_RowDataBound"
                        onselectedindexchanged="GridView1_SelectedIndexChanged" PageSize="1"
                        ShowHeader="False" style="margin-right: 0px; margin-bottom: 0px;"
                        Width="100%">
                        <Columns>
                            <asp:TemplateField>
                                <ItemTemplate>

                                                <asp:Label ID="Label14" runat="server" Font-Size="Large" Text="Question No :-"></asp:Label>
                                                <asp:Label ID="Label4" runat="server" Font-Bold="True" Font-Size="Large"
                                                    Text='<%# Eval("id") %>'></asp:Label>

                                                <asp:Label ID="Label15" runat="server" Font-Bold="True" Text="Question:-"
                                                    Font-Size="Large"></asp:Label>

      <asp:Label ID="Label6" runat="server" Font-Bold="False"
                                                    Text='<%# Eval("Question") %>'></asp:Label>

                                                A:-<asp:RadioButton ID="RadioButton1" runat="server" AutoPostBack="True"
                                                    Font-Bold="False"
                                                    oncheckedchanged="RadioButton1_CheckedChanged" Text='<%# Eval("A") %>' />

                                                <asp:Image ID="Image1" runat="server" BorderStyle="None" Height="149px"
                                                    ImageUrl='<%# Eval("image") %>' Width="449px" />

                                                B:-<asp:RadioButton ID="RadioButton2" runat="server" AutoPostBack="True"
                                                    Font-Bold="False"
                                                    oncheckedchanged="RadioButton2_CheckedChanged" Text='<%# Eval("B") %>' />

                                                C:-<asp:RadioButton ID="RadioButton3" runat="server" AutoPostBack="True"
                                                    Font-Bold="False"
                                                    oncheckedchanged="RadioButton3_CheckedChanged" Text='<%# Eval("C") %>' />

                                                D:-<asp:RadioButton ID="RadioButton4" runat="server" AutoPostBack="True"
                                                    Font-Bold="False"
                                                    oncheckedchanged="RadioButton4_CheckedChanged" Text='<%# Eval("D") %>' />

                                                <asp:Button ID="Button12" runat="server" BackColor="#006699" BorderStyle="None"
                                                    Font-Bold="True" Font-Size="Large" ForeColor="White" Height="34px"
                                                    Text="Next>>>" Width="230px" />
                                                 <asp:Button ID="Button2" runat="server" BackColor="#006699" BorderStyle="None"
                                                    CommandArgument='<%# Eval("id") %>' CommandName="Next" Font-Bold="True"
                                                    Font-Size="Large" ForeColor="White" Height="34px" Text="Mark for Review & Next"
                                                    Width="229px" />

                                                <asp:Button ID="Button1" runat="server" BackColor="#006699" BorderStyle="None"
                                                    CommandArgument='<%# Eval("id") %>' CommandName="Save" Font-Bold="True"
                                                    Font-Size="Large" ForeColor="White" Height="34px" OnClick="Button1_Click"
                                                    Text="Save and Next" Width="230px" />

                                </ItemTemplate>
                                <AlternatingItemTemplate>

                                                Q0 .
                                                abc

                                                   C:-<input
                                                    ID="GridView1_ctl02_RadioButton3" name="GridView1$ctl02$RadioButton3"
                                                    onclick="javascript:setTimeout('__doPostBack(\'GridView1$ctl02$RadioButton3\',\'\')', 0)"
                                                    type="radio" value="RadioButton3" />abc

                                                   A:-<input
                                                    ID="GridView1_ctl02_RadioButton1" name="GridView1$ctl02$RadioButton1"
                                                    onclick="javascript:setTimeout('__doPostBack(\'GridView1$ctl02$RadioButton1\',\'\')', 0)"
                                                    type="radio" value="RadioButton1" />abc

                                                   B:-<input
                                                    ID="GridView1_ctl02_RadioButton2" name="GridView1$ctl02$RadioButton2"
                                                    onclick="javascript:setTimeout('__doPostBack(\'GridView1$ctl02$RadioButton2\',\'\')', 0)"
                                                    type="radio" value="RadioButton2" />abc

                                                   D:-<input
                                                    ID="GridView1_ctl02_RadioButton3" name="GridView1$ctl02$RadioButton3"
                                                    onclick="javascript:setTimeout('__doPostBack(\'GridView1$ctl02$RadioButton3\',\'\')', 0)"
                                                    type="radio" value="RadioButton3" />abc

                                                <input ID="GridView1_ctl02_Button12" name="GridView1$ctl02$Button12"
                                                    style="color:White;background-color:#006699;border-style:None;font-size:Large;font-weight:bold;height:34px;width:230px;"
                                                    type="submit" value="<<<Prv" />  <input
                                                    ID="GridView1_ctl02_Button2" name="GridView1$ctl02$Button2"
                                                    style="color:White;background-color:#006699;border-style:None;font-size:Large;font-weight:bold;height:34px;width:229px;"
                                                    type="submit" value="Mark and Next" />

                                                <input ID="GridView1_ctl02_Button1" name="GridView1$ctl02$Button1"
                                                    style="color:White;background-color:#006699;border-style:None;font-size:Large;font-weight:bold;height:34px;width:230px;"
                                                    type="submit" value="Save and Next" />

                                </AlternatingItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <PagerStyle BackColor="White" BorderColor="White" ForeColor="White" />
                    </asp:GridView>

A: Save Answer in View-state using code
if (e.CommandName == "Save")
        {
 foreach (GridViewRow row in GridView1.Rows)
            {
            if (((RadioButton)row.FindControl("RadioButton1")).Checked)
            {

                Label12.Text = "A";

            }
            if (((RadioButton)row.FindControl("RadioButton2")).Checked)
            {

                Label12.Text = "B";

            }

            if (((RadioButton)row.FindControl("RadioButton3")).Checked)
            {

                Label12.Text = "C";

            }
            if (((RadioButton)row.FindControl("RadioButton4")).Checked)
            {

                Label12.Text = "D";

            }

string m = Convert.ToString(e.CommandArgument);
            ViewState[m] = Label12.Text;

}
Run a for Loop in Row Data Bound event of GridView1
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string id = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "id"));

        int i, j;
        for (i = 1; i <= 65; i++)
        {

            j = i + 100;
          string k = i.ToString();
            string l = j.ToString();

            if (ViewState[l] != null)
            {

                if (id == k)
                {

                    if (ViewState[l].ToString() == "A")
                    {

                        (e.Row.Cells[0].FindControl("RadioButton1") as RadioButton).Checked = true;
                    }
                    if (ViewState[l].ToString() == "B")
                    {

                        (e.Row.Cells[0].FindControl("RadioButton2") as RadioButton).Checked = true;
                    }

                    if (ViewState[l].ToString() == "C")
                    {

                        (e.Row.Cells[0].FindControl("RadioButton3") as RadioButton).Checked = true;
                    }
                    if (ViewState[l].ToString() == "D")
                    {

                        (e.Row.Cells[0].FindControl("RadioButton4") as RadioButton).Checked = true;
                    }

                }

            }
        }

    }
}

Solve !!!!!


text:
Q: Vimeo JavaScript API add event listener to all iframes on the page Been messing around with Froogaloop, Vimeo's JavaScript API, and am trying to add a class to the Vimeo iFrame that is currently playing. Seems simple enough, using the API's events, but I can't seem to wrap my head around it. Here's what I've got so far:
The code below is a simplified version of their example. While it's not causing any errors in my console, I'm not getting any of the logs (and therefore not getting the classes). Am I missing something?
Thanks for your help!
var iframe = $('article.video iframe')[0],
    player = $f(iframe);

player.addEvent('ready', function() {
    player.addEvent('play', on);
    player.addEvent('pause', off);
    player.addEvent('finish', off);
});

function on(id) {
    console.log('playing');
    player.addClass('playing');
}
function off(id) {
    console.log('not playing');
    player.removeClass('playing');
}

UPDATE

The issue definitely has to do with the variables. Player tells Froogaloop which iframe to work with, iframe identifies which html object that is. So I suppose the issue is how I can identify all the iframes on the page and then feed Froogaloop the appropriate iframe when one is activated.

A: Yes, as I see, in the on() and off() functions Froogaloop is giving you the ID of the iframe by parameter. So, in that case you should add and remove class like this:
$('#'+id).addClass('playing');

$('#'+id).removeClass('playing');

And in your HTML you should provide an id="videoX" to every iframe tag, plus to add &player_id=videoX at the end of the url address of the src property from the iframe.


text:
Q: Odd errors with connecting to AD - visual basic Have couple of odd issues. I connect to AD to get the list of active users and their groups and write it out into the table in SQL. Code is written in Visual Basic. Occasionally I would get an error "There is no such object on the server". But when I try to run the same process 5 min later - it goes fine. In other words I do not get that error each time I run the process, only occasionally.
The other part of the issue - if I try to extract data from the sql tables and create excel file with the report - right after running the process above
I'm getting the error:

System.AccessViolationException was unhandled
    HResult=-2147467261
    Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
    Source=System.Data
    StackTrace:
         at System.Data.OleDb.DataSourceWrapper.InitializeAndCreateSession(OleDbConnectionString constr, SessionWrapper& sessionWrapper)
         at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
         at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
         at System.Data.ProviderBase.DbConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)...

If I stop the processing, close out the windows app, re-open and run export to excel only - runs fine.
I thought that maybe memory was not released, but I do have commands in the end of processing that pulls data from AD:
dirEntry.Dispose()
dirEntry = Nothing

Is there special command to clear memory after connecting to AD? What can be causing those 2 sporadic errors? Thanks!
Per request - adding partial code.
- getting list of users and groups, then dispose dirEntry:
Public Sub ListAllADUsers(dirEntry As DirectoryEntry)
        Dim UserList As New Collection()
        Dim UsernameList As New Collection()
        Dim oresult As SearchResultCollection
    Dim dirSearcher As DirectorySearcher = New DirectorySearcher("(&(objectCategory=Person)(objectClass=user))")
    dirSearcher.SearchRoot = dirEntry
    dirSearcher.PropertiesToLoad.Add("SAMAccountName")
    dirSearcher.PropertiesToLoad.Add("givenname")
    dirSearcher.PropertiesToLoad.Add("cn")
    dirSearcher.ServerTimeLimit = New TimeSpan(0, 10, 0)
    dirSearcher.PageSize = 10000
    dirSearcher.ClientTimeout = TimeSpan.FromMinutes(12000)

    oresult = dirSearcher.FindAll()
    For Each result In oresult
        If Not result.GetDirectoryEntry.Properties("cn").Value Is Nothing Then
           UserList.Add(result.GetDirectoryEntry.Properties("cn").Value, result.GetDirectoryEntry.Properties("SAMAccountName").Value)
           GetGroupsAD(result.GetDirectoryEntry.Properties("SAMAccountName").Value.ToString(), result.GetDirectoryEntry.Properties("cn").Value.ToString())
            If StopFlag = 1 Then Exit Sub
        End If
    Next

    dirSearcher.Dispose()
End Sub

A: Well - resolved it. Had collections lists that I was going to use but decided not to. Once I commented it out - everything is working fine. Who knew it can mess up everything like that?? Closing. So if anyone would be using my code - just remove collections...


text:
Q: manage.py runserver 0.0.0.0:8000 ImportError No module named DBCONN I am running the manage.py runserver and getting an import error for "dbconn"  The file exists in the django project directory.  Here is the directory listing of my django project.  Also below this I have included my traceback.  If anyone has any ideas, I am learning django on the fly.
-rw-rw-r--. 1 cchadwick cchadwick 1230 Jun  1 12:30 chartcall.py
-rw-rw-r--. 1 cchadwick cchadwick 1651 Jun  1 12:24 dbconn.py
-rw-rw-r--. 1 cchadwick cchadwick    0 May 26 14:43 __init__.py
drwxrwxr-x. 2 cchadwick cchadwick  240 Jun  1 12:30 __pycache__
-rw-rw-r--. 1 cchadwick cchadwick 3569 Jun  1 11:58 settings.py
-rw-rw-r--. 1 cchadwick cchadwick  959 May 30 14:10 urls.py
-rw-rw-r--. 1 cchadwick cchadwick  181 May 31 15:04 views.py
-rw-rw-r--. 1 cchadwick cchadwick  396 May 26 14:43 wsgi.py

(dbenv) [cchadwick@opendev-cutco-com dashproj1]$ python manage.py runserver 0.0.0.0:8000

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f4d001ce488>
Traceback (most recent call last):
File "/home/cchadwick/dbenv/lib/python3.4/site-packages/django/utils   /autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/home/cchadwick/dbenv/lib/python3.4/site-packages/django /core/management/commands/runserver.py", line 117, in inner_run
autoreload.raise_last_exception()
File "/home/cchadwick/dbenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception
six.reraise(*_exception)
File "/home/cchadwick/dbenv/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/cchadwick/dbenv/lib/python3.4/site-packages/django/utils/autoreload.py", line 227, in wrapper
fn(*args, **kwargs)
File "/home/cchadwick/dbenv/lib/python3.4/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/cchadwick/dbenv/lib/python3.4/site-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/home/cchadwick/dbenv/lib/python3.4/site-packages/django/apps/config.py", line 94, in create
module = import_module(entry)
File "/home/cchadwick/dbenv/lib64/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2224, in _find_and_load_unlocked
ImportError: No module named 'dbconn'

Here is the code for the dbconn file.
import pyodbc

def db2conn():
    conn = pyodbc.connect(
    driver='{iSeries Access ODBC Driver}',
    system="0.0.0.0",
    uid='USER',
    pwd='PASS')

    c1 = conn.cursor()
    return c1, conn

This is the chartcall.py
#import numpy as np
from bokeh.plotting import figure
from bokeh.io import output_file, save, show
from time import sleep
from pandas import DataFrame, read_sql_query, to_numeric, options,    set_eng_float_format, formats
from geopy import Nominatim, geocoders
from geopy.exc import GeocoderTimedOut
import gmplot
import geocoder
from bokeh.models import (Range1d, PanTool, ResetTool, HoverTool,   ColumnDataSource, LabelSet,
                      GMapPlot, GMapOptions, DataRange1d, PanTool, WheelZoomTool, BoxSelectTool, Circle)
#from django.db import Connection
# import matplotlib.pyplot as plt
#from tkinter import *
#import dbconn

c1, conn = db2conn()

def orders_by_day():
    sql = """ Select count(doord#) total_ords, sum(dolin1) total_lin1   from dmfiles.dmordm0
              join dmfiles.bncchan0 on dootyp = ordertype
              and doomtd = ordermethod
              where
              doocat = 'ORD' and doco# = '00004' and channel = 'Catalog'
              and doshpd between current_date - 1 days and current_date

             """

     x = []

     y = []
     i = 0
     c1.execute(sql)
     for row in c1.execute(sql):
        x.append(row[0])
        y.append(row[1])

     return x, y


text:
Q: When rendering using GL_QUADS in OpenGL part of the shape is missing I am trying to render a square, using GL_QUADS, but every time it renders it has a triangle missing form
Here is the code I have:
gl.glPushMatrix();
gl.glBegin(GL.GL_QUADS);
gl.glVertex3d(pts2d.get(0).x, extra[0],pts2d.get(0).y);
gl.glVertex3d(pts2d.get(1).x,extra[0],pts2d.get(1).y);
gl.glVertex3d(pts2d.get(0).x, portalHeight,pts2d.get(0).y);
gl.glVertex3d(pts2d.get(1).x,portalHeight,pts2d.get(1).y);
gl.glEnd();
gl.glPopMatrix();

I am using JOGL, and the points are the correct points to create a square, I just don't know why there is a triangle cut out.

A: Note that OpenGL's ordering for quads is not the same ordering as for an equivalent triangle-strip. Here's what I mean.
Four vertices that make up a triangle strip for a quad are specified in this order:
0 2
1 3

Quads are specified in this order:
0 3
1 2

See the difference? It's counter-clockwise (or clockwise, depending on your winding order) around the quad's face. It's not top-to-bottom, left-to-right.


text:
Q: Asymptotically nonexpansive mapping that is not nonexpansive Let $C$ be a nonempty subset of a Banach space $X$. A mapping $T:C\to C$  is said to be asymptotically nonexpansive mappings if for all $n\in \mathbf{N},$ there exists a positive constant $k_n\geq1$ such that $\lim\limits_{n\to \infty}k_n=1$ $$\|T^nx-T^ny\|\leq k_n\|x-y\| \ \ \ \text{for all}x, y\in C.$$
Question
I think if $T$ be a nonexpansive mappings ($\|Tx-Ty\|\leq \|x-y\|$) then it will be asymptotically nonexpansive mappings. But I cannot prove that there is an asymptotically nonexpansive mappings, but not nonexpansive.


text:
Q: How to use fitBounds in react-google-map once you have bounds Where exactly do I call fitBounds or map.fitbounds. I am confused where to put it once I have the bounds or how to use it. I have set the bounds to a local state of bounds.
I have looked at this post here react-google-maps: how to use fitBounds, panBy, panTo, panToBounds public APIs? and either I just do it different or something because it does not make much since to me.
I have created a bounds const and then each time I make a marker I have added each of those to the bounds doing bounds.extends(Marker in here)
The code is a little messy so I will point out where I do this in it. Inside the filterItemsByRadius is where I create and set the bounds. At the end of the map function I think set the state of bounds to the bounds.
/* global google */
import { default as React, Component } from 'react';
import raf from 'raf';
import canUseDOM from 'can-use-dom';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import {
  withGoogleMap,
  GoogleMap,
  Circle,
  InfoWindow,
  Marker,
  withScriptjs,
} from 'react-google-maps';
import geolib from 'geolib';
import { geolocated } from 'react-geolocated';
import ItemList from './ItemList';
import { Col } from 'react-bootstrap';

import Paper from 'material-ui/Paper';
import Img from 'react-image';
import RaisedButton from 'material-ui/RaisedButton';
import FontIcon from 'material-ui/FontIcon';
import CreateRadius from './CreateRadius';
import offerActions from '../../redux/actions/offerActions';

const googleMapURL =
  'https://maps.googleapis.com/maps/api/js?libraries=places,geometry&key=AIzaSyA7XEFRxE4Lm28tAh44M_568fCLOP_On3k';

const isJson = str => {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
};

const GeolocationGoogleMap = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap defaultZoom={6} zoom={props.zoom} center={props.center} onClick={props.onMapClick}>
      {props.center && (
        <Marker
          position={props.center}
          title={"User's Location"}
          options={{ icon: require('./assets/blueDot.png') }}
        >
          {props.showCenterInfo && (
            <InfoWindow>

User's Location

            </InfoWindow>
          )}
        </Marker>
      )}
      {/* <Circle
          center={props.center}
          radius={props.zoom}
          options={{
            fillColor: 'red',
            fillOpacity: 0.2,
            strokeColor: 'red',
            strokeOpacity: 1,
            strokeWeight: 1,
          }}
        /> */}
      {props.markers.map((marker, index) => {
        const onClick = () => props.onMarkerClick(marker);
        const onCloseClick = () => props.onCloseClick(marker);

        return (
          <Marker
            key={index}
            position={marker.position}
            title={marker.number.toString()}
            onClick={onClick}
            options={{ icon: 'https://image.ibb.co/evMHxF/shopping_zone_marker_1.png' }}
          >
            {marker.showInfo && (
              <InfoWindow onCloseClick={onCloseClick}>

                  <ItemList marker={marker} />

              </InfoWindow>
            )}
          </Marker>
        );
      })}
    </GoogleMap>
  )),
);

class OfferMap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPosition: null,
      center: null,
      content: null,
      radius: 15, // ACZ --> put this const in config_env.
      showCenterInfo: true,
      markers: [],
      zoom: 6,
      bounds: null,
    };

    this.handleMarkerClick = this.handleMarkerClick.bind(this);
    this.handleCloseClick = this.handleCloseClick.bind(this);
    this.handleMapClick = this.handleMapClick.bind(this);
    this.filterItemsByRadius = this.filterItemsByRadius.bind(this);
    this.radiusChange = this.radiusChange.bind(this);
    this.zoomChange = this.zoomChange.bind(this);
  }

  componentWillReceiveProps(props) {
    if (props.coords && !props.coords.positionError) {
      this.setState({ center: { lat: props.coords.latitude, lng: props.coords.longitude } });
    } else {
      fetch('http://ip-api.com/json')
        .then(res => res.json())
        .then(data => {
          this.setState({ center: { lat: data.lat, lng: data.lon } });
        })
        .catch(error => {
          this.setState({ content: `Error: The Geolocation service failed (${error.message}).` });
        });
    }
    this.setState({ markers: props.items });
  }

  handleMapClick() {
    this.setState({ showCenterInfo: false });
  }

  handleMarkerClick(targetMarker) {
    this.setState({
      markers: this.state.markers.map(marker => {
        if (marker._id === targetMarker._id) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
    });
  }

  handleCloseClick(targetMarker) {
    this.setState({
      markers: this.state.markers.map(marker => {
        if (marker._id === targetMarker._id) {
          return {
            ...marker,
            showInfo: false,
          };
        }
        return marker;
      }),
    });
  }

  filterItemsByRadius(userRadius) {
    const items = this.state.markers;
    const markers = [];
    const bounds = new google.maps.LatLngBounds();

    items.map((item, i) => {
      let itemGeolocation;
      let itemDescription = 'NO DESCRIPTION';
      let itemThumb;
      // Should be ready - tbaustinedit
      if (item) {
        itemDescription = item.description;
        itemThumb = item.media.mediaVault[item.media.defaultIdx] || {
          mediaType: 'txt',
        };
      }
      if (item.geolocation) {
        itemGeolocation = item.geolocation.coords;
      }
      if (this.state.center) {
        const currentLocation = {
          latitude: this.state.center.lat,
          longitude: this.state.center.lng,
        };
        const distanceArr = geolib.orderByDistance(currentLocation, [itemGeolocation]);
        const miles = (distanceArr[0].distance / 1609.34).toFixed(2);
        if (miles <= userRadius) {
          const loc = new google.maps.LatLng(itemGeolocation.lat, itemGeolocation.lng);
          bounds.extends(loc);
          markers.push({
            _id: item._id,
            position: itemGeolocation,
            number: i,
            content: itemDescription,
            price: item.price,
            quantity: item.quantity,
            currency: item.currency,
            category: item.category,
            title: item.title,
            offer: item.offer,
            thumbnail: itemThumb,
            showInfo: item.showInfo || false,
          });
        }
      }
    });
    this.setState({
      bounds,
    });
    return markers;
  }

  radiusChange(event) {
    console.log(event.target.value);
    this.setState({
      radius: event.target.value,
    });

    const { filter } = this.props.offers;
    filter.radius = event.target.value;
    this.props.sortOffersNew(filter);
  }

  zoomChange(e) {
    console.log('value', e.target.value);
    this.setState({ zoom: Number(e.target.value) });
  }

  render() {
    const markers = this.filterItemsByRadius(this.state.radius);
    return (
      <Col xs={12} smOffset={0} mdOffset={0}>

            Offers within radius of: {' '}
            <input type="text" defaultValue={this.state.radius} onChange={this.radiusChange} /> {' '}
            miles

          {/* <CreateRadius
            radiusChange={this.radiusChange}
            numOffers={markers.length}
            initRadius={this.state.zoom}
          /> */}

          <GeolocationGoogleMap
            googleMapURL={googleMapURL}
            loadingElement={
}
            containerElement={
}
            mapElement={
}
            center={this.state.center}
            showCenterInfo={this.state.showCenterInfo}
            content={this.state.content}
            radius={this.state.radius}
            onMapClick={this.handleMapClick}
            onMarkerClick={this.handleMarkerClick}
            onCloseClick={this.handleCloseClick}
            markers={markers}
            zoom={this.state.zoom}
            bounds={this.state.bounds}
          />

      </Col>
    );
  }
}

function mapStateToProps({ browser, offers }) {
  return { browser, offers };
}

const dispatchToProps = dispatch => ({
  sortOffersNew: filter => dispatch(offerActions.sortOffers(filter)),
});

export default connect(mapStateToProps, dispatchToProps)(
  geolocated({
    positionOptions: {
      enableHighAccuracy: false,
    },
    userDecisionTimeout: 5000,
  })(OfferMap),
);

A: You can access fitBounds by adding a ref to the DOM element that google-maps-react generates.
first, add a ref:
<GoogleMap ref={(ref) => { this.map = ref; }}>...</GoogleMap>
Once the component is mounted, you will be able to call fitBounds using the ref.
this.map.fitBounds(bounds)

A: You can assign a ref to the GoogleMap Component, then call the fitBounds() function using a lifecycle hook.
import React, { useRef, useEffect } from 'react';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";
import { GOOGLE_API_KEY } from '../../config/config';

// =======================================================================
//  GOOGLE MAPS
// =======================================================================
const RegularMap = withScriptjs(
  withGoogleMap(
    ({ defaultCenter, markers }) => {
      const mapRef = useRef(null);

      // Fit bounds function
      const fitBounds = () => {
        const bounds = new window.google.maps.LatLngBounds();
        markers.map(item => {
          bounds.extend(item.position);
          return item.id
        });
        mapRef.current.fitBounds(bounds);
      };

      // Fit bounds on mount, and when the markers change
      useEffect(() => {
        fitBounds();
      }, [markers]);

      return (
        <GoogleMap ref={mapRef} defaultCenter={defaultCenter}>
          {markers.map(
            ({ position }, index) => <Marker key={`marker_${index}`} position={position} />
          )}
        </GoogleMap>
      );
    })
);

// =======================================================================
//  THE MAIN COMPONENT
// =======================================================================

const MapView = () => {
  const markers = [
    { position: { lat: 37.778519, lng: -122.405640 } },
    { position: { lat: 6.4454594, lng: 3.449074 } }
  ];

  return (
      <RegularMap
        defaultCenter={{ lat: 6.4454594, lng: 3.449074 }}
        markers={markers}
        googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}`}
        loadingElement={
}
        containerElement={
}
        mapElement={
}
      />
  );
}

export default MapView;

A: You can use fitbounds in componentDidMount or render function
add ref to GoogleMap and apply fitbounds
 <GoogleMap ref={map => map && map.fitBounds(bounds)}> .... </GoogleMap>

A: The example demonstrates how to center viewport for the given markers:
const MapWithAMarkers = compose(
    withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    lifecycle({
        componentWillMount() {

            this.setState({

                zoomToMarkers: map => {
                    //console.log("Zoom to markers");
                    const bounds = new window.google.maps.LatLngBounds();
                    map.props.children.forEach((child) => {
                        if (child.type === Marker) {
                            bounds.extend(new window.google.maps.LatLng(child.props.position.lat, child.props.position.lng));
                        }
                    })
                    map.fitBounds(bounds);
                }
            })
        },
    }),
    withScriptjs,
    withGoogleMap
)(props =>
    <GoogleMap ref={props.zoomToMarkers} defaultZoom={5} defaultCenter={{ lat: 25.0391667, lng: 121.525 }}>
        {props.markers.map(marker => (
            <Marker
                key={marker.id}
                position={{ lat: marker.lat, lng: marker.lng }}
            />
        ))}
    </GoogleMap>
    );

Demo

A: I wanted to restrict my map (https://developers.google.com/maps/documentation/javascript/examples/control-bounds-restriction).
I used the options property with GoogleMap component with https://www.npmjs.com/package/@react-google-maps/api library.
The library is complete re-write of the react-google-maps library
CODE:
<GoogleMap
        mapContainerStyle={containerStyle}
        center={center}
        zoom={10}
        ref={(ref) => {this.state.map = ref}}
        onLoad={this.onGoogleMapLoad}
        options={{
                          restriction: {
                               latLngBounds: {
                                   north: 19.137384, // Mumbai
                                   south: 18.510866, // Pune
                                   west: 72.874748,  // Mumbai
                                   east: 73.879864,  // Pune
                                },
                                strictBounds: false,
               }
         }}
>


text:
Q: How to disable the css changes made by Link/href Currently there is a table with some columns which looks like this:
If one wants to see details about a company it must click on the arrow at the right-end of the row.
The problem appears when I want to make the whole row clickable, it destroys the design of the page even if there are no css classes added with that.
Here is the code when only the right-end arrow is clickable:
import React from 'react';
import { Table, Image, Icon } from 'semantic-ui-react';
import { Link } from 'react-router-dom';

export default class GenericTable extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const { headers, emptyFirstHeader, rows, entityName, idList } = this.props;

    return (

            {emptyFirstHeader &&
}
            {headers.map(header => (

                {header}

            ))}

          {rows.map((row, rowIndex) => (

              {emptyFirstHeader && (

                  <Image src={row.cells[0]} />

              )}

              {
                (emptyFirstHeader ? row.cells.shift() : row,
                row.cells.map((cell, cellIndex) => {
                  if (cell === undefined) {
                    return null;
                  }
                  return (
                    <Table.Cell
                      key={
                        idList && `${idList[rowIndex]} ${headers[cellIndex]}`
                      }>
                      {cell}

                  );
                }))
              }

                <Link
                  to={
                    entityName && `/${entityName}/${idList[rows.indexOf(row)]}`
                  }>
                  <Icon name="chevron right" />
                </Link>

          ))}

    );
  }
}

And when I include each
 inside a <Link> it makes the row clickable but it breaks the design:
import React from 'react';
import { Table, Image, Icon } from 'semantic-ui-react';
import { Link } from 'react-router-dom';

export default class GenericTable extends React.PureComponent {
  constructor(props) {
    super(props);
  }

  render() {
    const { headers, emptyFirstHeader, rows, entityName, idList } = this.props;

    return (

            {emptyFirstHeader &&
}
            {headers.map(header => (

                {header}

            ))}

          {rows.map((row, rowIndex) => (
             <Link // ADDED HERE
                to={
                  entityName && `/${entityName}/${idList[rows.indexOf(row)]}`
                }>

              {emptyFirstHeader && (

                  <Image src={row.cells[0]} />

              )}

              {
                (emptyFirstHeader ? row.cells.shift() : row,
                row.cells.map((cell, cellIndex) => {
                  if (cell === undefined) {
                    return null;
                  }
                  return (
                    <Table.Cell
                      key={
                        idList && `${idList[rowIndex]} ${headers[cellIndex]}`
                      }>
                      {cell}

                  );
                }))
              }

                <Link
                  to={
                    entityName && `/${entityName}/${idList[rows.indexOf(row)]}`
                  }>
                  <Icon name="chevron right" />
                </Link>

         </Link> // CLOSED HERE
          ))}

    );
  }
}

How can it be done without affecting the design?

A: If you done need semantic HTML, you can edit the Table.Row to use Link as its components, like so. And then give the Row a class or style display: table-row

content of the Row

You can replace the default element with the as prop and the library will pass any other props to the new component, so if you pass to it will pass the link to the Link component.


text:
Q: bulma input field with right icon : how to bind jquery event Having an input type=password field made with bulma with an additional icon on the right, i want to bind an onclick event with jquery to this icon, to toggle the visibility of the password. it does not react this way.. every hint is welcome, thanks

            <input id="form_password" class="input" type="password" placeholder="Password">

A: Ok, i found the answer by myself. It's the icon class in bulma.

now it works ..


text:
Q: How to acces projectstage within a filter Using a filter for authentication I do not want to login each time during development stage and I do not want to outcomment the filter during development I thought about using the project-stage to only authenticate in production mode.
How can the projectstage be retrieved in a filter since FacesContext is not available?

A: If it's definied as <context-param> in web.xml the usual way, then you could obtain it in the filter's init() as follows:
private boolean development;

@Override
public void init(FilterConfig config) {
    development = "Development".equals(config.getServletContext().getInitParameter("javax.faces.PROJECT_STAGE"));
}

// ...


text:
Q: Sylius - Extend Product fixtures from CoreBundle I've extended the Product model from CoreBundle (v1.0.0-alpha) and I want to change the behavior of the fixtures based on this new model. Keeping in mind that CoreBundle\Fixture\Factory\ProductExampleFactory is final, I am looking for a way to extend the fixtures so I don't have to rewrite the whole class and the whole "default" suite.
AppBundle\Entity\Product
<?php

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Sylius\Component\Core\Model\Product as BaseProduct;

/**
 * Product
 *
 * @author leogout
 *
 * @ORM\Table(name="sylius_product")
 * @ORM\Entity
 */
class Product extends BaseProduct
{
    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Package", mappedBy="component")
     */
    protected $packages;

    /**
     * @var boolean
     *
     * @ORM\Column(type="boolean")
     */
    protected $exposed;

    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Customization", mappedBy="product")
     * @ORM\JoinColumn(name="customization_id", referencedColumnName="id")
     */
    protected $customizations;

    /**
     * Product constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->packages = new ArrayCollection();
        $this->customizations = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set exposed
     *
     * @param boolean $exposed
     * @return Product
     */
    public function setExposed($exposed)
    {
        $this->exposed = $exposed;

        return $this;
    }

    /**
     * Get exposed
     *
     * @return boolean
     */
    public function getExposed()
    {
        return $this->exposed;
    }

    /**
     * Add packages
     *
     * @param Package $packages
     * @return Product
     */
    public function addPackage(Package $packages)
    {
        $this->packages[] = $packages;

        return $this;
    }

    /**
     * Remove packages
     *
     * @param Package $packages
     */
    public function removePackage(Package $packages)
    {
        $this->packages->removeElement($packages);
    }

    /**
     * Get packages
     *
     * @return ArrayCollection
     */
    public function getPackages()
    {
        return $this->packages;
    }

    /**
     * Add customizations
     *
     * @param Customization $customizations
     * @return Product
     */
    public function addCustomization(Customization $customizations)
    {
        $this->customizations[] = $customizations;

        return $this;
    }

    /**
     * Remove customizations
     *
     * @param Customization $customizations
     */
    public function removeCustomization(Customization $customizations)
    {
        $this->customizations->removeElement($customizations);
    }

    /**
     * Get customizations
     *
     * @return ArrayCollection
     */
    public function getCustomizations()
    {
        return $this->customizations;
    }
}

Thanks in advance !
EDIT :
After some digging, I saw that I needed to code a whole new fixture with a new ProductFixture, a new ProductExampleFactory and a new MyCustomProductFixture on top of that with their own config files which is not ideal... Do you have a better solution ?