text:
Q: Javascript Linked List merge returning undefined Trying to merge two sorted list question from LeetCode, keep running into undefined result:
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    var res = new ListNode();
    var curr = res;
    while(l1 !== null && l2 !== null) {
        if(l1.val <= l2.val) {
            // Set current node to l1 if less than or equal
            curr = l1;
            // Move l1's head to next
            l1 = l1.next
        } else {
            // Else same case for l2
            curr = l2;
            l2 = l2.next;
        }
        // Move current to next
        curr = curr.next
    }

    if (l1 !== null) {
        curr = l1;
    } else if (l2 !== null) {
        curr = l2;
    }

    return res;
};

Not sure why res is returning undefined. From what I can tell, I'm setting res to be the head pointer for the resulting linked list nodes and performing the following logic:
While L1 or L2 has not reached its end, compare values.IF L1.val is less than or equal to L2.val, set it to the current node, then bump up the pointer for L1 to the next value.
ELSE do the mirror for L2.
Once the current node value is set, bump up the node to the next item (either L1.next or L2.next, which will be overridden by the next larger value from either of the lists) and repeat.
Once we reach the end of either L1 or L2, set the remaining linked list to the current node, then return the head res pointer of the full list.
Not sure where I'm going wrong here with the logic, maybe it's getting a little late haha. Apologies if this has been repeated, appreciate any help!

A: When you are doing current = res it updates the reference current is holding from res to l1/l2. To avoid this, what you want to do is to set the next node of current instead of the variable current  itself. The following code works -
var mergeTwoLists = function(l1, l2) {
    var res = new ListNode();
    var curr = res;
    while(l1 !== null && l2 !== null) {
        if(l1.val <= l2.val) {
            // Set current node to l1 if less than or equal
            curr.next = l1;
            // Move l1's head to next
            l1 = l1.next
        } else {
            // Else same case for l2
            curr.next = l2;
            l2 = l2.next;
        }
        // Move current to next
        curr = curr.next
    }

    if (l1 !== null) {
        curr.next = l1;
    } else if (l2 !== null) {
        curr.next = l2;
    }

    return res.next;
};

A: I could be wrong but it looks like you're making a copy of res into curr. Unless you're doing it by reference, it should treat those separately. Meaning all changes you're making to curr are not being reflected on res.


text:
Q: Javascript - setTimeout Closure Issue I'm struggling with the code below. I have tried many different ways of doing this but I end up with one of two incorrect results.
for(i = 0; i < result.length; i++) {

    var tmpBlockInfo = {
        size: worldTest.data[0].size,
        xStartPixel :  result[i].x * worldTest.data[0].size,
        yStartPixel : result[i].y * worldTest.data[0].size,
        blockType : (Math.random() * 100 > 10) ? 'path' : 'wall'
    }

    var tmpFunc = function(){
        worldTest.fillBlock(tmpBlockInfo, 157, 152, 124,  255)
    };

    var t = setTimeout(function(){
        tmpFunc()
    } , 500 * i);
}

The problem with the above code is tmpBlockInfo always gets the last result[i].x / result[i].y. So i'm asuming when the timeout runs the function its seeing what result[i].x / result[i].y was left on after the loop (rather than passing it as a "new" variable)
I thought putting it into a function would fix the closure problem, but no luck.
Also tried:
for(i = 0; i < result.length; i++) {

    var tmpBlockInfo = {
        size: worldTest.data[0].size,
        xStartPixel :  result[i].x * worldTest.data[0].size,
        yStartPixel : result[i].y * worldTest.data[0].size,
        blockType : (Math.random() * 100 > 10) ? 'path' : 'wall'
    }

    var t = setTimeout(function(){
        worldTest.fillBlock(tmpBlockInfo, 157, 152, 124,  255)
    } , 10000 * i);
}

With the same results as the first code.
If I do:
for(i=0; i < result.length; i++) {

    var tmpBlockInfo = {
        size: worldTest.data[0].size,
        xStartPixel :  result[i].x * worldTest.data[0].size,
        yStartPixel : result[i].y * worldTest.data[0].size,
        blockType : (Math.random() * 100 > 10) ? 'path' : 'wall'
    }

    setTimeout(function(passBlockInfo) {
        worldTest.fillBlock(tmpBlockInfo, 157, 152, 124,  255)
    } (tmpBlockInfo), 1000 * i);
}

It does process all the fillBlock functions correctly. BUT it does them all at the same time (e.g. it's not firing them one at a time. It's just doing them after each other but causing blocking (no screen update) and no delay between each one.
Any help with this would be great!

A: The reason is it is executing them right away is because you are executing the function in the setTimeout call.  What i would do is create another function like so
function MakeTimeoutCall(fn, data, timeout){
    setTimeout(function() {fn.call(null, data);}, timeout);
}

Then in your loop where you call setTimeout, do this
MakeTimeoutCall(
    function(passBlockInfo){
       worldTest.fillBlock(passBlockInfo, 157, 152, 124,  255);
    },
    tmpBlockInfo,
    1000 * i);

(Assuming worldTest is a global object).
That should work.  setTimeout is expecting a function to call at the end of the timeout, you are giving your function, but calling it right away.  The return value, in this case null, is then given to the timeout.  So there is no timeout, everything happens at once.
Just in case my answer is a little complicated given the context, here is a link to a simpler solution in jsfiddle.

A: Try this:
for(i = 0; i < result.length; i++) {
    var tmpBlockInfo = {
        size: worldTest.data[0].size,
        xStartPixel :  result[i].x * worldTest.data[0].size,
        yStartPixel : result[i].y * worldTest.data[0].size,
        blockType : (Math.random() * 100 > 10) ? 'path' : 'wall'
    }
    var t = setTimeout(createFillBlockFn(tmpBlockInfo) , 500 * i);
}

function createFillBlockFn(blockInfo) {
    return function() {
        worldTest.fillBlock(blockInfo, 157, 152, 124,  255)
    }
}

A: You need a wrapping function to retain scope.  This is just one of few ways to do that.
for(i=0; i < result.length; i++) {

    setTimeout(function () {

        var tmpBlockInfo = {
            size: worldTest.data[0].size,
            xStartPixel :  result[i].x * worldTest.data[0].size,
            yStartPixel : result[i].y * worldTest.data[0].size,
            blockType : (Math.random() * 100 > 10) ? 'path' : 'wall'
        };

       return function () {
           worldTest.fillBlock(tmpBlockInfo, 157, 152, 124,  255);
       };
    }(), 1000 * i);
}

A: This code will help you:
for(i=0; i < result.length; i++)
{
    setTimeout(function(){
        {
            size: worldTest.data[0].size,
            xStartPixel :  result[i].x * worldTest.data[0].size,
            yStartPixel : result[i].y * worldTest.data[0].size,
            blockType : (Math.random() * 100 > 10) ? 'path' : 'wall'
        }, 157, 152, 124,  255);
    } , 500 * i);
}

The variables are declared at the top of the function, so you have one var tmpBlockInfo, ont tmpFunc, and those variables you reassigning.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML not working when opened from file, works from ftp server I am trying to write html and css for a web page, but it doesn't show anything when I open the file directly from the file. It works fine when I access it through my ftp server, even from the same pc and browser. I have tried searching google for solutions, but I wasn't able to find anything
Errors image
Working image
index.html:
<!DOCTYPE html>

<link rel="stylesheet" href="style.css">

<meta charset="utf-8">
<title>Employee Page</title>

header.html

 Home

 Calendar

 Contacts

            File Server

                Documents
                GameFiles
                Videos

style.css
.menu {
width: 100%;
vertical-align:top;
height:25px;
float: top;
 }

ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}

li {
float: left;
font-size: 16px;
display:inline-block;
}

li a, .dropbtn {
display: inline-block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
background-color: red;
}

li.dropdown {
display: inline-block;
}

.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}

.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {

display: block;
}

Any help is appreciated. Thanks!

A: Typical issue for local development is open content just like file in browser:
file:// ...

and then with some dynamic elements you can get error:
XMLHttpRequest cannot load file:/// ... Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Solution is install web server on your local machine and open through http(s) protocol - eg. NGINX, Apache or use online service for that like WebCloud.
See woking example on http here.
I hope I helped.

A: First of all, it appears that your navigation is using absolute linking.

 Home

 Calendar

 Contacts

Furthermore, you can bring up you console, see what parts of your website refuse to load at all and change the routing.
EDIT
You cannot load these resources clearly for security reasons. Running pages through file:// protocol have disabled a lot of features because security issues. You can always create a javascript server using Node.js and host it locally without installing apache or something similar.
https://nodejs.org/en/

A: Try to check if the other files are in the same folder  with index.html. The problem probably is that it cant find locally the other files.
To be sure you can copy all the files in a directory(for example Desktop) and then try again.


text:
Q: Relógio em JavaScript não atualiza Estou criando uma view que irá mostrar o horário de um servidor da rede e estou usando JS para obter a data e hora atual do servidor, que por ventura vem a divergir com o horário atual, estando em algumas situações atrasado alguns minutos.
Para exibir um relógio na tela e o manter atualizando-se, usei o script abaixo:

Porém, se ao declarar e instanciar a variável date passando valores simulando o horário recebido do servidor com hora atrasada, o script não consegue mantém o horário atualizando-se.
Segue exemplo abaixo:

Não entendi o motivo do relógio com horário atrasado ser impedido de manter-se atualizando na tela. Poderiam me ajudar? Busquei algumas perguntas e não tive nada parecido no resultado das minhas buscas feitas.
Obrigado!!

A: Ao definir valores fixos no objeto Date() dentro da função, os valores serão sempre os mesmos. Já o Date() sem valores, irá retornar a data atualizada do sistema.
O que você pode fazer é declarar o objeto fora da função, e dentro dela incrementar 1 segundo com o método .setSeconds(), mas eu sugiro usar um nome mais específico para a variável e não apenas d, já que será uma variável com um escopo global (no caso, eu coloquei relogio):

setInterval(geraIntervalo, 1000);
var relogio = new Date(2019, 01, 30, 03, 14, 15), displayDate;
function geraIntervalo() {
   relogio.setSeconds(relogio.getSeconds() + 1);
   document.getElementById("horaServidor").innerHTML = relogio.toLocaleTimeString('pt-BR');
}


text:
Q: Get Session for Forms in Django I'm working on a single page to handle all stufs related to accounts such as login/register. For that i'm using a CBV with a multiforms.py that do the get,post,validations etc.
I'm having a problem with the login form, that is saying 'LoginForm' object has no attribute 'session'
current error
How i can get the session to use on the authenticate system ?
Here are the multiforms.py
class ProcessMultipleFormsView(ProcessFormView):

    def get(self, request, *args, **kwargs):
        form_classes = self.get_form_classes()
        forms = self.get_forms(form_classes)
        return self.render_to_response(self.get_context_data(forms=forms))

    def post(self, request, *args, **kwargs):
        form_classes = self.get_form_classes()
        form_name = request.POST.get('action')
        if self._individual_exists(form_name):
            return self._process_individual_form(form_name, form_classes)
        elif self._group_exists(form_name):
            return self._process_grouped_forms(form_name,form_classes)
        else:
            return self._process_all_forms(form_classes)

    def _individual_exists(self, form_name):
        return form_name in self.form_classes

    def _group_exists(self, group_name):
        return group_name in self.grouped_forms

    def _process_individual_form(self, form_name, form_classes):
        forms = self.get_forms(form_classes, (form_name,))
        form = forms.get(form_name)
        if not form:
            return HttpResponseForbidden()
        elif form.is_valid():
            return self.forms_valid(forms, form_name)
        else:
            return self.forms_invalid(forms)`

my LoginForm:
class LoginForm(MultipleForm,forms.Form):

    email = forms.EmailField(max_length = 60)
    password = forms.CharField(widget=forms.PasswordInput())`

