Thursday 31 January 2019

How do I use a pypi library with modifications in my project properly?

I would like to use a specialized PyPi library with LGPL 3.0 licensing that parses UTF-8 from HTTP Content-Disposition headers properly according to RFC-6266 in my commercial project.

The problem is that the project only supports Python 3.3, and I use 3.7 in the project. When I use this code with python 3.6 or 3.7 I get warnings.

There are some forks that add support up to 3.6 for the project, and other forks that add other useful functionality.

The maintainer hasn't cut a release in 5 years, so it seems unlikely a PR would be accepted at this point. What are my options to do this in the most legal and Pythonic way?

  • Do I use this as a template to write my own library?
  • Do I fork the repo, make my changes, and pip install from my own repo?
  • Something else?

Thanks Python professionals in advance for your advice.



from How do I use a pypi library with modifications in my project properly?

Overlapping happening instead of uploading image on mask

Background

I am allowing user to upload an image inside mask image....

Mask image :

enter image description here

User uploaded image :

enter image description here

Requirement: What I need as below :

enter image description here

Issue : What I am getting now as below : The uploaded image is displaying [ overlay ] outside the mask image instead of inside as below.

enter image description here

JS Fiddle: http://jsfiddle.net/uLfeaxck/

Here is website url

html

<h3>Upload Photo</h3>
<label id="btn_upload_from_computer" for="fileupload_image" class="button -primary -size-md -full-width">
<svg class="icon-computer" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="23px" height="20.031px" viewBox="0 0 23 20.031" enable-background="new 0 0 23 20.031" xml:space="preserve">
<path id="computer" fill="#FFFFFF" d="M21.793,0H1.207C0.539,0.002-0.002,0.545,0,1.213v14.42c-0.001,0.667,0.539,1.209,1.207,1.211
                h6.47v1.442c0,1-2.433,1-2.433,1v0.722l6.127,0.023h0.068l6.126-0.023v-0.722c0,0-2.434,0-2.434-1v-1.442h6.662
                c0.668-0.002,1.208-0.543,1.207-1.211V1.213C23.002,0.545,22.461,0.002,21.793,0z M21.235,15.11H1.765V1.735h19.47v13.378V15.11z" />
</svg>
From your computer
</label>
<input type="file" id="fileupload_image" style="position: absolute; left: -2000px;" accept="image/*" />



from Overlapping happening instead of uploading image on mask

FPS drop when adding child to a scene ARKit/SceneKit

I'm working on an ARKit project for 4 months now. I noticed that when adding a child to my scene rootNode, there is a FPS drop. The device freezes for less than a second. I did a lot of research and trials, noticed that all Apple's code examples have this FPS drop too when placing an object. It does not matter if the node is added directly (scene.rootNode.addChild(child)) or if it's added in the renderer loop at different phases (didUpdateAtTime, didApplyAnimations etc...). I found that once an object has been added to a scene, the next added object will render immediately. I use a 3D model created in SceneKit editor, clone it to generate my different nodes before adding them as child. I do this loading work before placing the objects.

Instruments shows that the renderer loop is busy for the duration of the freeze.

The only solution that I found is to add my nodes to the scene behind a loading screen before starting the whole experience.

Is that a normal behavior in game programming to render nodes before using them ?

Thanks guys



from FPS drop when adding child to a scene ARKit/SceneKit

Flask-sentinel /oauth/token endpoint CORS issue

I'm having issues trying to get a token from my flask-sentinel app with my front-end.

To make the AJAX requests from my front-end to my Python Eve API server I use the superagent module.

While using a Basic Authentication I don't have any issue getting data from my endpoints. See code below:

superagent
    .get( 'http://192.168.1.x:5000/endpoint' )
    .auth( this.params.username, this.params.password )
    .on( 'error', this.onError )
    .then( this.onSuccess );

If I try to request a token to the /oauth/token endpoint with this code:

superagent
    .post( 'http://192.168.1.x:5000/oauth/token' )
    .set( 'Content-Type', 'application/x-www-form-urlencoded' )
    .send( 'grant_type=password&client_id='+this.params.client_id+'&username='+this.params.username+'&password='+this.params.password )
    .on( 'error', this.onError )
    .then( this.onTokenReceived );

I get a CORS error:

Access to XMLHttpRequest at 'http://192.168.1.x:5000/oauth/token' from origin 'http://192.168.1.y:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Here are the settings of my application (omitting the database and domain settings):

SENTINEL_X_DOMAINS           = ['http://192.168.1.y:3000']
SENTINEL_X_HEADERS           = ['Authorization','Content-type','If-Match','Access-Control-Allow-Origin']
SENTINEL_X_EXPOSE_HEADERS    = SENTINEL_X_HEADERS
SENTINEL_RESOURCE_METHODS    = ['GET','HEAD','PUT','PATCH','POST','DELETE','OPTIONS']
SENTINEL_PUBLIC_METHODS      = SENTINEL_RESOURCE_METHODS
SENTINEL_X_ALLOW_CREDENTIALS = True

X_DOMAINS           = ['http://192.168.1.y:3000']
X_ALLOW_CREDENTIALS = True
X_HEADERS           = ['Authorization','Content-type','If-Match','Access-Control-Allow-Origin']
RESOURCE_METHODS    = ['GET','HEAD','PUT','PATCH','POST','DELETE','OPTIONS']

Can you please guide me in getting what I'm doing wrong?

Thank you in advance!



from Flask-sentinel /oauth/token endpoint CORS issue

How to break RxJava chain on error Result?

I've inherited this codebase which uses RxJava2 and kotlin with a rather peculiar Result pattern for API calls. i.e. all API calls return Singles with a Result object (which is a sealed class of Success and Error types as shown below) i.e.

sealed class Result<T, E> {
    data class Success<T, E>(
            val data: T
    ): Result<T, E>()

    data class Error<T, E>(
            val error: E
    ): Result<T, E>()
}

Now I'm trying to chain together a bunch of API calls of these but need to terminate the chain on the first Result.Error in it and continue if not.

The only way I can think of is to zip all of the Singles and then have a zipper function that checks the type of each parameter and returns a Result.Error() with the first error it encounters. i.e. something like,

Singles.zip(
    repo1.makeCall1(arg),
    repo1.makeCall2(arg2),
    repo2.makeCall1(arg3)
) { result1, result2, result3 ->
    val data1 = when (result1) {
        is Result.Error -> return@zip Result.Error(result1.error)
        is Result.Success -> result1.data
    }
    val data2 = when (result2) {
        is Result.Error -> return@zip Result.Error(result2.error)
        is Result.Success -> result2.data
    }
    val data3 = when (result3) {
        is Result.Error -> return@zip Result.Error(result3.error)
        is Result.Success -> result3.data
    }

    return@zip Result.Success(MergedData(data1, data2, data3))
}

which works but looks really weird (and feels like a code smell with this huge ass zipper method). Also does not allow me to chain anything more after the last method (that checks if the Result is a Success / Error).

I feel it would be a lot more readable to be able to chain these calls and terminate on the first error but I don't know enough Rx to do this. Is there an operator or an approach that could help make this better?



from How to break RxJava chain on error Result?

Permutations without recursive function call

Requirement: Algorithm to generate all possible combinations of a set , without duplicates , or recursively calling function to return results.

The majority , if not all of the Answers provided at Permutations in JavaScript? recursively call a function from within a loop or other function to return results.

Example of recursive function call within loop

function p(a, b, res) {
  var b = b || [], res = res || [], len = a.length;
  if (!len) 
    res.push(b)
  else 
    for (var i = 0; i < len 
         // recursive call to `p` here
       ; p(a.slice(0, i).concat(a.slice(i + 1, len)), b.concat(a[i]), res)
       , i++
    );
  return res
}

p(["a", "b", "c"]);

The current Question attempts to create the given permutation in a linear process , relying on the previous permutation.

For example , given an array

var arr = ["a", "b", "c"];

to determine the total number of possible permutations

for (var len = 1, i = k = arr.length; len < i ; k *= len++);

k should return 6 , or total number of possible permutations of arr ["a", "b", "c"]

With the total number of individual permutations determined for a set , the resulting array which would contain all six permutations could be created and filled using Array.prototype.slice() , Array.prototype.concat() and Array.prototype.reverse()

var res = new Array(new Array(k));

res[0] = arr;

res[1] = res[0].slice(0,1).concat(res[0].slice(-2).reverse());

res[2] = res[1].slice(-1).concat(res[1].slice(0,2));

res[3] = res[2].slice(0,1).concat(res[2].slice(-2).reverse());

res[4] = res[3].slice(-2).concat(res[3].slice(0,1));

res[5] = res[4].slice(0,1).concat(res[4].slice(-2).reverse());

Attempted to reproduce results based on the pattern displayed at the graph for An Ordered Lexicographic Permutation Algorithm based on one published in Practical Algorithms in C++ at Calculating Permutations and Job Interview Questions .

There appears to be a pattern that could be extended if the input set was , for example

["a", "b", "c", "d", "e"]

where 120 permutations would be expected.

An example of an attempt at filling array relying only on previous permutation

// returns duplicate entries at `j`
var arr = ["a", "b", "c", "d", "e"], j = [];
var i = k = arr.length;
arr.forEach(function(a, b, array) {
 if (b > 1) {
  k *= b;
  if (b === i -1) {
    for (var q = 0;j.length < k;q++) {
      if (q === 0) {
       j[q] = array;
      } else {
       j[q] = !(q % i) 
              ? array.slice(q % i).reverse().concat(array.slice(0, q % i)) 
              : array.slice(q % i).concat(array.slice(0, q % i));
      }
    }
  }
 }
})

however have not yet been able to make the necessary adjustments at parameters for .slice() , .concat() , .reverse() at above js to step from one permutation to the next ; while only using the previous array entry within res to determine current permutation , without using recursive.

Noticed even , odd balance of calls and tried to use modulus % operator and input array .length to either call .reverse() or not at ["a", "b", "c", "d", "e"] array , though did not produce results without duplicate entries.

The expected result is that the above pattern could be reduced to two lines called in succession for the duration of the process until all permutations completed, res filled ; one each for call to .reverse() , call without .reverse() ; e.g., after res[0] filled

// odd , how to adjust `.slice()` , `.concat()` parameters 
// for array of unknown `n` `.length` ?
res[i] = res[i - 1].slice(0,1).concat(res[i - 1].slice(-2).reverse());
// even    
res[i] = res[1 - 1].slice(-1).concat(res[i - 1].slice(0,2));

Question: What adjustments to above pattern are necessary , in particular parameters , or index , passed .slice() , .concat() to produce all possible permutations of a given set without using a recursive call to the currently processing function ?

var arr = ["a", "b", "c"];

for (var len = 1, i = k = arr.length; len < i; k *= len++);

var res = new Array(new Array(k));

res[0] = arr;

res[1] = res[0].slice(0, 1).concat(res[0].slice(-2).reverse());

res[2] = res[1].slice(-1).concat(res[1].slice(0, 2));

res[3] = res[2].slice(0, 1).concat(res[2].slice(-2).reverse());

res[4] = res[3].slice(-2).concat(res[3].slice(0, 1));

res[5] = res[4].slice(0, 1).concat(res[4].slice(-2).reverse());

console.log(res);

Edit, Update

Have found a process to utilize pattern described above to return permutations in lexicographic order for an input up to .length 4 , using a single for loop. Expected results are not returned for array with .length of 5.

The pattern is based on the second chart at "Calculating Permutations and Job Interview Questions"[0].

Would prefer not to use .splice() or .sort() to return results, though used here while attempting to adhere to last "rotate" requirement at each column. The variable r should reference the index of the first element of the next permutation, which it does.

The use of .splice() , .sort() could be included if their usage followed the pattern at the chart ; though at js below, they actually do not.

Not entirely certain that the issue with js below is only the statement following if (i % (total / len) === reset) , though that portion required the most investment of time; yet still does not return expected results.

Specifically, now referring to the chart, at rotating , for example 2 to index 0, 1 to index 2. Attempted to achieve this by using r , which is a negative index, to traverses from right to left to retrieve next item that should be positioned at index 0 of adjacent "column".

At next column, 2 would be placed at index 2 , 3 would be placed at index 0. This is portion, as far as have been able to grasp or debug, so far, is the area where error is occurring.

Again, returns expected results for [1,2,3,4], though not for [1,2,3,4,5]

var arr = [1, 2, 3, 4];
for (var l = 1, j = total = arr.length; l < j ; total *= l++);
for (var i = 1
     , reset = 0
     , idx = 0
     , r = 0
     , len = arr.length
     , res = [arr]
     ; i < total; i++) {
  // previous permutation
  var prev = res[i - 1];
  // if we are at permutation `6` here, or, completion of all 
  // permutations beginning with `1`;
  // setting next "column", place `2` at `index` 0;
  // following all permutations beginning with `2`, place `3` at
  // `index` `0`; with same process for `3` to `4`
  if (i % (total / len) === reset) {
    r = --r % -(len);
    var next = prev.slice(r);
    if (r === -1) {
      // first implementation used for setting item at index `-1`
      // to `index` 0
      // would prefer to use single process for all "rotations",
      // instead of splitting into `if` , `else`, though not there, yet
      res[i] = [next[0]].concat(prev.slice(0, 1), prev.slice(1, len - 1)
               .reverse());
    } else {
      // workaround for "rotation" at from `index` `r` to `index` `0`
      // the chart does not actually use the previous permutation here,
      // but rather, the first permutation of that particular "column";
      // here, using `r` `,i`, `len`, would be 
      // `res[i - (i - 1) % (total / len)]`
      var curr = prev.slice();
      // this may be useful, to retrieve `r`, 
      // `prev` without item at `r` `index`
      curr.splice(prev.indexOf(next[0]), 1);
      // this is not optiomal
      curr.sort(function(a, b) {
        return arr.indexOf(a) > arr.indexOf(b)
      });
      // place `next[0]` at `index` `0`
      // place remainder of sorted array at `index` `1` - n
      curr.splice(0, 0, next[0])
      res[i] = curr
    }
    idx = reset;
  } else {
    if (i % 2) {
      // odd
      res[i] = prev.slice(0, len - 2).concat(prev.slice(-2)
              .reverse())
    } else {
      //  even
      --idx
      res[i] = prev.slice(0, len - (len - 1))
               .concat(prev.slice(idx), prev.slice(1, len + (idx)))
    }
  }
}
// try with `arr` : `[1,2,3,4,5]` to return `res` that is not correct;
// how can above `js` be adjusted to return correct results for `[1,2,3,4,5]` ?
console.log(res, res.length)

Resources:

Generating Permutation with Javascript

(Countdown) QuickPerm Head Lexicography: (Formally Example_03 ~ Palindromes)