and the views.py:
def login_valid(self,request):

    user = authenticate(email=request.data.get('email'),password=request.data.get('password'))
    if user is not None:
        login(request,user)

         return HttpResponseRedirect(self.get_success_url('login'))

    else:
          return render(request,'accounts/login.html')`

I already tried alot stufs but still dont get why this error is happening


text:
Q: Is there any way to get public event informations from Facebook? I know since Cambridge Analytica facebook API has suspended some endpoints. But I need facebook public events informations for a project. The informations I need are:

*

*Event Name

*Date and Time

*Cover photo

*Description

*Event URL

*Address

*Event ID

*Page ID

I'm doing a project for a client. It will request those data from server side and save it in database. Then it will show available events in a community website for specific locations. We don't need data about attendee list or their post on the wall. My client is willing to go through app review process. Question is does Facebook sdk provide those informations? Reading the documentation, my understanding is it only provide event informations that are attended by me or created in a page in which I'm an admin.
Is there any way to get these information? Let me be clear, I'm talking about public events. Not the one created by me or by my page.
Thank you in advance.

A: Just to be 100% sure, I just tried to access events of a Page I don´t own, with a live App that has Page Public Content Access approved, and did not get the events. (Tested with the /page-id/events endpoint.)
The docs tell you that accessing Page events is not possible in any case:

This is a restricted edge. You cannot request access at this time.

Source: https://developers.facebook.com/docs/graph-api/reference/page/events/


text:
Q: Why does a query with an IN (subquery) take longer than a query with IN (discrete list) This has always bugged me, why does this query
SELECT
  *
FROM
  `TABLE`
WHERE `value` IN
  (SELECT
    val
  FROM
    OTHER_TABLE
  WHERE `date` < '2014-01-01')

run orders of magnitude slower than sequentially running both this query
SELECT
  `val`
FROM
  OTHER_TABLE
WHERE `date` < '2014-01-01'

Result:
+----+
| val |
+-----+
| v1  |
| v2  |
| v3  |
| v7  |
| v12 |
+-----+

and this query:
SELECT
  *
FROM
  `TABLE`
WHERE `value` IN ('v1', 'v2', 'v3', 'v7', 'v12')

A: From the docs: (emphasis added by me)

Subquery optimization for IN is not as effective as for the = operator
  or for the IN(value_list) operator.
A typical case for poor IN subquery performance is when the subquery
  returns a small number of rows but the outer query returns a large
  number of rows to be compared to the subquery result.
The problem is that, for a statement that uses an IN subquery, the
  optimizer rewrites it as a correlated subquery. Consider the following
  statement that uses an uncorrelated subquery:
SELECT ... FROM t1 WHERE t1.a IN (SELECT b FROM t2);
The optimizer rewrites the statement to a correlated subquery:
SELECT ... FROM t1 WHERE EXISTS (SELECT 1 FROM t2 WHERE t2.b = t1.a);
If the inner and outer queries return M and N rows, respectively, the
  execution time becomes on the order of O(M×N), rather than O(M+N) as
  it would be for an uncorrelated subquery.
An implication is that an IN subquery can be much slower than a query
  written using an IN(value_list) operator that lists the same values
  that the subquery would return.

http://dev.mysql.com/doc/refman/5.7/en/subquery-restrictions.html
Hopes this helps anyone else who might have been curious


text:
Q: how to setup ssh tunnel to named virtual host running Jenkins I'm currently setting up server inside our lab at Uni that will be used for multiple purposes including a bibliography database and a CI Server (Jenkins).  In order to maintain clean separation of concerns, I have a jailed Virtual Host (VH) for each function along with an assigned internal domain name.  Inside the lab, the arrangement works fine.  I've installed BIND9 on the server, so it is able to resolve domain names.
However, in order to connect to our lab from home, we need to first VPN into the Uni and then SSH into our lab's gateway machine. From the gateway we can access any internal machines we need to reach.  Once logged into the gateway, we use SSH Tunnels as needed.  Machines inside our lab cannot be directly accessed from the VPN without logging into the gateway as per the University's policy.
I'm wondering if it is possible to access virtual hosts through a single SSH tunnel?  Like Server Name Indication (SNI)? Or would I need to setup a proxy server like Squid?  I gather that both DNS as well as HTTP traffic would need to be routed correctly.  Can this be done using just hosts file settings?
Any advice would be much appreciated.  Thanks!
Update
I have continued working on the problem and have a solution that seems to work, but still has one remaining flaw; Jenkins, on the Manage page when using VPN/SSH, is complaining It appears that your reverse proxy set up is broken.  Thus, whilst my requests are correct, some of my responses are not, and I would like to fix this.
The short answer is to use a reverse proxy server located on the remote machine that forwards requests to the localhost ports that are being tunnelled.  The solution involved the following:
1) Since SNI is not available, it is possible in this case to assign an additional unique port to be listened to for each Virtual Host.  I've chosen to use the 808x upwards range.
2) I updated the stanza in the SSH config file on my local machine which I use to connect to the gateway machine to include forwarding of all these ports.
3) I have configured a local reverse proxy on my local machine (using Apache2 in my case) to allow me to refer to each port using a domain name, thus forwarding the requests to http://localhost:808x.  For the local VH's, I chosen to use the .vpn TLD to mark these as domain names for use when using VPN to connect to the lab.  Thus I can use the normal .int domain name when I'm in the lab without any conflicts.
Overall, this solution seems to work well.  Whilst there is an option to dismiss the error, I would like to fix it because, after reading through the documentation, it's unclear to me what the consequences would be of simply dismissing it.
So my question is now very Jenkins oriented, so I've included below the various configuration files I've setup.  I'm wondering what I may have miss-configured in my reverse proxies, or whether I need to use mod_rewrite.  Any advice would be appreciated.
SERVER SIDE
I have mod_proxy, mod_proxy_http, and mod_headers enabled.
I've only shown the changes I've made to the default files.
ports.conf
Listen 80
### TOMCAT is running on 8081
Listen 8082
Listen 8083

jenkins.int.vhost
<VirtualHost *:80 *:8081 *:8083>

        ServerName        jenkins.int
        ProxyRequests     Off
        ProxyPreserveHost On
        AllowEncodedSlashes NoDecode

        <Proxy http://localhost:8081/*>
          Order deny,allow
          Allow from all
        </Proxy>

        ProxyPass         /  http://localhost:8081/ nocanon
        ProxyPassReverse  /  http://localhost:8081/
        ProxyPassReverse  /  http://jenkins.int/

#       Header edit Location ^http://jenkins.vpn http://jenkins.int
</VirtualHost>

/etc/defaults/jenkins
# port for HTTP connector (default 8080; disable with -1)
HTTP_PORT=8081
JENKINS_ARGS="--webroot=/var/cache/$NAME/war --httpPort=$HTTP_PORT"

/var/lib/jenkins/jenkins.model.JenkinsLocationConfiguration.xml
<jenkinsUrl>http://jenkins.int/</jenkinsUrl>

/var/lib/jenkins/jenkins.CLI.xml
<jenkins.CLI>
  <enabled>true</enabled>
</jenkins.CLI>

This above is needed to enable scripts to run.
CLIENT SIDE
/etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>

    ServerName biblio.vpn

    ProxyPass / http://localhost:8082/

</VirtualHost>

<VirtualHost *:80>

    ServerName jenkins.vpn
    ProxyRequests Off
    ProxyPreserveHost On
    AllowEncodedSlashes NoDecode

    ProxyPass / http://localhost:8083/
    ProxyPassReverse / http://localhost:8083/
    ProxyPassReverse / http://jenkins.int/

</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

SSH config file
LocalForward localhost:8080 server.local:8080
LocalForward localhost:8081 server.local:8081
LocalForward localhost:8082 server.local:8082
LocalForward localhost:8083 server.local:8083

Update 2
After speaking with some helpful Jenkins users on IRC, I came to the conclusion that the broken reverse proxy error/warning could be dismissed in our case.
One last, minor but nuisance issue was that the "New View" link pointed to the wrong address ("jenkins.int" instead of "jenkins.vpn"). Editing core/src/main/java/jenkins/model/NewViewLink.java and replacing Jenkins.getInstance().getRootUrl() with "/" in line 47, then rebuilding Jenkins and uploading the WAR file, fixed this problem.

A: Find out the organization's reasons for the policy of tunneling you through the gateway machine when you already are tunneled into a VPN.

*

*A test network dangerous to the production network could be a reason, but a content database and a CI/CD system is hardly dangerous.

*Proprietary information not for all users may need to be secured. But this otherwise could be done with authentication on all systems. Maybe a data loss prevention solution if the data is extremely sensitive or valuable.

If the firewall allowed it, you could set up front end load balancers or proxies outside the lab. Proxy user connections on web apps and such to backends and databases inside the network. Classic design for "external" facing applications.
If you must tunnel, route the lab subnet through the tunnel rather than forward individual ports with ssh. Also, VPN direct from the Internet to this lab network would be easier to use. Tunnel within a tunnel is possible, but writing a config a less technical user can use might get tricky, between any routing required and possibly multiple different VPN clients.


text:
Q: how to pass parameters in sqlite transaction in cordova I have a bookid and i need to pass it on sqlite transaction in cordova
like

var bookName  = db.transaction(function(tx){
                    return tx.executeSql('SELECT * FROM Iqra_Book WHERE book_id=?',[1],function(tx,res){
                        var leng = res.rows.length;
                        console.log("Length: " + leng);
                        return bkName = res.rows.item(0).book_name;
                    }
                , function(e) {
                    return console.log("ERROR: " + e.message);
                });
            });

But I am getting this booName as undefined.
Can anyone help me out ?

A: you need to pass a variable to the book id. leave away the "return", you cant just return a value since the web database works asynchrounously
tx.executeSql('SELECT * FROM Iqra_Book WHERE book_id ="'+id+'"',[1],function(tx,res){

also, change the line
return bkName = res.rows[0].book_name;

to
return bkName = results.rows.item[0].book_name;

and check if it works

A: You should be using the values parameter of the executeSql() method.
eg.
let id = //the ID of the item you are looking for
tx.execute('SELECT * FROM Iqra_Book WHERE book_id=?',[id])
     .then(queryResult => {
       console.log(queryResult.rows.item(0).book_name)
     }).catch(err => console.error(`ERROR: ${JSON.stringify(err)}`);

NOTE

*

*item() is a function - you have that right, it cannot be accessed as an array as is shown in the previous answer (I hate that about the plugin, but that is how it is)

*the values passed in the previous example is just 1, so I hope the ID you wanted was 1.

*queryResult.rows is a list-like object, I would recommend going through a for-loop with the limit of queryResult.rows.length unless (like in this case) you know for sure there is only going to be 1 result.


text:
Q: Checking if two WGS84 lines intersect in JavaScript I am trying to work out given two GeoJSON lines (WGS84), if they intersect (i.e. cross one another). Let me give some pseudocode to illustrate:
// Providing Line 1 = lon1, lat1 and Line 2 = lon2, lat2
function linesIntersect(lon1, lat1, lon2, lat2) {

    var intersectionCheck = mathsToDoGeodesicIntersectionChecking()
    // This could be an external library or another code sample

    return intersectionCheck; // Return a boolean with true or false

}

The code samples I have tried are to long winded to post in the question, but you can see in the following GitHub repo (open line-crosses.html in a browser and open the dev tools to see some tests run).
It appears that the popular library Turf.js does not have a line intersect function. I am keen to make sure that the lines be created geodesically and checked in the same fashion (i.e. accounting for the curvature of the Earth rather).
The operation seems comparatively simple in a projected coordinate system scenario. I have a script (based off of code for in the comments of this post) that converts the lines coordinates to Web Mercator and checks for intersection, however I am uncertain as to the issues this may cause.
The code provided by moveable-type appears to get very close but unfortunately seems to check entire line paths and not line segments you provide (i.e. will these two lines ever intersect at their current bearings). Similarly GeographicLib looks like it may be able to help but I am struggling to find the solution using the library.
I am not specifically interested in where they intersect but more if they do. It would also be highly beneficial if they could handle discontinuity, as in to say  to be able to handle a line that starts at a latitude of -179 and ends in at latitude 179 (see here for more explanation of what I mean).

A: If the endpoints of your segments are within 5000 km of each other, then
pick some suitable midpoint (e.g., the point halfway between the 2
midpoints), and use this as the center of projection for GeographicLib's
gnomonic projection.  Map the two line segments into this projection and
solve the resulting 2d intersection problem.  This will give you a good
idea whether or not the segments intersect.  To get more accuracy repeat
with a new center of projection at the intersection point (extending the
segments if necessary).  Repeat this enough times and you get an exact
answer.  I have code posted to do this here.  (There's no discontinuity
at longitude = ±180° with this method.)


text:
Q: Android: 9-patch png is treated like a normal png I've made this 9-patch png and added it to the res/drawable folder:

It works nice in the example eclipse shows:

But on the emulator it looks messed up:

Why is this happening and how can I fix this?
EDIT: The border on which I've placed the black dots is white, not transparent. Not sure if that's got anything to do with it...

A: This probably happens because you have a small mistake with the black pixels you have set.
Try to re-cut the edges of the picture and to add the black pixels all over again.
I had this problem too once and this helped me.
if the border is white then this is your problem it has to be pure black or nothing at all.
UPDATE: Try this image:

A: It seems you are not saved your image with .9.png
In order to make it work do like this
save your image in the following format in your drawable folder
yourimage.9.png (not png format of your image)
Check this reference draw 9 patch

A: The Android SDK contains a 9-patch editing tool (draw9patch.bat) that can help you to produce and/or validate 9-patch images.  Without it, it is very easy to make a mistake in defining your border.
The one-pixel border should be transparent except for the black pixels that define the various parts of the image to be treated differently during scaling.


text:
Q: Form password field is plain text after using jQuery serialize() I have a login form includes password field. I show this login form in modal way and I would like to handle the form submit response is a special way(actually update the login bar to a account menu), so i prevent the default form submit by
$("#myformid").submit(function(event){
   var form = $(this);
   console.log(form.serialize());
   event.preventDefault();
   jQuery.ajax({
      url: "http://localhost:5782/login",
      success: function (data) {
        login_form_modal.style.display = 'none';
      },
      data: {
        form: form.serialize(),
      },
      type:"POST",
      async: false,
   });
})

I noticed that in the browser debug console, the password is plain text. My question is, is it safe to submit a serialized form using ajax?
'csrf_token=IjI4ODJZjJmMWI5MGU1ZMjM1Y2Y0M2QxNzY3ZGUwZmI5MDki.YcCuVA.3D_79wx6Lp2-hbZWRT04z_eGhbc&username=myusername&password=MyPlainTextPassword'
Thanks,

A: You have to send the password from the client to the server.
Both the client and the server need to know what it is — the client because it produces it and the server because it has to pass it through the right hash algorithm and compare it to whatever is in the database.
What you don't want is for the password to be intercepted in transit. The way to do that is to use HTTPS and not plain HTTP. (This obviously doesn't matter when you are working with localhost URLs and the data is development data and not production data, but needs to be dealt with for your production deployment).


text:
Q: Dynamically access object with react components in typescript by key I want to dynamically select a react component from a object with a key
import React, {useState, useEffect} from 'react'
import ComponentA from '@components/ComponentA';
import ComponentB from '@components/ComponentB';

const DynamicComponent: React.FC = ({key}) => {
  const [Component, setComponent] = useState<any>();
  const COMPONENTS = {
    COMPONENT_A: ComponentA,
    COMPONENT_B: ComponentB,
  };

  useEffect(() => {
    if (key) setComponent(COMPONENTS[key])
  }, [key]);

  return Component ? React.createElement(Component) : null;
};

With this i get a type error on COMPONENTS[key]
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ COMPONENT_A: FC<{}>; }'.
No index signature with a parameter of type 'string' was found on type '{ COMPONENT_A: FC<{}>; }'.

How do i type this correctly?

A: You need define PropTypes for your component, also type of Key.
import React, {useState, useEffect} from 'react'
import ComponentA from '@components/ComponentA';
import ComponentB from '@components/ComponentB';

type Key = "COMPONENT_A" | "COMPONENT_B"

type Props = { key: Key }

const DynamicComponent: React.FC<Props> = ({key}) => {
  const [Component, setComponent] = useState<any>();
  const COMPONENTS = {
    COMPONENT_A: ComponentA,
    COMPONENT_B: ComponentB,
  };

  useEffect(() => {
    if (key) setComponent(COMPONENTS[key])
  }, [key]);

  return Component ? React.createElement(Component) : null;
};

A: You're missing default value for useState
You can use null as default value:

useState(null)

Like this:
 const [Component, setComponent] = useState<any>(null);

A: I found the answer here: https://stackoverflow.com/a/55014391
Typing the COMPONENTS object fixed my problem.
import React, {useState, useEffect} from 'react'
import ComponentA from '@components/ComponentA';
import ComponentB from '@components/ComponentB';

const DynamicComponent: React.FC = ({key}) => {
  const [Component, setComponent] = useState<any>();
  const COMPONENTS: {[key: string]: React.FC<any>} = {
    COMPONENT_A: ComponentA,
    COMPONENT_B: ComponentB,
  };

  useEffect(() => {
    if (key) setComponent(COMPONENTS[key])
  }, [key]);

  return Component ? React.createElement(Component) : null;
};


text:
Q: Wrapping/Casting C struct in Cython to Python class I'm just starting to get myself familiar with Cython, trying to wrap some structs from a C library to Python methods and classes. What I do not really understand is how casting from (initialized) C structs to the corresponding Python class should work. What am I missing here:
A snippet from the C header file:

struct test_struct {
    int _something;
    complex_struct* _another;
};
typedef struct test_struct test;

test *test_new(void);
int some_method(test **n, int irrelevant);

Corresponding snippet from my .pxd:

cdef struct test_struct:
    pass
ctypedef test_struct test

test* test_new()
int some_method(test **n, int irrelevant)

My .pyx:

def do_something(int irrelevant):
    cdef test* t = test_new()
    ret = some_method(&t, irrelevant)

    # Here comes the problem...
    return <Test?>t

cdef class Test:
    cdef test* _t

    # cinit here and some methods here. No members except _t

Everything up to the return statement works fine. I get a correct value in ret, etc. But the cast in the return statement seems to be incorrect or its missing more information. When issuing t = do_something(42) Python segfaults.
The segfault itself is not at all helpful:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a9e74b in internal_print () from /usr/lib/libpython2.7.so.1.0
(gdb) bt
#0  0x00007ffff7a9e74b in internal_print () from /usr/lib/libpython2.7.so.1.0
#1  0x00007ffff7a81adb in PyFile_WriteObject () from /usr/lib/libpython2.7.so.1.0
#2  0x00007ffff7b19acb in sys_displayhook () from /usr/lib/libpython2.7.so.1.0
#3  0x00007ffff7a64c23 in PyObject_Call () from /usr/lib/libpython2.7.so.1.0
#4  0x00007ffff7af2ff7 in PyEval_CallObjectWithKeywords () from /usr/lib/libpython2.7.so.1.0
#5  0x00007ffff7af6f3b in PyEval_EvalFrameEx () from /usr/lib/libpython2.7.so.1.0
#6  0x00007ffff7af91b0 in PyEval_EvalCodeEx () from /usr/lib/libpython2.7.so.1.0
#7  0x00007ffff7af92b2 in PyEval_EvalCode () from /usr/lib/libpython2.7.so.1.0
#8  0x00007ffff7b11f9f in run_mod () from /usr/lib/libpython2.7.so.1.0
#9  0x00007ffff7b13ec0 in PyRun_InteractiveOneFlags () from /usr/lib/libpython2.7.so.1.0
#10 0x00007ffff7b140ae in PyRun_InteractiveLoopFlags () from /usr/lib/libpython2.7.so.1.0
#11 0x00007ffff7b1470e in PyRun_AnyFileExFlags () from /usr/lib/libpython2.7.so.1.0
#12 0x00007ffff7b24bcf in Py_Main () from /usr/lib/libpython2.7.so.1.0
#13 0x00007ffff746f000 in __libc_start_main () from /usr/lib/libc.so.6
#14 0x000000000040073e in _start ()

As you can see, the do_something method should return a Python object of type Test. What do I need to add to make the cast successful? Do I need to manually map the struct to the Python class? Is there some Cython magic I can use?

A: You need to make Test into an actual wrapper around the C type. But you also cannot pass a C argument to a Python function (such as a constructor). So you'll need a factory function as well. Here's an example:
cdef class Test:
    cdef test* _t

    def __cinit__(self):
        self._t = NULL

    def _setup(self, test* t):
        self._t = t
        return self

    property something:
        def __get__(self):
            return self._t._something
        def __set__(self, int val):
            self._t._something = val

cdef Test_create(test* t):
    return Test()._setup(t)

Then in do_something():
return Test_create(t)


text:
Q: Finding the intersection of circles in Stewart's Galois Theory On page 94 of Stewart's "Galois Theory", 4th edition, he leaves as an exercise the the case of the intersection of two circles.
He is proving that the pythagorean closure $\mathbb{Q}^{py}$ of $\mathbb{Q}$ contains all constructible points. Taking $z$ in the intersection $C(z_1, \left|z_2 - z_3\right|) \cap C(z_4, \left|z_5 - z_6\right|)$ of two circles where $z_j \in \mathbb{Q}^{py}$ he arrives at
$(z - z_1) (\overline{z} - \overline{z_1}) = r^2$
$(z - z_4) (\overline{z} - \overline{z_4}) = s^2$
where $r = \left|z_2 - z_3\right|$ and $s = \left|z_5 - z_6\right|$. He says that one can solve in $z$ and $\overline{z}$ and get that $z$ satisfies a quadratic equation with coefficients in $\mathbb{Q}^{py}$. I am having trouble proving that, can someone help?

A: Sure. The main idea is: intersection two circles is the same than intersecting a circle and a line.
If you substract your two equations, you will get a linear equation in $z$ and $\bar{z}$, so you can write $\bar{z}$ under the form $az+b$, where $a$ and $b$ are constructible (easy to see from the constructibility of the $z_j's$), then you can plug the expression of $\bar{z}$ into your first equation to get a quadratic equation satisfied by $z$, where the coefficients are also constructible.


text:
Q: About using variables in an Isolate with AlarmManager I am trying to make an app sending a message using an isolate with AlarmManager. But I'm stuck. Below is the code. There's a button. When you press the button, it calls the function startAlarm. Again, it executes the function sendToIsolate. Strangely, when sendToIsolate() is called not with AlarmManager, it prints "Hello" in the terminal because it sends a variable, str, to its sendPort. But when it is called within AlarmManager.oneShot() as a callback, it never does. What could be a way to solve the issue?
import 'dart:isolate';
import 'dart:ui';

import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(home: MyHomePage()));
}

const String portName = "MyAppPort";

String? str;

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

void sendToIsolate() {
  SendPort? sendPort = IsolateNameServer.lookupPortByName(portName);
  if (sendPort != null) {
    sendPort.send(str);
  }
}

class _MyHomePageState extends State<MyHomePage> {
  ReceivePort receivePort = ReceivePort();

  @override
  void initState() {
    super.initState();
    IsolateNameServer.registerPortWithName(receivePort.sendPort, portName);

    receivePort.listen((v) {
      print(v);
    });
  }

  void startAlarm() async {
    str = "Hello";
    // await AndroidAlarmManager.oneShot(
    //   Duration(seconds: 60),
    //   1,
    //   sendToIsolate,
    //   wakeup: true,
    //   exact: true,
    // );
    sendToIsolate();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: startAlarm,
          child: Text("Start"),
        ),
      ),
    );
  }
}


text:
Q: Unable to unsubscribe while running observables in a foreach method I am iterating an array of items via foreach method. Each item executes two http calls which are nested. I am unable to unsubscribe the observables when the loop finishes. Could you please provide an solution for this
import { Observable, Subject } from 'rxjs';
import { mergeMap, take } from 'rxjs/operators';

private _unsubscribeAll: Subject<any>;

constructor(...) {
    this._unsubscribeAll = new Subject();
}

ngOnChanges(): void {

    //this.fileList is an array of ids

    this.fileList.forEach((id) => {

        this.getData(id).subscribe((res:any) => {
            console.log(res)
        })

    });

    getData(id): Observable<any> {

        return this.fileService.getFileDetails(id).pipe(take(1),
        mergeMap(data => {
            if(data != undefined) {
            return this.fileService.downloadFile(data[0].path)
            }
        }))

    }

}

ngOnDestroy() {

    this._unsubscribeAll.next();
    this._unsubscribeAll.complete();

}

A: You can do as simple as this:
const subscriptions: Subscription[] = []

this.fileList.forEach((id) => {

    this.subscriptions.push(
        this.getData(id).subscribe((res: any) => {
            console.log(res)
        })
    )

});

ngOnDestroy() {
    this.subscriptions.forEach(s => s.unsubscribe())
}

A: Consider creating a single subscription by mapping fileList into an array of observables and waiting for them all to complete using forkJoin, as demonstrated below:
private subscription: Subscription;

public ngOnChanges(): void {
    this.subscription = this.getData().subscribe((x:any[]) => { });
}

public getData(): Observable<any[]> {
    const observables: Observable<any>[] = this.fileList.map(id => {
      return this.fileService.getFileDetails(id).pipe(
        first(),
        filter(data => data != undefined),
        mergeMap(data => this.fileService.downloadFile(data[0].path))
      )
    );

    return forkJoin(observables);
}

public ngOnDestroy(): void {
    this.subscription.unsubscribe();
}


text:
Q: Qual a diferença entre Object.create ou new Object() em JavaScript? Estou passando por uma dúvida técnica em JavaScript:

*

*Qual a diferença entre Object.create e new Object()?

*Quais os casos em que tenho que adotar um ao invés do outro?

A: O método Object.create recebe parâmetros. O primeiro é obrigatório e será usado como protótipo do novo objeto. O segundo é um mapa de propriedades com as quais objeto já "nasce".
Já new Object() é uma forma mais longa e não recomendada de se dizer {}.
As três linhas de código abaixo são equivalentes:
let a = {}; // legal
let b = new Object(); // coisa de dinossauros pedantes

let c = Object.create(null); // isso pode ser útil se ao invés de nulo
                             //você passar um parâmetro.

O método create pode ser bastante útil se você usar alguma lógica mais complexa para criar seus objetos. Novamente, os dois trechos de código abaixo são equivalentes:
// forma verbosa
let foo = {};
foo.prototype = Array;

let bar = {nome: "john", idade: 21};

for (let propriedade in bar) {
    foo[propriedade] = bar[propriedade];
}

// forma curta
let foo = Object.create(Array, {nome: "john", idade: 21});

A: TL;DR
Na grande maioria das vezes, para se criar um objeto em JavaScript, basta fazer algo assim:
const myObject = {
  // ...
};

De modo que, terá sido criado um novo objeto myObject cujo protótipo aponta para Object.prototype. O {} (forma literal), é análogo a se utilizar new Object() ou Object(). Apesar dessa equivalência, prefira sempre utilizar {}.
Já a função Object.create, diferentemente do demonstrado anteriormente, deverá ser utilizada quando:

*

*For necessário definir um protótipo diferente ao objeto a ser criado; e/ou:

*For necessário definir descritores de propriedade iniciais do objeto a ser criado (não confundir com propriedades).

Portanto, ao se criar um objeto com {}, new Object() ou Object(), limita-se a um novo objeto cujo protótipo é sempre Object.prototype. A função Object.create permite que sejam criados objetos com um protótipo diferente e/ou propriedades com descritores definidos com maior granularidade.

Primeiro argumento de Object.create
O primeiro argumento de Object.create é útil para definir um "protótipo customizado" na criação de um objeto. Então, no exemplo abaixo:
const customPrototype = {}; // Qualquer objeto.

const obj = Object.create(customPrototype);

O objeto obj terá como protótipo o objeto customPrototype, que foi passado no primeiro argumento da função. Então a avaliação de Reflect.getPrototypeOf(obj) === customPrototype resultaria em verdadeiro.
É, de certo modo, o mesmo que isto:
const customPrototype = {}; // Qualquer objeto.

const obj = {};
Reflect.setPrototypeOf(obj, customPrototype);

A desvantagem de redefinir o protótipo após o objeto ter sido criado é que os atuasi interpretadores de JavaScript não possuem otimizações para a redefinição prototípica, uma vez que é uma operação pouco usual e relativamente custosa (toda a cadeia de protótipos do objeto será alterada). Portanto, é mais indicado definir o protótipo customizado durante a criação do objeto do que fazer isso uma vez que o objeto já tenha sido criado. Por isso existe o primeiro argumento de Object.create.
Segundo argumento de Object.create
O segundo argumento de Object.create define os descritores de propriedade que o objeto a ser criado possuirá.
Ao contrário do inúmeras pessoas pensam, o segundo argumento de Object.create não serve para definir propriedades iniciais para um objeto, mas sim definir os descritores de propriedades iniciais que o objeto irá assumir. Sobre descritores e atributos de propriedades, é um assunto extenso que dá uma resposta por si só. Trato em mais detalhes sobre eles em O que são e como funcionam os descritores e atributos de propriedade do JavaScript?.
Então, um exemplo (criando um novo objeto cujo protótipo é null e com os dados descritores de propriedades):

const obj = Object.create(null, {
  name: {
    value: 'Bob',
    writable: false,
    enumerable: false,
    configurable: false
  },
  age: {
    value: 50,
    writable: false,
    enumerable: false,
    configurable: false
  }
});

console.log(obj);
console.log(Object.keys(obj));

console.log('---\nAs propriedades estão aqui!');

// As propriedades estão lá! Só não podem ser enumeradas
// normalmente porque o atributo `enumerable` de cada
// propriedade foi definido, na criação, como `false`.
console.log(Object.getOwnPropertyNames(obj));
console.log(obj.name);
console.log(obj.age);

Desse modo, não é correto fazer isto:
// Este código não é válido.
const obj = Object.create(null, {
  name: 'Bob',
  age: 50
});

Como o segundo argumento não contém descritor(es) de propriedade válido(s), o seguinte erro será lançado:

Uncaught TypeError: Property description must be an object

É pouco intuitivo e menos útil. Seria muito mais interessante utilizar o segundo argumento de Object.create para definir as propriedades (não confundir com descritor de propriedade) a serem assumidas pelo objeto durante a sua criação. Se isso for necessário, pode-se combinar Object.create com Object.assign:

// Criaremos um objeto cujo protótipo é `null`
// E as propriedades definidas inicialmente são `name` e `age`:
const obj = Object.assign(Object.create(null), {
  name: 'Bob',
  age: 50
});

console.log(obj); //=> { name: "Bob", age: 50 }
console.log(Reflect.getPrototypeOf(obj)); //=> null

Mais detalhes sobre o Object.assign nesta resposta ou na documentação.
A título de curiosidade, além de Object.create, as funções Object.defineProperty e Object.defineProperties também podem ser utilizadas para definir propriedades através da descrição de propriedades em um objeto. A diferença é que Object.create faz na criação e, as duas últimas, uma vez que o objeto já tenha sido criado.
Considerações sobre {}, Object() e new Object()
São equivalentes:
1 | const a = {};
2 | const b = new Object();
3 | const c = Object();

Na linha 1, cria-se um objeto a partir da notação literal. Na linha 2, cria-se um objeto a partir da instanciação do construtor Object. Na linha 3, cria-se um objeto a partir da invocação de Object. Todos os três criarão um novo objeto cujo protótipo é Object.prototype.
Demonstração:

const a = {};
const b = new Object();
const c = Object();

console.log(Reflect.getPrototypeOf(a) === Object.prototype); //=> true
console.log(Reflect.getPrototypeOf(b) === Object.prototype); //=> true
console.log(Reflect.getPrototypeOf(c) === Object.prototype); //=> true

Então, não é correto dizer que as três formas acima são equivalentes à Object.create(null), uma vez que os protótipos são diferentes.
Ao utilizar Object.create(null), cria-se um novo objeto no qual null é o protótipo. Já utilizar {}, Object() ou new Object() são três formas equivalentes de se criar um novo objeto no qual Object.prototype é o protótipo.
No entanto, Object.create(Object.prototype) é, sim, equivalente às três formas em questão.

São detalhes sutis, mas que fazem diferença. Esta outra excelente respsota dá mais detalhes sobre a cadeia de protótipos, que é um conceito fundamental para entender esta resposta sobre Object.create.
Além disso, a leitura sobre descritores de propriedades é, também, importante para entender plenamente o funcionamento de Object.create.


text:
Q: How to prove COROLLARY 16.3.2 in Convex Analysis? In "Convex Analysis" by Rockafellar:

COROLLARY 16.3.2. Let $A$ be a linear transformation from $R^{n}$ to $R^{m}$. For any convex set $C$ in $R^{n}$, one has
$$
(A C)^{\circ}=A^{*-1}\left(C^{\circ}\right) .
$$
For any convex set $D$ in $R^{m}$, one has
$$
\left(A^{-1}(\mathrm{cl} D)\right)^{\circ}=\mathrm{cl}\left(A^{*}\left(D^{\circ}\right)\right) .
$$
If there exists some $x$ such that $A x \in$ ri $D$, the closure operation can be omitted from the second formula.
PROOF. Immediate from the preceding corollary. $\|$

The preceding corollary show following:

COROLLARY 16.3.1. Let A be a linear transformation from $R^{n}$ to $R^{m}$. For any convex set $C$ in $R^{n}$, one has
$$
\delta^{*}\left(y^{*} \mid A C\right)=\delta^{*}\left(A^{*} y^{*} \mid C\right), \quad \forall y^{*} \in R^{m} .
$$
For any convex set $D$ in $R^{m}$, one has
$$
\delta^{*}\left(\cdot \mid A^{-1}(\mathrm{cl} D)\right)=\operatorname{cl}\left(A^{*} \delta^{*}(\cdot \mid D)\right) .
$$
If there exists some $x$ such that $A x \in \mathrm{ri} D$, the closure operation can be omitted in the second formula, and
$$
\delta^{*}\left(x^{*} \mid A^{-1} D\right)=\inf \left\{\delta^{*}\left(y^{*} \mid D\right) \mid A^{*} y^{*}=x^{*}\right\},
$$
where for each $x^{*}$ the infimum is attained (or is $+\infty$ vacuously).
PROOF. Take $f(x)=\delta(x \mid C), g(y)=\delta(y \mid D)$. $\quad \|$

But i can not prove $$
\left(A^{-1}(\mathrm{cl} D)\right)^{\circ}=\mathrm{cl}\left(A^{*}\left(D^{\circ}\right)\right) .
$$ by preceding corollary. I only obtain that $x\in
\left(A^{-1}(\mathrm{cl} D)\right)^{\circ}\Leftrightarrow \delta^{*}\left(x \mid A^{-1}(\mathrm{cl} D)\right)\leqslant 1$. So a natural thought of mine was to prove $x\in \mathrm{cl}\left(A^{*}\left(D^{\circ}\right)\right) \Leftrightarrow\operatorname{cl}\left(A^{*} \delta^{*}(x \mid D)\right)\leqslant 1 .$ Is my idea correct? If it is correct, how to prove it completely? Can anyone help me to write a detailed proof?


text:
Q: Ravel() on only two dimensions of a 3D numpy array I have a numpy array of shape (182, 218, 182).
I'm trying to reorganize it such that it is size (182, 39676) - e.g., take each of the 182 slices of it and ravel() out each of those slices into one dimension, but still keep the slices separate.
I can think of a few ways of doing this with a loop, but it seems un-pythonic to make a loop in numpy. Anyone know if there's a method or parameter somewhere that'll do the trick?
Thanks!

A: import numpy
   # initialize a[182][218][182]
   a=numpy.reshape(a,(182,39676))

This reshape should do the work.


text:
Q: Php code to encrypt client input data and decrypt it at the server side I want to encrypt password and confirm password field at the client side and after it reaches to the server side via some network it should be decrypted to it's original form again.
Below is the code of a javascript file (enc.js) that i wrote which will encrypt data at the client side. I am unable to decrypt it at the server side.
$(document).ready(function()
{ $("#login_submit").click (

        function()
        {
            var password=$("#password").val();
            var pass=CryptoJS.MD5(password).toString();
            var q=$("#salt").val();
            var encp = CryptoJS.MD5(q + pass).toString();
            $("#password").attr('value', encp);
        });
});

The above code is working absolutely fine, but i need some help to decrypt the encrypted data at the server side which has been encrypted using CryptoJS.MD5() at the client side.
Below is the code of clent side web page (register.php)
<?PHP
session_start();
session_regenerate_id(true);
if(!isset($_SESSION['user']))
{
header("location:../login/log.php");
}
else if(($_SESSION['user']) != "admin")
{
echo "

";
header( "refresh:3; url=nopage.php" );
echo "Access Denied";
echo "Back";
}
else
{
require_once("./include/membersite_config.php");
include_once "../validation/Validator.php";
require("../connection123.php");
$protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https')
=== FALSE ? 'http' : 'https';
$host     = $_SERVER['HTTP_HOST'];
$script   = $_SERVER['SCRIPT_NAME'];
$params   = $_SERVER['QUERY_STRING'];
$currentUrl = $protocol . '://' . $host . $script . '?' . $params;
$head=$v->valHeader($currentUrl);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Cache-Control" content="no-cache"/>
<meta http-equiv="Cache-Control" content="no-store"/>
<meta http-equiv="Cache-Control" content="must-revalidate"/>
<meta http-equiv="Cache-Control" content="private"/>
<meta http-equiv="Cache-Control" content="pre-check=0"/>
<meta http-equiv="Cache-Control" content="post-check=0"/>
<meta http-equiv="Cache-Control" content="max-stale=0"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="Mon, 26 Jul 1997 05:00:00 GMT"/>
<link rel="STYLESHEET" type="text/css" href="style/fg_membersite.css" />

<link rel="STYLESHEET" type="text/css" href="style/pwdwidget.css" />

<?php
$current_url = $_SERVER['REMOTE_ADDR'].$_SERVER['PHP_SELF'];
$v=new validator();
                            error_reporting(0);
                            $url=$_SERVER['HTTP_REFERER'];
                            $headerAdd=$v->valHeader($url);
                            $salt = substr(md5(uniqid(rand(), true)), 0, 32);
?>

Back
<?php
// make a random id
$_SESSION["token"] = md5(uniqid(mt_rand(), true));
echo 'Logout	';

?>

<?php
$token= md5(uniqid());
$_SESSION['delete_customer_token']= $token;
session_write_close();
?>

<form id='register' name='register' action='afterregister.php' method='post'  accept-charset='UTF-8'>
<fieldset >
<legend>Register New Account Here</legend>

* Required fields

<?php echo $fgmembersite->GetErrorMessage(); ?>

<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="registeracct" value="Register Account" />
Your Full Name*:

<input type='text' name='name' id='name' value='' maxlength="30" autocomplete="off" />

UserName*:

<input type='text' name='username' id='username' value='' maxlength="30"   autocomplete="off"/>[Only letters without space]
<input id="salt" type="hidden" name="salt" maxlength=50 value=<?php echo $salt;?>/>

Email id*:

<input type='text' name='email' id='email' value='' maxlength="300"  autocomplete="off"/>

Password*:

<input type='password' name='password' id='password' maxlength="30" autocomplete="off" />

Confirm Password*:

<input type='password' name='cnpwd' id='cnpwd' maxlength="30" autocomplete="off" />

<input type="submit" id="login_submit" name="Submit" value="Submit" />

</fieldset>
</form>

<?php
}
?>

Below is the code of server side (afterregister.php)

<?php
session_start();
session_regenerate_id(true);
$s_id=session_id();//PHPSESSID
error_reporting(0);
require("../connection123.php");
include_once "../validation/Validator.php";
include_once "../validation/val.php";
$v=new Validator();
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
  exit();
}
$array=array('token','registeracct','name','username','salt','email','password','cnpwd','Submit');
$n=$v->array_equal($_POST,$array);
if($n!=0){
         $redirect="../nopage.php";
    die('');
  }
    $ip="";
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {   //check ip from share internet
        $ip1 = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {   //to check ip is pass from proxy
        $ip1 = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip1 = $_SERVER['REMOTE_ADDR'];
    if(filter_var($ip1,FILTER_VALIDATE_IP)){
        $ip=$ip1;
    }else{
    header("location:../nopage.php");
    }
    }

    $formname="";
    if(isset($_POST['registeracct']))
    {
       $formname= $_POST['registeracct'];
    }
    $token = $_SESSION['delete_customer_token'];
    unset($_SESSION['delete_customer_token']);
    session_write_close();
    //echo $formname;
    $stmt = $mysqli -> prepare("SELECT logindt FROM tblaudit ORDER BY logindt DESC LIMIT 1");

        $stmt-> execute();
        $stmt->store_result();
        $stmt-> bind_result($result1);
        $login="";
       if($stmt->fetch())
       {
         $login=$result1;
       }
//echo $login;
    //echo $ip;

    $name1=$v->validateSQLInjectionlogin($_POST['name']);
    $name2=$v->xss_protect($name1);
    $name=$v->validf_name($name2);
    //echo $name;
/** if($name==""){
        $redirect="../nopage.php";
        die('');
    }**/

    $name1=$v->validateSQLInjectionlogin($_POST['username']);
    $usernamee=$v->xss_protect($name1);
    $username=$v->validf_name($usernamee);

    //echo $username;

    $salt1=$v->validateSQLInjectionlogin($_POST['salt']);
    $salt=$v->xss_protect($salt1);

    $email="";
    if(isset($_POST['email']))
    {
    $email= $_POST['email'];
    }

    //echo $email;

    $name1=$v->validateSQLInjection($_POST['password']);
    $password=$v->xss_protect($name1);

    //$pass=md5($salt . md5($password));
    $pass=md5($password);

    //echo $pass;

    $cnfpwd1=$v->validateSQLInjection($_POST['cnpwd']);
    $cnfpwd=$v->xss_protect($cnfpwd1);

    //echo $cnfpwd;
    $no='no';

    $confirmcode = 'y';

    $stmt1 = $mysqli -> prepare("SELECT distinct username FROM users WHERE username=?");
    $stmt1->bind_param("s", $username);
    $stmt1->execute();
    $stmt1->store_result();
    $stmt1-> bind_result($result2);

    $stmt5 = $mysqli -> prepare("SELECT distinct email FROM users WHERE  email=?");
    $stmt5->bind_param("s", $email);
    $stmt5-> execute();
    $stmt5->store_result();
    $stmt5->bind_result($result3);

    /** if($formname=="" or $name=="" or $username=="" or $salt=="" or $password=="" or $cnfpwd=="" )
    {
         $redirect="../nopage.php";
         die('');
    }**/
if ($token && $_POST['token']==$token)
{
    if($stmt1->fetch())
    {
      echo "

";
      echo "Username already exists. Please provide a unique username";
      echo "Back";

      $stmt1->close();

    }
    else if (strlen($username) < 5 OR strlen($username) > 20)
    {
      echo "

";
      echo "Username should be within 5-20 characters long.";
      echo "Back";

    }
    elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i", $email))
    {
      echo "

";
      echo "Enter a valid Email-id.";
      echo "Back";

    }
    elseif($stmt5->fetch())
    {
      echo "

";
      echo "Email-id already exists. Please provide a unique email-id";
      echo "Back";

      $stmt5->close();
    }
    else if (!preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/', $password))
    {
      echo "

";
      echo "Password should contain minimum 8 characters, atleast an uppercase letter, a lowercase letter and a number.";
      echo "Back";

    }
    else if($password != $cnfpwd)
    {
              echo "

";
              echo "Confirm password not matched!";
              echo "Back";
    }
    else
    {
        $stmt2 = $mysqli->prepare("insert into users(name,username,email,password,confirmcode,locked) values(?,?,?,?,?,?)");
        $stmt2->bind_param('ssssss',$name,$username,$email,$pass,$confirmcode,$no);
        $stmt2->execute();

        $stmt3=$mysqli->prepare("insert into session(id,username,salt,session_id) values(?,?,?,?)");
        $stmt3->bind_param('ssss',$ip,$username,$salt,$s_id);
        $stmt3->execute();

        // create the audit trail
        //$stmt4 = $mysqli->prepare("insert into tblaudit (uID,editor,formname,whenpost,ip) values(?,?,?,NOW(),?)");
        //$stmt4->bind_param('ssss',$userid,$editor,$formname,$ip);
        //$stmt4->execute();

        $stmt4=$mysqli->prepare("update tblaudit set formname=?, whenpost= NOW() where logindt=?");
        $stmt4->bind_param('ss',$formname,$login);
        $stmt4->execute();

        include "thank-you-regd.html";

        $stmt2->close();
        $stmt3->close();
        $stmt4->close();

        $mysqli->close();

    }
}
else
{
   echo "unable to register a new account";
}
?>

A: Understanding SSL

SSL (Secure Sockets Layer) is the standard security technology for
  establishing an encrypted link between a web server and a browser.
  This link ensures that all data passed between the web server and
  browsers remain private and integral.

However, you can create your own (useless) encryption but i recommend you use SSL.
Types of encryption: https://support.microsoft.com/en-us/kb/246071

*

*asymmetric encryption - Symmetric encryption is the oldest and best-known technique. A secret key, which can be a number, a word, or
  just a string of random letters, is applied to the text of a message
  to change the content in a particular way. This might be as simple as
  shifting each letter by a number of places in the alphabet. As long as
  both sender and recipient know the secret key, they can encrypt and
  decrypt all messages that use this key.

*symmetric encryption - here are two related keys--a key pair. A public key is made freely available to anyone who might want to send
  you a message. A second, private key is kept secret, so that only you
  know it.

asymmetric and symmetric encryption work together to create a SSL encryption to communicate from the client to the server.
It is highly advised you do not attempt to reinvent the wheel, use SSL. any encryption you write on the client side can easily be cracked because JavaScript is readable.

Hashing vs Encryption
MD5 (message-digest algorithm) - s a widely used cryptographic hash function producing a 128-bit (16-byte) hash value, typically expressed in text format as a 32 digit hexadecimal number. MD5 has been utilized in a wide variety of cryptographic applications, and is also commonly used to verify data integrity.
Hashing & encryption are entirely different terminologies. Hashing is one way, and may have several alternative patterns that match. Encryption is reversible with a key. read more here: http://www.securityinnovationeurope.com/blog/whats-the-difference-between-hashing-and-encrypting

Understanding Javascript
Javascript - is a high level, dynamic, untyped, and interpreted programming language. It has been standardized in the ECMAScript language specification.
JavaScript is not meant to manage security. JavaScript is mainly meant for DOM (Document Object Model) manipulation & a few other related manipulations. Though,it does have some capabilities outside the scope of the DOM.

A: Unfortunately client side javascript source code is widely open for everyone to see and examine. You simply right click and press "view source..." or use firebug or something else.
In addition, every unsecured http request (via http and not https = ssl) is sent as a readable unencrypted string and can be monitored from other devices in your network.
Both of the above mean that you actually shouldnt MD5 your user + pass in client side js prior to sending them to the server because it really doesnt matter as users can view your js source code anyway and deduce your salt and arrangement of the string to be hashed. So it really wont matter if you send the user + pass without any encryption.
To facilitate encryption Id advise you to purchase a ssl plan from your hosting company (like godaddy) and make sure they install it for you. Then, its only a matter of navigating to your site via https.


text:
Q: Getting runtime issue in swift When I am using this line of code:
if (context == &KVOContext && keyPath == contentOffsetKeyPath && object as? UIScrollView == scrollView) {
    //...
}

I am getting runtime issue which is:

Simultaneous accesses to 0x7f7eea603fb8, but modification requires
  exclusive access

I don't know how to solve this. Can anyone give me solution for this?


text:
Q: Margins with newlfm How do I adjust margins with newlfm?  I've set everything I can find to zero, but there are still vast expanses of whitespace.
Here is a minimal example:
\documentclass[11pt,stdletter,orderfromtodate,sigleft]{newlfm}

\headermarginsize{0in}
\rightmarginsize{0in}
\topmarginsize{0in}
\topmarginskip{0in}
\headermarginsize{0in}
\headermarginskip{0in}

% Some of the article customisations are relevant for this class

\name{MyName} % To be used for the return address on the envelope
\signature{My sig} % Goes after the closing (ie at the end of the letter, with space for a signature)
\address{Address \\ of \\ Sender}
% Alternatively, these may be set on an individual basis within each letter environment.

\begin{document}

\begin{letter}{Name and \\ Address \\ of \\ Receiver}

\opening{Dear John,}

My Letter

\closing{Regards,} % eg Regards,

\cc{} % people this letter is cc-ed to
\encl{} % list of anything enclosed
\ps{} % any post scriptums. ``PS'' labels must be put in manually

\end{letter}
\end{document}

A: I would personally advise against using newlfm specifically for this reason. Use a regular article document class and set your margins and style without hassle:

\documentclass[11pt]{article}

\usepackage{geometry,lipsum}
\geometry{
  margin=1in
}

\setlength{\parindent}{0pt}% Remove paragraph indent

\begin{document}

\pagestyle{empty}% Remove page headers/footers

\mbox{}\hfill
\begin{tabular}{l @{}}
  Address \\
  of \\
  Sender \\ \\
  \today
\end{tabular}

\bigskip % Vertical skip between sender/receiver address

\begin{tabular}{@{} l}
  Name and \\
  Address \\
  of \\
  Receiver
\end{tabular}

\bigskip % Vertical skip between receive address and letter opening

Dear John,

\medskip % Vertical skip between letter opening and letter body

\lipsum[1]

\medskip % Vertical skip between letter body and closing

\hspace*{.5\linewidth}%
Regards,

\medskip % Vertical skip between letter closing and signature start

\vspace{5\baselineskip} % Content that includes your signature, or space for it

My signature

\bigskip % Vertical skip between signature and attachment references

cc: % people this letter is cc-ed to

\medskip

encl: % list of anything enclosed

\medskip

ps: % any post scriptums

\end{document}

The code and accompanying output reads better together as the content flow is sequential - you don't have to put the sender/recipient and signature detail in the preamble when they could easily fit within the document body.
With a plain article class, you can use geometry to set your margins as you need.

A: This command will modify the top margin.
\topmarginskip{0in}
\newlfmP{topmarginskip=-1in}

You can use negative values if you want. You can find other pertinent commands in the manual.

A: You can do it with setting \newlfmP{headermarginsize=10pt}.


text:
Q: Google Play Console prevent production is released automatically Is there any method for preventing automatically roll out in Google Play Console?
In the App Store, I can select whether I permit automatically release by App store after review or release manually.
I read this docs But timed publishing doesn't match my need.
Also, I traveled several features in play console. But I cannot find any functions for that.

A: In the new Play Console, we can use Managed Publish in Publishing overview tab.

A: After you push your APK file or Android app bundle to the production channel and fill up all the necessary fields, you have the option to setup the rollout amount.
If you want to control that process, then simply set it to 0. It will not get released unless you increase it.

A: I found you cannot set it to 0%, if you do so the button to continue will be disabled.
What did work was setting it to a percentage that is higher than zero, but still results in 0 matching users, e.g 0.001%


text:
Q: error in the xaml.g.cs in xamarin.forms The type or name space does not exist...this error happens in the xaml.g.cs
that is here:
[global::Xamarin.Forms.Xaml.XamlFilePathAttribute("C:\\montana\\neoFly_Montana1\\neoFly_Montana\\neoFly_Montana\\PopUp\\LoginPopup.xaml")]
public partial class LoginPopup : global::Rg.Plugins.Popup.Pages.PopupPage {

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
    private global::Xamarin.Forms.Image login_img_forms;

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
    private global::Xamarin.Forms.StackLayout login_stack_forms;

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
    private global::Xamarin.Forms.MyEntry login_entry_login;

    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
    private global::Xamarin.Forms.MyEntry login_entry_pass;

it happend after I changed the xaml file:
<?xml version="1.0" encoding="utf-8" ?>
<pages:PopupPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:neoFly_Montana.LayoutScripts"
         xmlns:pages="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"
         xmlns:animations="clr-namespace:Rg.Plugins.Popup.Animations;assembly=Rg.Plugins.Popup"
         x:Class="neoFly_Montana.PopUp.LoginPopup"
         CloseWhenBackgroundIsClicked="False">

              <MyEntry Placeholder="E-mail:" Margin="10,0,0,0" x:Name="login_entry_login" FontSize="Medium" TextColor="{StaticResource MarromClaro}" PlaceholderColor="{StaticResource MarromClaro}"/>

I added the MyEntry and the xmlns:local="clr-namespace:neoFly_Montana.LayoutScripts"
I tried to clean and rebuild solution

A: The compiler needs to know what MyEntry is - there are two steps to this.  The first is to define the namespace, which you've already done.  The second is to specify that MyEntry exists in the local namespace:
you need to use <local:MyEntry ...


text:
Q: How to handle future in ion library? I've been working with ion library and I've stored the value returned ( as a string ) in the future variable, but I don't know how to show the results or retrieve it. Here's my code.
 public Future<String> getCars(){

   future =
            Ion.with(this)
           .load("http://localhost:3000/api/cars")
           .asString()
           .setCallback(new FutureCallback<String>() {
               @Override
               public void onCompleted(Exception e, String result) {

               }
           });

   return future;

}

How to handle the variable I'm returning? Is my usage correct in the first place? I would like to know if I'm on the right track, and if I'm, I would like to know how to get json data as a string and show it in a TextView.
Thank you.

A: This is correct. Your string is in the "result" variable. Just put it in the TextView using setText.


text:
Q: How to set instance name of google-chrome (or any x11 application) I'm now using dwm window manager and I know I can set rules to specify a application to a certain tag like this:
static const Rule rules[] = {
    /* xprop(1):
    *  WM_CLASS(STRING) = instance, class
    *  WM_NAME(STRING) = title
    */
    /* class      instance    title       tags mask     isfloating   monitor */
    { "Gimp",     NULL,       NULL,       0,            True,        -1 },
    { "Google-chrome",  NULL, NULL,       1 << 1,       False,       -1 }, // set chrome's tab. 2013-12-13
    { "UXTerm",    NULL,      "proxy",    1 << 8,       False,       -1 }, // let goagent proxy run in tab #9. 2013-12-13
};

Now I want to run several chrome instances with different webpages specified to different tags. The problem is some of the webpages' titles are dynamic. So I think set rules by title is not a good practice.
Here is my question: how to set the instance name of Google-chrome (or any X11 application) so I can create the rules by instance name.

A: For Chrome (or Chromium), you can change the second element of WM_CLASS by launching it with the --class="myClass" flag on startup (documentation). This will affect the class column of your dwm config, though, and not the instance one, which would be the first element of the WM_CLASS array.
The solution, then, might be to use --app=URI instead, which does sort of create discrete instances with "fixed" names which are based on the input URI. This solves the problem of the dynamic tab title; drawback however is that in --app mode you can only have one tab (and it's borderless).
As for the general question, one could use wmctrl to change the window class manually: http://tripie.sweb.cz/utils/wmctrl/


text:
Q: Problema con password_verify Estoy iniciando con PHP y tengo un problema con la función Password_Verify. Les explico:
Al utilizar esta función, no me retorna TRUE aún cuando en teoría los datos obtenidos son "correctos".
Les muestro el código y les explico al mismo tiempo:
Controlador Login
    function validarUsuario()
{
    $usuario = isset($_POST['usuario']) ? $_POST['usuario'] : null;
    $password = isset($_POST['password']) ? $_POST['password'] : null;

    $login = new Login();
    $passwordbd = $this->model->login($usuario);
    error_log('Login::Controller -> ValidarUsuario() -> Password recibida: ' . $password); //imprimo en el log la contraseña que el usuario ingresó (desencriptada)
    error_log('Login::Controller -> ValidarUsuario() -> PasswordBD recibida: ' . $passwordbd); //imprimo en el log la contraseña obtenida de la base de datos dependiendo del usuario ingresado
    if (password_verify($password, $passwordbd)) { //Hago la comparación de las contraseñas, según los parámetros establecidos de la función
        error_log('Login::Controller -> Password_verify -> contraseñas coinciden'); //Si las contraseñas coinciden, envío un mensaje de éxito
        $mensaje = "Inicio de sesión correcto";
        $tipoMensaje = "alert alert-success";
    } else {
        error_log('Login::Controller -> Password_verify -> contraseñas NO coinciden'); //si las contraseñas no coinciden, envío un mensaje de error
        $mensaje = "Error en el inicio de sesión";
        $tipoMensaje = "alert alert-danger";
    }
    $this->view->mensaje = $mensaje;
    $this->view->tipoMensaje = $tipoMensaje;
    $this->render();
}

Modelo Login
   function login($usuario)
{
    try {
        $query = $this->prepare('SELECT * FROM usuarios WHERE usuario = :usuario');
        $query->execute([
            'usuario' => $usuario
            ]);
        if($query->rowCount() == 1){ //Si la consulta es exitosa, obtengo el registro del campo "password" y lo guardo en la variable $passwordbd
            $resultado = $query->fetch(PDO::FETCH_ASSOC);
            if(isset($resultado['password'])){
                $passwordbd = $resultado['password'];
            }
            error_log('LoginModel::Success -> Valores recibidos');
        }else{
            error_log('LoginModel::Error -> Valores no encontrados');
        }
        error_log('LoginModel::Success-> Password: '.$resultado['password']); //Imprimo la contraseña obtenida de la base de datos (encriptada por password_hash)
        return $passwordbd; //retorno el valor de la contraseña obtenida
    } catch (PDOException $e) {
        error_log('LoginModel::Error->PDOException: '.$e);
        return $e->getMessage();
    }
}

Ahora bien, los error_log los he puesto para poder saber qué está pasando y mostrar las contraseñas obtenidas por el usuario y por la base de datos. Entonces, en este caso podemos observar que la contraseña del usuario "luis" es luis, que cifrada con password_hash obtuve $2y$10$lE2G/LBuWnK7JaQQV4.3ZuTs/7uXioXUC404KlXuWRH**

Y en el error log me muestra exactamente lo mismo:

Entonces, si los resultados se supone son correctos, ¿Por qué no me retorna nada?
¿Estoy aplicando mal la funcion? Agradecería mucho su retroalimentación y también que me mostraran los errores que tengo. Muchas gracias
*Edit: La forma en que cifré los datos ha sido la siguiente:
Controlador
function registrarTutor()
{
    $nombre = isset($_POST['nombre']) ? $_POST['nombre'] : null;
    $usuario = isset($_POST['usuario']) ? $_POST['usuario'] : null;
    $password = isset($_POST['password']) ? $_POST['password'] : null;

    $pass_cifrada = password_hash($password, PASSWORD_DEFAULT);

    if(!$nombre || !$usuario || !$password){
        $mensaje = "No puedes dejar este campo vacío";
        $tipoMensaje = "alert alert-danger";
    }else{
        if ($this->model->insertar([
            'nombre' => $nombre,
            'usuario' => $usuario,
            'password' => $pass_cifrada,
        ])) {
            $mensaje = "Usuario agregado con éxito";
            $tipoMensaje = "alert alert-success";
        } else {
            $mensaje = "¡Error! Algo salió mal :(";
            $tipoMensaje = "alert alert-danger";
        }
    }
    $this->view->mensaje = $mensaje;
    $this->view->tipoMensaje = $tipoMensaje;
    $this->render();
}

Modelo
public function insertar($datos)
{
    try {
        $query = $this->prepare('INSERT INTO usuarios(nombre,usuario,password,rol,condicion) VALUES (:nombre,:usuario,:password,"admin","1");');
        $query->execute([
            'nombre'   => $datos['nombre'],
            'usuario'  => $datos['usuario'],
            'password' => $datos['password'],
        ]);
        return true;
    } catch (PDOException $e) {
        return false;
    }
}

A: En los comentarios me han ayudado con la solución, al parecer era demasiado simple pero no había tomado en cuenta éso que me comentó, el aumentar el nivel de caracteres permitidos en la base de datos. Muchisimas gracias Diablo por la solución.

A: Si nos fijamos en el manual si se usa el algoritmo PASSWORD_DEFAULT este podría crear una cadena de más de 60 caracteres, para ello sería bueno tener 255 caracteres permitidos en nuestra columna en la Base de Datos que va guardar esta información, si la columna no cumpla con este requisito no va coincidir tu contraseña al usarse password_verify, ya que no te ha guardado correctamente tu contraseña haseada en tu Base de Datos.
password_hash() crea un nuevo hash de contraseña usando un algoritmo de hash fuerte de único sentido. password_hash() es compatible con crypt(). Por lo tanto, los hash de contraseñas creados con crypt() se pueden usar con password_hash().
Actualmente se admiten los siguientes algoritmos:

*

*PASSWORD_DEFAULT - Usar el algoritmo bcrypt (predeterminado a partir de PHP 5.5.0). Observe que esta constante está diseñada para cambiar siempre que se añada un algoritmo nuevo y más fuerte a PHP. Por esta razón, la longitud del resultado de usar este identificador puede cambiar con el tiempo. Por lo tanto, se recomienda almacenar el resultado en una columna de una base de datos que pueda ampliarse a más de 60 caracteres (255 caracteres sería una buena elección).

*PASSWORD_BCRYPT - Usar el algoritmo CRYPT_BLOWFISH para crear el hash. Producirá un hash estándar compatible con crypt() utilizando el identificador "$2y$". El resultado siempre será un string de 60 caracteres, o false en caso de error.

Manual: password_hash


text:
Q: Connecting Flask app to a Websocket server Not able to connect a Flask app as a websocket client to another websocket server.
I tried to look around how to implement this, but the only solution i found is when the connection is Short-lived one-off send-receive.
So, when I make a Long-lived connection, Flask app is not running anymore. I guess the problem, is because both of them are running "forever".
so if run the following code first, flask app won't run, and if I do the opposite the websocket connection won't be established.
 websocket.enableTrace(True)
 ws = websocket.WebSocketApp(config["WS_URI"],
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
 ws.on_open = on_open

 ws.run_forever()

a sample Flask app:
from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    return "index"

A: The solution I found was to run them on different processes.
I wrote a small post explaining the details.


text:
Q: Pine script - How to use two exit conditions on one position ID? Once a position is long or short I have three exit conditions
1)ATR based stop is hit
2)Close position if close price moves to the wrong side of the EMA value
3)Once moving averages flip the open trade closes then opens in the other direction
1 and 3 work fine. I'm having trouble with 2) close when price moves above/below EMA and am not receiving an error code.
Here is the script:
//@version=4
//Strategy

//Inputs

startTime = input(title="Start Time", type = input.time, defval = timestamp("01 Jan 2017 00:00 +0000"))
endTime = input(title="End Time", type = input.time, defval = timestamp("01 Jan 2023 00:00 +0000"))

//Time
inDateRange = (time >= startTime) and (time < endTime)

fastSMALen = input(title="Fast SMA Length", type=input.integer, defval=9)
slowSMALen = input(title="Slow SMA Length", type=input.integer, defval=21)
exitEMALen = input(title="Exit EMA", type=input.integer, defval=20)

//Stop Loss inputs
atrLen = input(title="ATR Length", type=input.integer, defval=10)
stopOffset = input(title="Stop ATR Multiple", type=input.float,
     defval=2, minval=0.01)

//Position Sizing inputs
PosSizeLoss = input(title="Risk $", type=input.integer,
     defval=200) //Amount to risk losing on a trade

//Calculate strategy values

fastSMA = sma(close, fastSMALen)
slowSMA = sma(close, slowSMALen)
**exitEMA = ema(close, exitEMALen)**

atrValue = atr(atrLen)

//Calculate Posotion Size
PosSizeUnits = PosSizeLoss/(atrValue*stopOffset)

//Trading conditions
long = crossover(fastSMA, slowSMA) and inDateRange
short = crossunder(fastSMA, slowSMA) and inDateRange
**lema_exit = crossover(close, exitEMA) and inDateRange**
**sema_exit = crossover(close, exitEMA) and inDateRange**

//Command to execute long trades - strateg.long says buy long,
if (long)
    stopLoss = low - atrValue*stopOffset
    strategy.entry("long", strategy.long, PosSizeUnits) //stop=high for the day the indicators crosses using stop order
    strategy.exit("exit", "long", stop=stopLoss)
    strategy.close("long", when = lema_exit)

//Command to execute short trades
if (short)
    stopLoss = high + atrValue*stopOffset
    strategy.entry("short", strategy.short, PosSizeUnits) // stop = low for the day the indicator crosses
    strategy.exit("exit", "short", stop=stopLoss)
    strategy.close("short", sema_exit)

//Command to close all trades outside of timeframe
if (not inDateRange)
    strategy.close_all()

I've tried two exit.strategy and this isn't possible because you cant have two exit conditions for one position ID, however I can see on the charts that the script above isn't exiting when there is a close on the other side of my exitEMA.
I also tried when = cross(close, exitEMA) but its the same outcome.
Any ideas much appreciated, is strategy.close and strategy.exit conflicting without throwing an error somehow?


text:
Q: Add to dictionary inside a nested object in Firestore? I have a document of jobs posted and inside each job I have a fields for the details of the job. I want to keep tract of the applicants who applied to each job .
So at first I have an array of applicants, but I later research and realised that it's not possible to add to the array.
The other option people suggested is that I keep a dictionary of the user reference and a boolean like this
So now I want to add to that applicants object , I tried but with no success. I will really appreciate it if someone points me to the right direction.
I am also open to other suggestion on how I should handle this problem.
Another option I am thinking is to have a sub collection but then I will have to query for that separately which I am trying to avoid .


text:
Q: How to filter VCF file with a list CHR or contig IDs? I need to subset/filter a SNP vcf file by a long list of non-sequential contig IDs, which appear in the CHR column. My VCF file contains 13,971 contigs currently, and I want to retain a specific set of 7,748 contigs and everything associated with those contigs (all variants and genotype information etc.).
My contig list looks like:
dDocent_Contig_1
dDocent_Contig_100
dDocent_Contig_10000 etc.
I am considering the following script:
vcftools --vcf TotalRawSNPs.vcf --chr dDocent_Contig_1 --chr dDocent_Contig_100 (etc...) --recode --recode-INFO-all --out FinalRawSNPs
where I list every contig ID individually with a --chr flag before. For this --chr flag, I cannot feed it a text file of contig IDs to keep, which would be ideal. If I list all contigs individually, it'll create a massive script in the command line.
I've seen options for filtering by a list of individuals, but not any clear option for filtering by CHR/contig IDs only. Is there a more efficient way to filter my vcf file by CHR/contig?


text:
Q: ¿Cómo seguir ejecutando script.sql cuando ocurre un error? ¿Es posible continuar con la ejecución de un script SQL al encontrar un error? Por ejemplo, si la columna es not null y se le asigna valor null, ¿es posible continuar con la ejecución? Y si es posible, ¿qué comando debería ejecutar?
CREATE TABLE usuarios (
    id_usu SERIAL,
    nom_usu VARCHAR(50) NOT NULL,
    log_usu VARCHAR(40) NOT NULL,
    pas_usu VARCHAR(40) NOT NULL,
    niv_adm BOOLEAN,
    PRIMARY KEY(id_usu)
);

Allí tenemos la tabla con valores NOT NULL. Si volcamos datos en ella y los valores son null no se seguirá ejecutando la consulta.
INSERT INTO usuarios (nom_usu, log_usu, pas_usu, niv_adm) VALUES (null, 'ADD', 'XXXXX', 1);
INSERT INTO usuarios (nom_usu, log_usu, pas_usu, niv_adm) VALUES ('CHRIS', 'ADD', 'XXXXX', 1);

Y el segundo INSERT no procederá a volcar sus datos que son del tipo correcto.

A: En PgAdmin, puedes ejecutar el script usando la opción en el menú Query --> Execute pgScript. O puedes usar F6.
En ambos casos, el script debería ejecutarse por completo, aún si ocurren ciertos errores.
Otra opción es de ejecutar el script usando el programa psql en vez de PgAdmin. El comportamiento por defecto de psql es de continuar ejecutando cuando ocurre un error. Puedes usar el comando siguiente para ejecutar el script:
\i c:/path/script.sql


text:
Q: import file and convert too pandas Using python and pandas i want to achieve the following:
i have about 600 json files with the following file format:
User Name: ǝuuǝıɹpɐ\nAll Tags: Delightful Followers\t|\tlibtards\t........|\tExpressionEngine\t|\t\nYour Tag:

i want to create a pandas DataFrame for all the files and have it look like this
User name     All Tags                                       Your tag
ǝuuǝıɹpɐ     Delightful Followers\t|\tlibtards\t....
.             .
.             .

i tried usign the following code:
 data = pd.read_csv('D:/datasets/edx1/word_cloud/557563.json', sep="\n", header=None)

which gives me the following DataFrame
0   User Name: ǝuuǝıɹpɐ
1   All Tags: Delightful Followers\t|\tlibtards\t|...
2   Your Tag:

Also im not sure why the json file looks the way it does, reading online it says that json files are dictionaries but it doesnt seem to be the case here.

A: 1) Iterate over files, for instance by using os.listdir() on the input directory: docs
2) for each file, open (exact procedure depends on your Py version) and convert the file into a Python dictionary using json.load() from the json module, docs. This will turn the json into a standard dict.
3) you can convert these dictionaries into pandas DataFrames by using from_dict() : docs.


text:
Q: How to log errors in browser (error view) instead of blank screen in React I have a React application which is not created with create-react-app. I would like to add a error handling functionality but I have no idea how:
When there is an error, instead of getting a blank page and errors in console, in development, how do I enable this functionality in a React application
where it shows the error stack in the browser?
Do I have to write the code for it or there is a react configuration that I can just enable or should I use a library to achieve this?

EDIT:
Above image is what I want to see as an error report in my browser when there is an error. It is not an error I am trying to solve.

A: Try Error Boundaries . Add those in your Root Level to catch all errors inside that.


text:
Q: How to sample a mip level in glsl using textureLod? How do I go about sampling a mip level in glsl using textureLod()?
From what I know, mipmap LOD can only be "explicitly" accessed through the vertex shader (although not sure if it's supported in version 420, as most of the documentation is outdated). Second, you need to define the mipmap level-of-detail by setting texture parameters, such as GL_TEXTURE_MAX_LEVEL and GL_TEXTURE_BASE_LEVEL.
In my code, I define these texture parameters after calling glCompressedTexImage2D:
glTexParameteri(texture_type, GL_TEXTURE_MIN_FILTER, min_filter);
glTexParameteri(texture_type, GL_TEXTURE_MAG_FILTER, mag_filter);
glTexParameteri(texture_type, GL_TEXTURE_MAX_LEVEL, 9);
glTexParameteri(texture_type, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(texture_type, GL_TEXTURE_WRAP_S, wrap_s);
glTexParameteri(texture_type, GL_TEXTURE_WRAP_T, wrap_t);

Next, I use this code for each binding each texture sample (types such as albedo map ect):
glActiveTexture(GL_TEXTURE0 + unit);    // Set active texture type
glBindTexture(GL_TEXTURE_2D, id);   // Bind the texture object

Finally, here is my shader code:
Vertex:
#version 420 core

out vec3 _texcoord;
out vec4 _albedo_lod;

uniform sampler2D albedo;   // Albedo and specular map

void main()
{
    _texcoord = texcoord;
    _albedo_lod = textureLod(albedo, vec2(_texcoord.st), 2.0);
}

With the attaching fragment:
#version 420 core

layout(location = 0) out vec4 gAlbedo;  // Albedo texel colour

in vec3 _texcoord;
in vec4 _albedo_lod;

void main()
{
    gAlbedo = _albedo_lod;  // Assign albedo
}

Now for some reason, no matter what LOD value I input, the result always resorts to this:

Which seems to be the very last mip level (despite what value I input). Bearing in mind I'm packing 10 mip levels as a .dds file. When however I manually set the base mip level via the texture parameter GL_TEXTURE_BASE_LEVEL, it works.
So all in all, Why won't it sample the correct mip level in glsl using textureLod? Is this somewhat deprecated in version 420?
EDIT: Here is the code for loading the dds file:
// This function imports a dds file and returns the dds data as a struct
inline GLuint LoadDds(std::vector<std::string> file, size_t &img_width, size_t &img_height, size_t &num_mips, GLvoid* data, GLint wrap_s, GLint wrap_t, GLint min_filter, GLint mag_filter, size_t texture_type, bool anistropic_filtering)
{

    // Create one OpenGL texture
    GLuint textureID;
    glGenTextures(1, &textureID);

    // "Bind" the newly created texture : all future texture functions will modify this texture
    glBindTexture(texture_type, textureID);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    for (unsigned int i = 0; i < file.size(); i++)  // For each image...
    {
        FILE *fp;

        unsigned char header[124];
        unsigned int height;
        unsigned int width;
        unsigned int linearSize;
        unsigned int mipMapCount;
        unsigned int fourCC;
        unsigned int components;
        unsigned int format;
        unsigned int bufsize;
        unsigned char* buffer;

        /* try to open the file */
        errno_t err;
        err = fopen_s(&fp, file[i].c_str(), "rb");
        if (fp == NULL)
            return 0;

        /* verify the type of file */
        char filecode[4];
        fread(filecode, 1, 4, fp);
        if (strncmp(filecode, "DDS ", 4) != 0)
        {
            fclose(fp);
            return 0;
        }

        /* get the surface desc */
        fread(&header, 124, 1, fp);

        height = *(unsigned int*)&(header[8]);
        width = *(unsigned int*)&(header[12]);
        linearSize = *(unsigned int*)&(header[16]);
        mipMapCount = *(unsigned int*)&(header[24]);
        fourCC = *(unsigned int*)&(header[80]);
        bufsize = mipMapCount > 1 ? linearSize * 2 : linearSize;
        buffer = (unsigned char*)malloc(bufsize * sizeof(unsigned char));

        fread(buffer, 1, bufsize, fp);

        /* close the file pointer */
        fclose(fp);

        components = (fourCC == FOURCC_DXT1) ? 3 : 4;
        switch (fourCC)
        {
        case FOURCC_DXT1:
            format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
            break;
        case FOURCC_DXT3:
            format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
            break;
        case FOURCC_DXT5:
            format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
            break;
        default:
            free(buffer);
            return 0;
        }

        unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16;

        unsigned int offset = 0;
        for (unsigned int level = 0; level < mipMapCount && (width || height); ++level)
        {
            unsigned int size = ((width + 3) / 4) * ((height + 3) / 4) * blockSize;
            glCompressedTexImage2D(texture_type != GL_TEXTURE_CUBE_MAP ? GL_TEXTURE_2D : GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, level, format, width, height,
                0, size, buffer + offset);

            if ((level < 1) && (i < 1))     // Only assign input variable values from first image
            {
                img_width = width;  // Assign texture width
                img_height = height;    // Assign texture height
                data = buffer;  // Assign buffer data
                num_mips = mipMapCount;     // Assign number of mips
            }

            offset += size;
            width /= 2;
            height /= 2;
        }

        if (anistropic_filtering)   // If anistropic_filtering is true...
        {
            GLfloat f_largest;  // A contianer for storing the amount of texels in view for anistropic filtering
            glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &f_largest);     // Query the amount of texels for calculation
            glTexParameterf(texture_type, GL_TEXTURE_MAX_ANISOTROPY_EXT, f_largest);    // Apply filter to texture
        }

        if (!mipMapCount)
            glGenerateMipmap(texture_type); // Generate mipmap

        free(buffer);   // Free buffers from memory
    }

    // Parameters
    glTexParameteri(texture_type, GL_TEXTURE_MIN_FILTER, min_filter);
    glTexParameteri(texture_type, GL_TEXTURE_MAG_FILTER, mag_filter);
    glTexParameteri(texture_type, GL_GENERATE_MIPMAP, GL_TRUE);
    glTexParameteri(texture_type, GL_TEXTURE_MAX_LEVEL, 9);
    glTexParameteri(texture_type, GL_TEXTURE_BASE_LEVEL, 0);
    glTexParameteri(texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(texture_type, GL_TEXTURE_WRAP_S, wrap_s);
    glTexParameteri(texture_type, GL_TEXTURE_WRAP_T, wrap_t);

    // Set additional cubemap parameters
    if (texture_type == GL_TEXTURE_CUBE_MAP)
        glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, wrap_s);

    return textureID;   // Return texture id
}

And here is an image of each mipmap level being generated using NVIDIA's dds plugin:

A: Since you sample per vertex this seems to be exactly the expected behavior.
You say the mip level parameter has no influence, but from what I can see the difference should only be noticeable once the pixel density goes under the vertex density and values starts averaging out. This might however never happen if you don't store the entire mipchain, since the lowest resolution might still have enough definition (I can't really tell from the screen capture, and I can only guess the model's tesselation).
Since you're generating the mipchain manually though you could easily test out with different flat colors for each level and see if they're indeed properly fetched (and actually if you're unsure about the importer it might be worth it to try it out in the pixel shader as well first).