Generating all Permutations [non-recursive] (Attempt to port to from C++ to javascript jsfiddle http://jsfiddle.net/tvvvjf3p/)

Calculating Permutation without Recursion - Part 2

permutations of a string using iteration

iterative-permutation

Permutations by swapping

Evaluation of permutation algorithms

Permutation algorithm without recursion? Java

Non-recursive algorithm for full permutation with repetitive elements?

String permutations in Java (non-recursive)

Generating permutations lazily

How to generate all permutations of a list in Python

Can all permutations of a set or string be generated in O(n log n) time?

Finding the nth lexicographic permutation of ‘0123456789’

Combinations and Permutations



from Permutations without recursive function call

Caching Selected Text Element with Google Doc Apps Script

Update: This is a better way of asking the following question.

Is there an Id like attribute for an Element in a Document which I can use to reach that element at a later time. Let's say I inserted a paragraph to a document as follows:

var myParagraph = 'This should be highlighted when user clicks a button';
body.insertParagraph(0, myParagraph);

Then the user inserts another one at the beginning manually (i.e. by typing or pasting). Now the childIndex of my paragraph changes to 1 from 0. I want to reach that paragraph at a later time and highlight it. But because of the insertion, the childIndex is not valid anymore. There is no Id like attribute for Element interface or any type implementing that. CahceService and PropertiesService only accepts String data, so I can't store myParagraphas an Object.

Do you guys have any idea to achieve what I want?

Thanks,

Old version of the same question (Optional Read):

Imagine that user selects a word and presses the highlight button of my add-on. Then she does the same thing for several more words. Then she edits the document in a way that the start end end indexes of those highlighted words change.

At this point she presses the remove highlighting button. My add-on should disable highlighting on all previously selected words. The problem is that I don't want to scan the entire document and find any highlighted text. I just want direct access to those that previously selected.

Is there a way to do that? I tried caching selected elements. But when I get them back from the cache, I get TypeError: Cannot find function insertText in object Text. error. It seems like the type of the object or something changes in between cache.put() and cache.get().

var elements = selection.getSelectedElements();
    for (var i = 0; i < elements.length; ++i) {
      if (elements[i].isPartial()) {
        Logger.log('partial');
        var element = elements[i].getElement().asText();

        var cache = CacheService.getDocumentCache();
        cache.put('element', element);  


        var startIndex = elements[i].getStartOffset();
        var endIndex = elements[i].getEndOffsetInclusive();
     }
    // ...
   }

When I get back the element I get TypeError: Cannot find function insertText in object Text. error.

 var cache = CacheService.getDocumentCache();
 cache.get('text').insertText(0, ':)');  

I hope I can clearly explained what I want to achieve.



from Caching Selected Text Element with Google Doc Apps Script

Why OpenCV Mat creates memory leeks?

Not sure if this is relevant, but I'm using opencv4nodejs for my project, and I did run in this situation where if I don't call .release() on each Mat object, the memory consumption goes up ~10MB/s.

This simple example code will crate the issue.

function loop(camera, display)
{
    let mat = camera.read();

    let grey_mat = mat.bgrToGray();

    loop(camera, display);
}

Where as, this one fixes the problem:

function loop(camera, display)
{
    let mat = camera.read();

    let grey_mat = mat.bgrToGray();

    grey_mat.release();

    mat.release();

    loop(camera, display);
}

If I search for why OpenCV Mat object causes leeks I get answers where people say that Mat is capable of taking care of memory usage on its own.

If the last statement is true, what am I doing wrong? And if I'm not doing anything wrong, why do I have to explicitly tell a Mat object to release its memory? Or, is there a potential issue with the npm module opencv4nodejs itself?



from Why OpenCV Mat creates memory leeks?

Rewriting an Android OpenGL filter to Metal (for CIFilter)

There are dozens of image filters written for the Android version of our app in GLSL (ES). As of iOS 12, OpenGL is deprecated, and CIFilter kernels have to be written in Metal.

I had some previous background in OpenGL, however writing CIFilter kernels in Metal is new to me.

Here is one of the filters. Could you help me in translating it to Metal as a CIFilter kernel? That would provide a good example for me so I could translate others.

#extension GL_OES_EGL_image_external : require
precision mediump float;
varying vec2 vTextureCoord;
uniform samplerExternalOES sTexture;
uniform float texelWidth;
uniform float texelHeight;
uniform float param_Intensity_40;
void main() {
    float SIZE = 1.25 + (param_Intensity_40 / 100.0)*2.0;
    vec4 color;
    float min = 1.0;
    float max = 0.0;
    float val = 0.0;
    for (float x = -SIZE; x < SIZE; x++) {
        for (float y = -SIZE; y < SIZE; y++) {
            color = texture2D(sTexture, vTextureCoord + vec2(x * texelWidth, y * texelHeight));
            val = (color.r + color.g + color.b) / 3.;
            if (val > max) { max = val; } else if (val < min) { min = val; }
        }
    }
    float range = 5. * (max - min);
    gl_FragColor = vec4(pow(1. - range, SIZE * 1.5));
    gl_FragColor = vec4((gl_FragColor.r + gl_FragColor.g + gl_FragColor.b) / 3. > 0.75 ? vec3(1.) : gl_FragColor.rgb, 1.);
}



from Rewriting an Android OpenGL filter to Metal (for CIFilter)

Require user to be logged in not working for gravity form though user is logged in wordpress

In a WordPress project, I am using login in frontend. I have included plugin Gravity form. One of the page(e.g. abc) has form with form setting as 'Require user to be logged in'.

Issue: When I first log in and go to page abc, form shows(as user is logged in) but when I first go to page abc and then do login although user is logged in form isn't showing(it shows only if I refresh the page). Why is this happening?

I am using if($("body").hasClass("logged-in")) to check whether user is logged in or not.

Any help/suggestions are welcome. One thing I have noticed during 'inspect' in application is a specific cookie wordpress_456b46f4d1347f23495548c111992d89 with path as /wp-content/plugins isn't initially loaded in page with gravity form after login. It comes after refresh. I am confused regarding this cookie.



from Require user to be logged in not working for gravity form though user is logged in wordpress

Javascript/Jquery making text to fit perfectly on div given dimensions with line break(if needed)

I'm having a little hard time working this out: I have these functions that I use in order to fit a single lined text into given dimensions.

function getFontSize(width, height, text, font, callback) {
    var n = 100;
    var ctxfont = n + 'px ' + font;
    var result = measureTextHeight(ctxfont, text);
    while (result.width > width || result.height > height) {
        n--;
        var ctxfont = n + 'px ' + font;
        var result = measureTextHeight(ctxfont, text);
    }
    callback({
        'width': result.width,
        'height': result.height,
        'size': n
    });
}

function measureTextHeight(ctxFont, text) {
    var width = 1500;
    var height = 500;

    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");
    ctx.save();
    ctx.font = ctxFont;
    ctx.clearRect(0, 0, width, height);
    ctx.fillText(text, parseInt(width * 0.1, 10), parseInt(height / 2, 10));
    ctx.restore();
    document.body.appendChild(canvas);
    var data = ctx.getImageData(0, 0, width, height).data;


    var topMost = false;
    var bottomMost = false;
    var leftMost = false;
    var rightMost = false;
    for (var x = 0; x < width; x++) {
        for (var y = 0; (y < height) && (!leftMost); y++) {
            //console.log("x: %s y: %s index: %s", x,y, getAlphaIndexForCoordinates(x,y,width,height).toString() );
            if (data[getAlphaIndexForCoordinates(x, y, width, height)] != 0) {
                leftMost = x;
            }
        }
    }
    for (var y = 0; y < height; y++) {
        for (var x = 0; (x < width) && (!topMost); x++) {
            //console.log("x: %s y: %s index: %s", x,y, getAlphaIndexForCoordinates(x,y,width,height).toString() );
            if (data[getAlphaIndexForCoordinates(x, y, width, height)] != 0) {
                topMost = y;
            }
        }
    }
    for (var x = width - 1; x >= 0; x--) {
        for (var y = height - 1; (y >= 0) && (!rightMost); y--) {
            //console.log("x: %s y: %s index: %s", x,y, getAlphaIndexForCoordinates(x,y,width,height).toString() );
            if (data[getAlphaIndexForCoordinates(x, y, width, height)] != 0) {
                rightMost = x;
            }
        }
    }
    for (var y = height - 1; y >= 0; y--) {
        for (var x = width - 1; (x >= 0) && (!bottomMost); x--) {
            //console.log("x: %s y: %s index: %s", x,y, getAlphaIndexForCoordinates(x,y,width,height).toString() );
            if (data[getAlphaIndexForCoordinates(x, y, width, height)] != 0) {
                bottomMost = y;
            }
        }
    }
    canvas.remove();
    return ({
        width: (rightMost - leftMost) + 1
        , height: (bottomMost - topMost) + 1
    });
}

function getAlphaIndexForCoordinates(x, y, width, height) {
    return (((width * 4 * y) + 4 * x) + 3);
}

I pass the wanted dimensions and font to getFontSize function and it returns the real width and height of the text as well as the font size needed for it to be accomplished. This way I can draw the text to canvas using ctx.filltext() function, the best fit possible, and align it in the center based on its width and height. I'm not sure if it's the most efficient way of achieving the wanted result but it's working.

What I want to do now is instead of making it single lined, I can set a given width and height for a div and then, giving the text, it would fit perfectly those dimensions adding line breaks if needed, and still return the real width and height of the text so I can draw it correctly to the canvas like this fiddle: http://jsfiddle.net/vkgjrd3e/ although in the fiddle it still has some space on the bottom of the div.

What I'm trying to achieve is the best fit possible for the text, given its font and its container dimensions; adding line breaks if needed.



from Javascript/Jquery making text to fit perfectly on div given dimensions with line break(if needed)

Not able to secure website on Firefox even after installing SSL certificate

I am using the below code to install SSL certificate on my website:

const express = require('express');
const path = require('path');
const app = express();
const fs= require('fs');
let privateKey = fs.readFileSync('certificate/x.key', 'utf8');
let ca = fs.readFileSync('certificate/x.crt', 'utf8');
let certificate = fs.readFileSync('certificate/x.crt', 'utf8');
let credentials = { key: privateKey, cert: certificate, ca: ca };
const http = require('http');
const https = require('https');

app.use(express.static(path.join(__dirname, 'build')));

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

let httpsServer = https.createServer(credentials, app);

httpsServer.listen(443);

This is a react app and I am serving it via Node.js.

When I open the website on Chrome or Microsoft Edge, it shows the connection as secure, encrypted and valid but when I open it on firefox, it shows that the connection is not secure. Valid in Chrome Not working in Firefox

What could be the problem?



from Not able to secure website on Firefox even after installing SSL certificate

Custom Core Image filter color issue

I'm learning how to write custom Core Image filters, but have this problem where the rendered color is not the same as specified in kernel code when color value is between 0 - 1. (Color is correct when equal to 0 or 1.)

This is my filter code:

import UIKit
class testFilter: CIFilter
{   
    // simply return half red color (0.5)

    var colorKernel = CIColorKernel(string:
        "kernel vec4 theFilter()" +
        "{ return vec4(0.5, 0.0, 0.0, 1.0); }"
    )

    override var outputImage: CIImage!
    { 
        let rect = CGRect(x: 0, y: 0, width: 200, height: 100)
        return colorKernel.applyWithExtent(rect,arguments: nil)
    }
}

Usage:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // generate image
        let filter = testFilter()
        let ciImage = f.outputImage      
        let image = UIImage(CIImage: ciImage) 

        // add to view
        let v = UIImageView(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
        v.image = image     
        view.addSubview(v)
    }
}

The output image looks like this, the actual red component value is around 190 (I checked color value using Photoshop). For a value of 0.5 I thought the correct output value would be 255 * 0.5 = 122.5?

the output image



from Custom Core Image filter color issue

running/controlling emultor on remote server

i know this not suitable question for SO but i have nowhere else to ask hopefully i'll get a answer before mods close this question !

so i use couple of android apps on daily bases on specific time , and its very time consuming

i want to somehow automatize the process

the idea is to install some sort of emulator on the server , and program that emulator trough some programing language to run the apps on the server when its time

im a web developer , i work with php , nodejs , python not really familiar with mobile space , so i thought to ask here

is there any solution out there to do what i want ? i search around and found Appium but im not sure if it would do what i want

pleas not these apps doesn't have a public api for me to use , also i only have remote access to server via ssh terminal



from running/controlling emultor on remote server

Step fade Infinite Scroll appending of items

I'm using Isotope's Masonry layout alongside Infinite Scroll, which is initiated by clicking a button.

I want to animate/transition each .article item into place, however I am only able to achieve this via CSS on the initial layout. Is there a way of creating this 'step fade' effect each time the infinite scroll function is run?

Many thanks.

HTML

<div class="articles">
    <div class="article">
    </div>
</div>

JQUERY

$('.articles').imagesLoaded(function () {
    // vars
    // Define grid
    var $grid = $('.articles');

    $grid.isotope({
        itemSelector: '.article',
        layoutMode: 'masonry',
        transitionDuration: 0,
        stagger: 500,
        hiddenStyle: { opacity: 0 },
        visibleStyle: { opacity: 1 }
    });

    var iso = $grid.data('isotope');

    // Init infinite scroll
    $grid.infiniteScroll({
        path: '.pagination .next a',
        append: '.article',
        outlayer: iso,
        loadOnScroll: false,
        scrollThreshold: false,
        button: '.load-more-button',
        hideNav: '.pagination',
        status: '.load-status',
    });         
});



from Step fade Infinite Scroll appending of items

How to get value of LiveData from repository that don't access to lifeCycleOwner for observing it?

I have used of MVVM and ROOM and databindig in my app.According Guide to app architecture ,I want to cash data using room.In the xml layout of RecyclerView item, I use CategoryViewModel variable.I get list of categories from Room database withLiveData type. I want to change LiveData<list<CategoryItem>> type to MutableLiveData<ArrayList<CategoryViewModel>> type. Because finally my adapter consume ArrayList<CategoryViewModel> data type.How to get value of LiveData? When I call getValue() method, returns null. this is CategoryItem model:

    @Entity(tableName = "category_table")
public class CategoryItem implements Serializable {

    @PrimaryKey
    private int id;
    private String title;
    private String imagePath;
    @TypeConverters({SubCategoryConverter.class})
    private ArrayList<String> subCategory;
    @TypeConverters({DateConverter.class})
    private Date lastRefresh;

    public CategoryItem(int id, String title, String imagePath, ArrayList<String> subCategory, Date lastRefresh) {
        this.id = id;
        this.title = title;
        this.imagePath = imagePath;
        this.subCategory = subCategory;
        this.lastRefresh=lastRefresh;
    }

    public CategoryItem(int id, String title, String imagePath) {
        this.id = id;
        this.title = title;
        this.imagePath = imagePath;
    }

    public CategoryItem() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

    public ArrayList<String> getSubCategory() {
        return subCategory;
    }

    public void setSubCategory(ArrayList<String> subCategory) {
        this.subCategory = subCategory;
    }

    public Date getLastRefresh() {
        return lastRefresh;
    }

    public void setLastRefresh(Date lastRefresh) {
        this.lastRefresh = lastRefresh;
    }

}

this is CategoryViewModel class:

     public class CategoryViewModel extends AndroidViewModel {

        private String title;
        private String imagePath;
        private MutableLiveData<ArrayList<CategoryViewModel>> allCategories=new MutableLiveData<>();
        private CategoryRepository repository;

        public CategoryViewModel(@NonNull Application application) {
            super(application);
            repository=new CategoryRepository(application, Executors.newSingleThreadExecutor());
        }

        public void init(CategoryItem categoryItem){
            this.title=categoryItem.getTitle();
            this.imagePath=categoryItem.getImagePath();
        }

        public MutableLiveData<ArrayList<CategoryViewModel>> getAllCategories(){

            allCategories=repository.getCategory();
            return allCategories;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getImagePath() {
            return imagePath;
        }
    }

This is CategoryRepository class:

    public class CategoryRepository {

    private static final String TAG="CategoryRepository";
    private static int FRESH_TIMEOUT_IN_MINUTES = 1;

    private final Executor executor;

    private APIInterface apiInterface;
    public MutableLiveData<ArrayList<CategoryViewModel>> arrayListMutableLiveData=new MutableLiveData<>();


    private CategoryDao categoryDao;
    private Application application;

    public CategoryRepository(Application application,Executor executor) {
        this.executor = executor;
        this.application = application;
        apiInterface= APIClient.getClient().create(APIInterface.class);
        LearnDatabase database= LearnDatabase.getInstance(application);
        categoryDao=database.categoryDao();
    }

    public MutableLiveData<ArrayList<CategoryViewModel>>  getCategory(){

        refreshCategory();

        List<CategoryItem> items;
        categoryDao.loadCategoryItem();

        items=categoryDao.loadCategoryItem().getValue(); // return null
        CategoryItem category;
        ArrayList<CategoryViewModel> arrayList=new ArrayList<>();

        for(int i=0;i<items.size();i++){

            category=items.get(i);
            CategoryViewModel categoryViewModel=new CategoryViewModel(application);
            categoryViewModel.init(category);
            arrayList.add(categoryViewModel);
        }


        arrayListMutableLiveData.setValue(arrayList);

        return arrayListMutableLiveData;
    }

    private void refreshCategory(){

        executor.execute(() -> {
            String lastRefresh=getMaxRefreshTime(new Date()).toString();
            boolean sliderExists =(!(categoryDao.hasCategory(lastRefresh)).isEmpty());
            Log.e(TAG,"sliderExist: "+sliderExists);
            Log.e(TAG,"lastrefresh: "+lastRefresh);
            Log.e(TAG,"hasSlider: "+categoryDao.hasCategory(lastRefresh).toString());
            // If user have to be updated
            if (!sliderExists) {
                Log.e(TAG,"in if");
                apiInterface.getCategory().enqueue(new Callback<List<CategoryItem>>() {
                    @Override
                    public void onResponse(Call<List<CategoryItem>> call, Response<List<CategoryItem>> response) {

                        executor.execute(() -> {
                            List<CategoryItem> categories=response.body();
                            for (int i=0;i<categories.size();i++){
                                categories.get(i).setLastRefresh(new Date());
                                categoryDao.saveCategory(categories.get(i));
                            }

                        });
                    }

                    @Override
                    public void onFailure(Call<List<CategoryItem>> call, Throwable t) {

                        Log.e(TAG,"onFailure "+t.toString());
                    }
                });
            }

        });
    }

    private Date getMaxRefreshTime(Date currentDate){
        Calendar cal = Calendar.getInstance();
        cal.setTime(currentDate);
        cal.add(Calendar.MINUTE, -FRESH_TIMEOUT_IN_MINUTES);
        return cal.getTime();
    }
   }

This is xml layout of item of recyclerView:

 <?xml version="1.0" encoding="utf-8"?>
<layout>
    <data class="CategoryDataBinding">
        <variable
            name="category"
            type="com.struct.red.alltolearn.viewmodel.CategoryViewModel"/>
    </data>

    <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="200dp"
        android:layout_height="150dp"
        app:cardCornerRadius="15dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/imgItemCategory"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                app:imageUrl="@{category.imagePath}" />

            <TextView
                android:id="@+id/txtTitleItemCategory"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="@{category.title}"
                android:textColor="#FFFFFF"
                android:textSize="20sp"
                android:textStyle="bold" />
        </RelativeLayout>

    </android.support.v7.widget.CardView>
</layout>

This is CategoryDao class:

@Dao

public interface CategoryDao {

@Query("SELECT * FROM course_table")
LiveData<List<CategoryItem>> loadCategoryItem();


@Insert(onConflict = OnConflictStrategy.REPLACE)
void saveCategory(CategoryItem category);

@Query("SELECT * FROM category_table WHERE lastRefresh > Date(:lastRefreshMax)")
List<CategoryItem> hasCategory(String lastRefreshMax);

}

And finally I observe MutableLiveData in my Fragment:

    private void setupCategoryRecycler() {
    categoryViewModel = ViewModelProviders.of(this).get(CategoryViewModel.class);
    categoryViewModel.getAllCategories().observe(this, new Observer<ArrayList<CategoryViewModel>>() {
        @Override
        public void onChanged(@Nullable ArrayList<CategoryViewModel> categoryViewModels) {
            Log.e(TAG, "categoryitem: " + categoryViewModels.toString());
            categoryAdapter = new CategoryAdapter(getContext(), categoryViewModels);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, true);
            linearLayoutManager.setReverseLayout(true);
            CategoryRecy.setLayoutManager(linearLayoutManager);
            CategoryRecy.setAdapter(categoryAdapter);
        }
    });
}



from How to get value of LiveData from repository that don't access to lifeCycleOwner for observing it?

Error: Unable to find the controller for path "/login_check". The route is wrongly configured. (LexikJWTAuthentication)

Description

When I'm doing a normal request to my symfony server running on http://localhost:8000/api/admin/login_check it returns the desired jwt token.

However, when I do it with the functional tests (with ./bin/phpunit) I get the following error:

Error: Unable to find the controller for path \"/api/admin/login_check\". The route is wrongly configured.

I also went through the functional test docs.

Bug Reproduced

I was also able to reproduce the bug by cloning a working example provided by one of the creators of the lexikjwtauthenticationbundle.

Logs

[2019-01-29 21:30:24] request.INFO: Matched route "api_admin_login". {"route":"api_admin_login","route_parameters":{"_route":"api_admin_login"},"request_uri":"http://localhost/api/admin/login_check","method":"POST"} []
[2019-01-29 21:30:24] security.INFO: Populated the TokenStorage with an anonymous Token. [] []
[2019-01-29 21:30:24] request.WARNING: Unable to look for the controller as the "_controller" parameter is missing. [] []

Test method:

    public function testLogin(){

        $client = static::createClient();
        $client->request('POST', '/api/admin/login_check', [], [],
            [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ],
            json_encode([
                'email' => 'email@test.com',
                'password' => 'qwerty123'
            ])
        );

        $this->assertEquals(200, $client->getResponse()->getStatusCode());

    }

Routes:

# Admin Routes
api_admin_login_check:
    path: /api/admin/login_check
    methods:  [POST]

security:

security:

# more configs here

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        login_admin:
            pattern: ^/api/admin/login
            stateless: true
            anonymous: true
            json_login:
                username_path: email
                provider: app_admin_provider
                check_path: /api/admin/login_check
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure

        admin_api:
            pattern: ^/api/admin
            stateless: true
            provider: app_admin_provider
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator

    access_control:
        - { path: ^/api/admin/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api/admin/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api/admin, roles: ROLE_ADMIN }
        - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }

Why is there a 404 route not found for /api/admin/login_check route during Functional Testing but works fine with curl and postman?

Github #610



from Error: Unable to find the controller for path "/login_check". The route is wrongly configured. (LexikJWTAuthentication)

Pyautogui mouse clicks without actually moving the mouse

I'd like to know if it's possible to automate clicks with pyautogui without compromising the funcionality of my cursor. I automate clicks with pyautogui but my cursor becomes useless while the script is running as the cursor moves around the screen. I was wondering if it is possible to either 1) have two cursos and have pyautogui automating one while I operate the other myself, or 2) have pyautogui click on the screen without actually moving my cursor.



from Pyautogui mouse clicks without actually moving the mouse

Not able to release postgres client using npm-postgres

Here is the code that I have tried.client.release() or client.end() is giving me UnhandledPromiseRejectionWarning .I would want to release the connection back to the pool or end it once data is inserted.

client.query(format(query, values), (err, res) => {
          if (err) {
            console.error(err, res);
            client.release();
          } else {
            console.log('POSTGRES DATA INSERTED SUCCESSFULLY');
            //  client.end();
            client.release();
          }
        });



from Not able to release postgres client using npm-postgres

PyTorch autocomplete in Sublime Text 3

I'm a fan of Sublime Text 3 and would like to get code autocompletion for PyTorch. However, I can't get this working yet. Any suggestions or starting points where I can begin to get this working?

I have searched in the packages repository of Sublime Text but unfortunately there's none.

Note: I have looked at a related question here IDE autocomplete for pytorch but that's only for VS Code.



from PyTorch autocomplete in Sublime Text 3

How to get the web data using requests and pyqt5?

I want to get the data from http://www.sse.com.cn/assortment/stock/list/info/announcement/index.shtml

You can see five boxes. I would like to input the information as shown in the figure. enter image description here

I tried to use requests

url = r'http://www.sse.com.cn/assortment/stock/list/info/announcement/index.shtml'
payload = {'inputCode': '600000', 'single_select_2':'DQGG', 'start_date': '2018-06-01', 'end_date':'2019-01-23'}
response = requests.post(url, data = payload)

However, I cannot get the correct result.

What should be the correct approach?

How to do it using pyqt5?



from How to get the web data using requests and pyqt5?

LSTM autoencoder always returns the average of the input sequence

I'm trying to build a very simple LSTM autoencoder with PyTorch. I always train it with the same data:

x = torch.Tensor([[0.0], [0.1], [0.2], [0.3], [0.4]])

I have built my model following this link:

inputs = Input(shape=(timesteps, input_dim))
encoded = LSTM(latent_dim)(inputs)

decoded = RepeatVector(timesteps)(encoded)
decoded = LSTM(input_dim, return_sequences=True)(decoded)

sequence_autoencoder = Model(inputs, decoded)
encoder = Model(inputs, encoded)

My code is running with no errors but y_pred converge to:

tensor([[[0.2]],
        [[0.2]],
        [[0.2]],
        [[0.2]],
        [[0.2]]], grad_fn=<StackBackward>)

Here is my code:

import torch
import torch.nn as nn
import torch.optim as optim


class LSTM(nn.Module):

    def __init__(self, input_dim, latent_dim, batch_size, num_layers):
        super(LSTM, self).__init__()
        self.input_dim = input_dim
        self.latent_dim = latent_dim
        self.batch_size = batch_size
        self.num_layers = num_layers

        self.encoder = nn.LSTM(self.input_dim, self.latent_dim, self.num_layers)

        self.decoder = nn.LSTM(self.latent_dim, self.input_dim, self.num_layers)

    def init_hidden_encoder(self):
        return (torch.zeros(self.num_layers, self.batch_size, self.latent_dim),
                torch.zeros(self.num_layers, self.batch_size, self.latent_dim))

    def init_hidden_decoder(self):
        return (torch.zeros(self.num_layers, self.batch_size, self.input_dim),
                torch.zeros(self.num_layers, self.batch_size, self.input_dim))

    def forward(self, input):
        # Reset hidden layer
        self.hidden_encoder = self.init_hidden_encoder()
        self.hidden_decoder = self.init_hidden_decoder()

        # Reshape input
        input = input.view(len(input), self.batch_size, -1)

        # Encode
        encoded, self.hidden = self.encoder(input, self.hidden_encoder)
        encoded = encoded[-1].repeat(5, 1, 1)

        # Decode
        y, self.hidden = self.decoder(encoded, self.hidden_decoder)
        return y


model = LSTM(input_dim=1, latent_dim=20, batch_size=1, num_layers=1)
loss_function = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.0001)

x = torch.Tensor([[0.0], [0.1], [0.2], [0.3], [0.4]])

while True:
    y_pred = model(x)
    optimizer.zero_grad()
    loss = loss_function(y_pred, x)
    loss.backward()
    optimizer.step()
    print(y_pred)



from LSTM autoencoder always returns the average of the input sequence

web2py: detect change in dropdown widget

How can we detect a change from a dropdown widget so that code can be executed?

Table loan references table services. Both have field called interest_rate. When I change loan.service via dropdown I'd like to reflect the corresponding interest_rate from services table to loan table.

How can this be achieved?

model

db.define_table('services',
                Field('service_name',requires=[IS_NOT_EMPTY(),IS_NOT_IN_DB(db,'services.service_name')]),
                Field('service_type','reference service_types',requires=IS_IN_DB(db,db.service_types.id,
                                                                                '%(type_name)s',
                                                                                error_message='not in table',
                                                                                zero=None),
                                                                                ondelete='RESTRICT',
                                                                                ),
                Field('interest_rate','decimal(15,2)',requires=IS_DECIMAL_IN_RANGE(0,100)),
                Field('max_term','integer'),
                auth.signature,
                format='%(service_name)s',
    )

db.define_table('loan',
    Field('service','reference services',requires=IS_IN_DB(db,db.services.id,
                                            '%(service_name)s',
                                            error_message='not in table',
                                            zero=None),
                                            ondelete='RESTRICT',),
    Field('member_id','reference members',requires=IS_IN_DB(db,db.members.id,
                                            '%(member_name)s',
                                            error_message='not in table',
                                            zero=None),
                                            ondelete='RESTRICT',
                                            label='Member'),
    Field('amount','decimal(15,2)',requires=IS_DECIMAL_IN_RANGE(1000)),
    Field('interest_rate','decimal(6,2)',default=10),
    )   



from web2py: detect change in dropdown widget

web2py: detect change in dropdown widget

How can we detect a change from a dropdown widget so that code can be executed?

Table loan references table services. Both have field called interest_rate. When I change loan.service via dropdown I'd like to reflect the corresponding interest_rate from services table to loan table.

How can this be achieved?

model

db.define_table('services',
                Field('service_name',requires=[IS_NOT_EMPTY(),IS_NOT_IN_DB(db,'services.service_name')]),
                Field('service_type','reference service_types',requires=IS_IN_DB(db,db.service_types.id,
                                                                                '%(type_name)s',
                                                                                error_message='not in table',
                                                                                zero=None),
                                                                                ondelete='RESTRICT',
                                                                                ),
                Field('interest_rate','decimal(15,2)',requires=IS_DECIMAL_IN_RANGE(0,100)),
                Field('max_term','integer'),
                auth.signature,
                format='%(service_name)s',
    )

db.define_table('loan',
    Field('service','reference services',requires=IS_IN_DB(db,db.services.id,
                                            '%(service_name)s',
                                            error_message='not in table',
                                            zero=None),
                                            ondelete='RESTRICT',),
    Field('member_id','reference members',requires=IS_IN_DB(db,db.members.id,
                                            '%(member_name)s',
                                            error_message='not in table',
                                            zero=None),
                                            ondelete='RESTRICT',
                                            label='Member'),
    Field('amount','decimal(15,2)',requires=IS_DECIMAL_IN_RANGE(1000)),
    Field('interest_rate','decimal(6,2)',default=10),
    )   



from web2py: detect change in dropdown widget

How to group chat messages per user?

I have a group chat message build using Vue.js. I am currently fetching the messages which returns an array like this:

"data":[
    {
        "id":1,
        "message":"<p>yo<\/p>",
        "removed":"false",
        "user":{
            "uid":2,
            "metadata":{
                "username":"Testing"
            }
        },
        "post_date":"2018-02-24 14:30"
    },
    {
        "id":2,
        "message":"<p>test<\/p>",
        "removed":"false",
        "user":{
            "uid":1,
            "metadata":{
                "username":"Admin"
            }
        },
        "post_date":"2018-02-24 22:31"
    },
    {
        "id":3,
        "message":"<p>Wassup?<\/p>",
        "removed":"false",
        "user":{
            "uid":1,
            "metadata":{
                "username":"Admin"
            }
        },
        "post_date":"2018-02-24 22:40"
    },
    {
        "id":12,
        "message":"again for testing post date",
        "removed":"false",
        "user":{
            "uid":1,
            "metadata":{
                "username":"Admin"
            }
        },
        "post_date":"2018-03-04 00:59"
    },
    {
        "id":13,
        "message":"Hello!",
        "removed":"false",
        "user":{
            "uid":2,
            "metadata":{
                "username":"Testing"
            }
        },
        "post_date":"2018-03-04 11:13"
    },
    {
        "id":13,
        "message":"<p>Hi!</p>",
        "removed":"false",
        "user":{
            "uid":2,
            "metadata":{
                "username":"Testing"
            }
        },
        "post_date":"2018-03-04 11:13"
    },
],

At the moment I am just looping through the data and outputting each message into a separate div. What I would prefer is to group the messages when the same user has posted more than once in a row.

How would I go about this? Should it be an option server side (maybe an optional group parameter?) or somehow done client side?

EDIT This is how the chat current looks: How the chat currently looks

And this is the desired look: Desired chat look

The problem if I group them by the UID/Username, is that the messages need to be output in order. So if User 1 send three messages, then User 2 send two, then User 1 sends another message, all of user 1s message will be grouped together. Rather the User 1s three messages should be grouped, then User 2s, then it should show User 1s last message.



from How to group chat messages per user?

Android animate and resize Fragment on drag

I have an Activity that holds a Fragment and other Views. When showing the Fragment, it is shown as full screen (match_parent). The behavior I am looking for is dragging the Fragment down to minimize it so it appears as a floating view with a height of 100dp on top of the Activity (check YouTube player animation as a reference).

Also, child views need to change position depends on if Fragment is fullscreen or floating mini state

Since I have little to no experience on advanced view animations. Would love to get some references or code samples on how to achieve this.

For now, I am trying to achieve this using GestureDetectorCompat while manipulating the ViewGroup LayoutParams.



from Android animate and resize Fragment on drag

Disabling source output in python unittest stack traces

The unittest framework in python outputs a stack trace when you encounter an exception. Each line of the stack trace is accompanied by source code in the output. This causes the stack trace to be hundreds of lines of scrolling and, in my opinion, very hard to read.

Is there a way to run a python unittest so that when an exception is caught the stack trace output is in a shortened form? I'd like just the source lines, excluding all the extra source.



from Disabling source output in python unittest stack traces

Admob ad page views much higher than impressions on tablets

I have recently published an app to the Play Store with Admob ads. I noticed something odd today as my page views reported by AdSense were much higher than my impressions (7400 page views vs 1500 impressions). My match rate is still high (90%+) which suggests to me the ad requests are being fulfilled but the ads are not being displayed to the user. I then checked the platform information on AdSense to find that nearly all page views on 'high-end mobile devices' lead to an impression (1800 page views to 1500 impressions) whereas on 'tablets' I have 5600 page views to 13 impressions. This suggests to me that the ads are being displayed fine on mobile phones but barely at all on tablets.

What could be causing this? Are there any additional steps that must be taken to ensure AdMob ads are displayed on tablets as well?

Note: most of my ads appear as interstitials and some banner ads.



from Admob ad page views much higher than impressions on tablets

Wednesday 30 January 2019

using python to execute bcp to export query from remote server to local drive

I have the below python group of statements. I am using dynamic built sql statements using python. the resulting SELECT statement is then used as teh queryout statement in a bcp.

My problem is that the query itself is too large, and BCP is failing to operate it. I have confirmed that bcp works using:

BCP "Select * from <<DATABASE.dbo.TABLE>>" queryout "D:\data\test.csv" -t^ -r '0x0A' 
    -U <<USER>> -P <<PASSWORD>> -S "LIVE" -c -C65001

but if the select statement is large, the statement fails. How can I counter this? The table is large (over 100m records) and all I want to do is use the dynamic SQL to export it from a remote server to a local table.

Python Script:

def getRoster(self):
    self.conn = pyodbc.connect(self.ConnStr)
    sql = r'SELECT * FROM <<DB>>.dbo.TableConfiguration'
    self.roster = pd.read_sql(sql,self.conn)

def GenerateSQL(self, table):
    exportsql = 'select '

    columnsql = """select
                    'CASE WHEN ISNULL('+COLUMN_NAME+', '''') = '''' THEN '''' ELSE '+COLUMN_NAME+' END AS '+UPPER(COLUMN_NAME)
                    from <<DB>>.INFORMATION_SCHEMA.COLUMNS
                    where TABLE_NAME = '%s'
                    order by ORDINAL_POSITION""" % table.tablename
    self.conn = pyodbc.connect(self.ConnStr)
    cursor = self.conn.cursor()
    cursor.execute(columnsql)
    exportsql += ', '.join([field[0] for field in cursor])
    exportsql += ' from {}.dbo.{}'.format(table.dbname, table.tablename)
    exportsql += ' {}'.format(table.Clause)
    return (exportsql)

def ExportTables(self):
    now = datetime.now()
    self.getRoster()
    for row in self.roster.itertuples():
         SQL = self.GenerateSQL(row)
         self.filename = '{}_{}.csv'.format(row.tablename, now.strftime("%Y-%m-%d"))
         command = 'BCP \"{}\" queryout \"{}\" -t|| -U "<<USER>>" -P <<PASSWORD>> -S "LIVE" -T -r 0x0a -c -C65001'.format(SQL, os.path.join(self.path, self.filename))
         print (command)
         subprocess.run(command)



from using python to execute bcp to export query from remote server to local drive

Android library project not using correct resources for debug variant

My problem is much as described in questions such as this: Build variants in Gradle for a Library Project in Android

That is, I'm making a library module with debug and release build types, and each build type has its own resources (for example in strings.xml). However, the release resources are always selected even when building the debug variant.

Pretty much everything I'm reading indicates that this has been fixed in Android Studio 3.0, but I'm on 3.3 and still experiencing the problem. One suggestion I've seen is to use releaseCompile and debugCompile. Those are deprecated so I used the replacements:

debugImplementation project(path: ':myLibrary', configuration: 'debug')
releaseImplementation project(path: ':myLibrary', configuration: 'release')

That produces these errors:

ERROR: Unable to resolve dependency for ':app@myAppDebug/compileClasspath': Could not resolve project :myLibrary.
Affected Modules: app

ERROR: Unable to resolve dependency for ':app@myAppDebugAndroidTest/compileClasspath': Could not resolve project :myLibrary.
Affected Modules: app

ERROR: Unable to resolve dependency for ':app@myAppDebugUnitTest/compileClasspath': Could not resolve project :myLibrary.
Affected Modules: app

I've quadruple checked the spelling, and it matches the name of the library. I was doing this before that resulted in the incorrect behavior described above:

implementation project(':myLibrary')

From the library build file:

android {
    publishNonDefault true
    ...
    buildTypes {
        debug {}
        release {
            minifyEnabled false
            zipAlignEnabled true
            signingConfig signingConfigs.releaseConfig
            //proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    ...

I also have a "qa" build type that I have omitted from discussion, but I have no reason to believe that's relevant as I'm not currently attempting to build that type. Any suggestions, or anything else I should add to the question?



from Android library project not using correct resources for debug variant

Getting high resolution android-resource Uri for Android application icon

I need to get the android-resource uri (of the form android.resource://[package]/[res id]) of an application icon (of any given package). This is passed to another application to set an ImageView using the setImageUri API. However, the image being set is a low resolution version and I would like to know how to get the Uri for the high resolution version.

As a test code, I have 3 ImageViews. The first two, I am setting the image using setDrawable. The third using setImageUri for the same application icon.

package com.test.icontest

import android.content.Context
import android.graphics.drawable.Drawable
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.DisplayMetrics
import android.widget.ImageView

class MainActivity : AppCompatActivity() {

    companion object {
        const val TEST_PACKAGE = "com.washingtonpost.rainbow"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val imageView = findViewById<ImageView>(R.id.iconImage)
        imageView.setImageDrawable(getAppIconDrawable(applicationContext, false))

        val imageView2 = findViewById<ImageView>(R.id.iconImage2)
        imageView2.setImageDrawable(getAppIconDrawable(applicationContext))

        val imageView3 = findViewById<ImageView>(R.id.iconImage3)
        imageView3.setImageURI(getAppIconUrl(applicationContext))

    }

    // Returns the Uri for the android application icon
    fun getAppIconUrl(context: Context): Uri {
        val iconCode = context.packageManager.getApplicationInfo(TEST_PACKAGE, 0).icon

        // Third image below
        return Uri.Builder()
            .scheme("android.resource")
            .authority(TEST_PACKAGE)
            .path(iconCode.toString())
            .build()
    }

    // Returns the Drawable for the android application icon
    fun getAppIconDrawable(context: Context, highRes: Boolean = true): Drawable {
        val applicationInfo = context.packageManager.getApplicationInfo(TEST_PACKAGE, 0)
        val res = context.packageManager.getResourcesForApplication(applicationInfo)

        return if (highRes)
            res.getDrawableForDensity(applicationInfo.icon, DisplayMetrics.DENSITY_XXXHIGH, null) // Second image below
        else
            res.getDrawable(applicationInfo.icon, null) // First image below
    }
}


The result:

First image - set using setDrawable - kinda blurry
Second image - set using setDrawable with DENSITY_XXXHIGH
Third image - set using setImageUri - kinda blurry, but I want this "sharper" like the second image above



from Getting high resolution android-resource Uri for Android application icon

FIRMessaging should be called from main thread only

I am using intel multi-os-engine to build my iOS-app. When trying to setup Firebase Messaging I get the following error:

* Assertion failure in -FIRMessaging teardown, /Users/hpbaxxter/StudioProjects/app/ios/xcode/Pods/FirebaseMessaging/Firebase/Messaging/FIRMessaging.m:374 2019-01-24 15:13:15.988333+0100 SkipAndGo[4195:75192] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRMessaging should be called from main thread only.'

*** First throw call stack: ( 0 CoreFoundation 0x00000000177921bb __exceptionPreprocess + 331 1 libobjc.A.dylib
0x0000000016d30735 objc_exception_throw + 48 2 CoreFoundation
0x0000000017791f42 +[NSException raise:format:arguments:] + 98 3
Foundation 0x0000000013de9940 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 166 4
SkipAndGo 0x000000000b5b512a -[FIRMessaging teardown] + 234 5 SkipAndGo
0x000000000b5b3da3 -[FIRMessaging dealloc] + 195 6 libobjc.A.dylib 0x0000000016d42dcc _ZN11objc_object17sidetable_releaseEb + 202 7
??? 0x0000000044f6ec79 0x0 + 1157033081 ) libc++abi.dylib: terminating with uncaught exception of type NSException

I already read Q&A's like this one here.

This is my Code when setting up FIRMessaging:

Globals.dispatch_async(Globals.dispatch_get_main_queue(), new Globals.Block_dispatch_async() {
            @Override
            public void call_dispatch_async() {
                FIRMessaging.alloc().setDelegate(CLOUDMESSAGES_DELEGTE);
                application.registerForRemoteNotifications();
            }
        }
);



from FIRMessaging should be called from main thread only

GoDaddy Web Hosting with Angular and Microsoft Web API

I have purchased hosting with Go Daddy as well as an ssl cert for my domain. If I want to host a site using Angular for the front end and Microsoft Web Api for the back end, I believe that I need a sub domain, does this mean that I need to purchase a second SSL cert to host the API? Is there a way that both of these can be hosted on the same web site? This is for a simple personal site that I don't want to invest too much money into.



from GoDaddy Web Hosting with Angular and Microsoft Web API

remove .pdf restrictions from php or javascript

I've been using qpdf to remove .pdf restrictions, this can be used throught php like this:

shell_exec('qpdf --decrypt "'.$pdfName.'" unlocked.pdf');

This works well on localhost, but it's impossible to execute on a shared web hosting for security reasons.

So I'm looking for another way to make this work without shell commands.

Is there any solution on PHP or JavaScript languages?



from remove .pdf restrictions from php or javascript

Django admin plugin for scanning table list

Is there any Django Admin plugin, which scans on start the whole schema for table/column list and configures Django Admin for all tables in schema?

I want to make admin panel for non-django application, because there is no better admin panel than Django, but I don't want to sync schema definition between node.js and Django



from Django admin plugin for scanning table list

Issues when attaching and detaching external app from QDockWidget

Consider this little piece of code:

import subprocess
import win32gui
import win32con
import time
import sys
from PyQt5.Qt import *  # noqa


class Mcve(QMainWindow):

    def __init__(self, path_exe):
        super().__init__()

        menu = self.menuBar()

        attach_action = QAction('Attach', self)
        attach_action.triggered.connect(self.attach)
        menu.addAction(attach_action)

        detach_action = QAction('Detach', self)
        detach_action.triggered.connect(self.detach)
        menu.addAction(detach_action)

        self.dock = QDockWidget("Attach window", self)
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock)

        p = subprocess.Popen(path_exe)
        time.sleep(0.5)  # Give enough time so FindWindowEx won't return 0
        self.hwnd = win32gui.FindWindowEx(0, 0, "CalcFrame", None)
        if self.hwnd == 0:
            raise Exception("Process not found")

    def detach(self):
        try:
            self._window.setParent(None)
            # win32gui.SetWindowLong(self.hwnd, win32con.GWL_EXSTYLE, self._style)
            self._window.show()
            self.dock.setWidget(None)
            self._widget = None
            self._window = None
        except Exception as e:
            import traceback
            traceback.print_exc()

    def attach(self):
        # self._style = win32gui.GetWindowLong(self.hwnd, win32con.GWL_EXSTYLE)
        self._window = QWindow.fromWinId(self.hwnd)
        self._widget = self.createWindowContainer(self._window)
        self.dock.setWidget(self._widget)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Mcve("C:\\Windows\\system32\\calc.exe")
    w.show()
    sys.exit(app.exec_())

The goal here is to fix the code so the window attaching/detaching into a QDockWidget will be made properly. Right now the code has 2 important issues.

Issue1

Style of the original window is screwed up:

a) Before attaching (the calculator has a menu bar)

enter image description here

b) When attached (the calculator menu bar is gone)

enter image description here

c) When detached (the menu bar hasn't been restored properly)

enter image description here

I've already tried using flags/setFlags qt functions or getWindowLong/setWindowLong bit I haven't had luck with all my attempts

Issue2

If you have attached and detached the calculator to the mainwindow and then you decide to close the mainwindow you definitely want everything (pyqt process) to be closed and cleaned properly, right now that won't be the case, why?

In fact, when you've attached/detached the calculator to the mainwindow the python process will hold and you'll need to force the termination of the process manually (ie: ctrl+break conemu, ctrl+c cmd prompt)... which indicates the code is not doing things correctly when parenting/deparenting

Additional notes:



from Issues when attaching and detaching external app from QDockWidget

How to mock varible that imported in tested module, and it is not a function parameter (do this with describe.each and on each test change mock value)

I need to test function in my ts-module.

module-to-test.ts

import { config } from './app-config';

export const isSomethingWhatINeedSelector = createSelector(
    firstDependencySelector,
    secondDependencySelector,
    (first, second) => config.key && (first || !second)
);

But I don't want to write many test for this case, and I want to try to use describe.each([[],[],[]]) functionality to reduce number of code lines.

And I need to change config.key on each iteration of describe.each. When I do at the beginning of the test-file something like this:

jest.mock('./app-config', () => ({
    config: {
        key : false,
    },
}));

it works for the whole file and all the tests. I want to make mock inside "test/it" functions to change value of key dynamically.

Now I have that code, that doesn't work as expected

describe.each([
    [
        'should be ....',
        true, false
    ],
    [
        'should be ....',
        false, true
    ],
    /* and etc. ... [], [], [] ... only for questnion here is two params*/
])('Functionality of ...', (
    testTitle = '',
    mockStatusOfConfigKey,
    expected,
) => {
    const state = ... /* initial */

    beforeEach(() => {
        jest.resetModules();
        /*....configuring the state*/
    }); 

    it(testTitle, () => {
        jest.mock('./app-config', () => ({ /*...or doMock(), that don't works*/
           config: {
              key : mockStatusOfConfigKey,
           },
        }));
        expect(isSomethingWhatINeedSelector(state)).toBe(expected);
    });
    });

Any ideas how to make mocks dynamically changable inside test functions? config.key is just true/false



from How to mock varible that imported in tested module, and it is not a function parameter (do this with describe.each and on each test change mock value)

Matplotlib -Close window without explicit mouseclick

The following code displays the following window:

import numpy as np 
import matplotlib.pylab as pl
import matplotlib.gridspec as gridspec
from matplotlib import pyplot as plt 

def plot_stuff(x,y,z):  
    gs = gridspec.GridSpec(3, 1) 
    plt.style.use('dark_background')
    pl.figure("1D Analysis")
    ax = pl.subplot(gs[0, 0]) 
    ax.set_ylabel('X VALUE')
    pl.plot(x, color="red")
    ax = pl.subplot(gs[1, 0]) 
    ax.set_ylabel('Y VALUE')
    pl.plot(y, color="green")    
    ax = pl.subplot(gs[2, :])
    ax.set_ylabel('Z VALUE')
    pl.plot(z, color="blue")
    plt.show()

How do I close the window without an explicit mouse click?

I need to visualize a LOT of data so I'm searching a way to automating the process of opening and closing windows.

I know that plt.show() is a blocking operation and I've tried using the plt.close("all") method as mentioned in the related questions but the window remains there, does not close and I have to close it manually.

I need a simple code for automating the process of opening a window, visualize the data, closing the window after a certain interval of time; and then repeat the procedure in a for loop fashion.



from Matplotlib -Close window without explicit mouseclick

Ajax get request not working in safari with HTTPS

I want to load some template files dynamically with the help of ajax. I have added the ajax $.get method for loading the html files and it's working fine with all browsers except safari browser.

In safari it gives me "Failed to load resource: cancelled" error when first time I open the url. However after I refresh my page again, it loads all the files.

When I open my url with http request instead of https, it can load the template file in first time on safari browser.

This issue only happens when I open the url with https. I have successfully installed the certificate and its working fine with other browser. Even there is no certificate issue in safari as well.

Here is my code

var decorator = {
    init: function (book, cd) {
        this.loadTPL(cd);
    },
        tpl: {
        btnStart: "tpl/startBtn.html",
        interfaceTpl: "tpl/interfaceTpl.html",
        topMenu: "tpl/topMenu.html",
        topMenuItem: "tpl/topMenuItem.html",
    },


    loadTPL: function (cbTpl) {
        var self = this;
        var objTpl = {};

        async.forEachOf(this.tpl, function (value, key, callback) {
            $.get(value, {}, function (data) {
                //alert("Load was performed.");
                //console.log(value, data);
                objTpl[key] = data;
                callback();
            });

        }, function (err, results) {
            if (err) {
                console.log(err);
            }
            self.tpl = objTpl;
            cbTpl(err);
        });

    }
}

Any Idea?



from Ajax get request not working in safari with HTTPS

PocketSphynix is not continuously outputting speech to text as expected

Motivation & back story (No need to read Optional):

I had a working piece of code that would use pocket sphynix and google recognizer together in order to support both menu based voice navigation and also continuous speeh to text.

Therefore the user code navigate the app using their voice if the words that they used matched with a menu item for example:

"Ok atom, start x" "Ok atom, stop x" "Ok atom, do z"

Note: "Ok atom" trigger phrase was found by PocketSphinx, then PocketSphinx killed was canceled and Google voice was used for longer phrases due to better accuracy.

Also if the recognizer did not match it would start continuous speech to text that was sent to backend like a chatbot (handled by google voice):

"Hi my name is dr green thumb.... "What for dinner tonight...."

If there was silence for 10 secs google voice would be canceled & PocketSphinx would be started again for keyword/wakeword trigger = "Ok atom"

**Everything was ok until, I need the actual raw audio bytes also for a backend application. I have search all over stackoverflow and none of the solution work or are realistic for my project.

Then I found that PocketSphinx can give you back the raw data, so I had to factor out the Google voice and ONLY use PocketSphinx**

The Actual Problem:

However after refactor out/removing Google voice recognizer and only using PocketSphinx, because I require easy access to the "raw audio bytes" of the recognition, PocketSphinx keeps hearing its trigger word "ok atom" and not any other words/voice before or after that trigger word!!!

No matter what I say for example "hello", "hi", "1,2,3" , etc... it only hears the trigger "ok atom", see my relevant code snippet:

The code snippet of the AsynTask that sets up the pocket sphynix:

 @Override
        protected Exception doInBackground(Void... params) {
            try {
                SpeechRecognitionService speechService = serviceReference.get();

                Assets assets = new Assets(speechService);


                File assetDir = assets.syncAssets();


                speechService.pocketSphinxRecognizer = defaultSetup()
                        .setAcousticModel(new File(assetDir, "en-us-ptm"))
                        .setDictionary(new File(assetDir, "cmudict-en-us.dict"))
                        // threshold to balance between false +/- (higher is less sensitive, was 1e-45f)
                        .setKeywordThreshold(1e-30f)
                        .getRecognizer();
                speechService.pocketSphinxRecognizer.addListener(listener);

                // create keyword-activation search
                speechService.pocketSphinxRecognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
            } catch (IOException e) {
                return e;
            }
            return null;
        }

The code snippet for pocket sphynix life cycle methods:

private String KWS_SEARCH = "ok atom"; 

private void switchSearch(String searchName) {
            pocketSphinxRecognizer.stop();
            if (searchName.equals(KWS_SEARCH))
                pocketSphinxRecognizer.startListening(searchName);
            else
                pocketSphinxRecognizer.startListening(searchName, 10000);
        }

        private class PocketSphinxRecognitionListener implements edu.cmu.pocketsphinx.RecognitionListener {
            @Override
            public void onPartialResult(Hypothesis hypothesis) {

                try {
                    if (hypothesis != null) {
                        String cmd = hypothesis.getHypstr();

                        Log.d(TAG, "onPartialResult:" + cmd);

                        if (cmd.equalsIgnoreCase(KWS_SEARCH))
                        {

                            handleResults(cmd);
                        }
                        else
                        {
                            sendToBacknedForProcessing(cmd);
                        }

                    }

                }
                catch (NullPointerException exc)
                {
                    exc.printStackTrace();
                }
            }

            @Override
            public void onBeginningOfSpeech() {}

            @Override
            public void onEndOfSpeech() {

                if (!pocketSphinxRecognizer.getSearchName().equals(KWS_SEARCH))
                {
                  switchSearch(KWS_SEARCH);
                }
            }

            @Override
            public void onResult(Hypothesis hypothesis) {


                if (hypothesis != null) {
                    String cmd = hypothesis.getHypstr();
                    Log.d(TAG, "onResult:" + cmd);

                        sendToBacknedForProcessing(cmd);
                }
                }


            @Override
            public void onError(Exception e) {
                Log.e(TAG, "Pocketsphinx encounted an exception: " + e.getMessage());
            }

            @Override
            public void onTimeout() {
                switchSearch(KWS_SEARCH);
            }
        }

I actually followed this popular article (https://www.guidearea.com/pocketsphinx-continuous-speech-recognition-android-tutorial/) step by step but still no correct results.

What I want to do is to support to modes both voice navigation if the right words are recognized else continous specch to text that is sent to the backend.

Thanks a million!



from PocketSphynix is not continuously outputting speech to text as expected

LLSimpleCamera : AVAssetWriterInput appendSampleBuffer crashing

I am using LLSimpleCamera for recording a video. It's recording fine when I use rear camera but when I switch to front camera, app crashes and the error reported is

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[AVAssetWriterInput appendSampleBuffer:] Media type of sample buffer must match receiver's media type ("soun")'

I have tried many of the stackOverflow posts but not able to fix crash. Can anyone let me know what can be the issue ?



from LLSimpleCamera : AVAssetWriterInput appendSampleBuffer crashing