VSCode exiting C code with code=3221225477

Question: I wrote the C program below using VSCode on my old 64 bit Windows 10 Enterprise computer. It worked perfectly when I ran it on there, and it also works perfectly when I run it on this online C compiler. However, when I try to run it on VSCode on my new 64 bit Windows 11 Home computer, it exits with code=3221225477. Does anyone know what I should do about this? Thanks.
What I've tried so far:

I've tried writing programs to test each of the functions in it and they all ran perfectly fine on VSCode on my new computer; I'm only getting problems when I run the entire program
Because my new computer has Norton installed on it, it likes to think that some of my C programs are viruses and stops them from being executed. However, I made a folder that I have told it not to interfere with and copied my program there. I still got code=3221225477 when I ran it.

/*
File name       : triangulation.c
Author          : kene02
Last modified   : 20/12/2021
License         : All rights reserved

Description:
Uses triangulation to find where a point is.
*/

#define _USE_MATH_DEFINES

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

// Function declarations
float distance_between(float *point_1, float *point_2);
float find_gradient(float *point_1, float *point_2);
char *bearing(float *point_1, float *point_2);
float *triangulate(float *a, float *b, float *c, float *d);

int main()
{
    // Allocating memory for coordinates
    float *point_a = (float *)malloc(2*sizeof(float));
    float *point_b = (float *)malloc(2*sizeof(float));
    float *point_c = (float *)malloc(2*sizeof(float));
    float *point_d = (float *)malloc(2*sizeof(float));

    point_a[0] = 328;
    point_a[1] = -1445;

    point_b[0] = 325;
    point_b[1] = -1455;

    point_c[0] = 286;
    point_c[1] = -1567;

    point_d[0] = 292;
    point_d[1] = -1575;

    // Print coordinates
    printf("\nA(%.1f, %.1f)\t", point_a[0], point_a[1]);
    printf("B(%.1f, %.1f)\n", point_b[0], point_b[1]);
    printf("C(%.1f, %.1f)\t", point_c[0], point_c[1]);
    printf("D(%.1f, %.1f)\n\n", point_d[0], point_d[1]);

    // Evaluate point of intersection
    float *point_x = triangulate(point_a, point_b, point_c, point_d);

    // Evaluate bearings
    char *bng_ba = bearing(point_b, point_a);
    char *bng_dc = bearing(point_d, point_c);
    char *bng_xa = bearing(point_x, point_a);
    char *bng_xc = bearing(point_x, point_c);

    if (strcmp(bng_ba, bng_xa) != 0 || strcmp(bng_dc, bng_xc) != 0) {
        printf("Lines do not intersect.\n\n");
    } else {
        float length_xa = distance_between(point_x, point_a);
        float length_xc = distance_between(point_x, point_c);

        printf("Point of intersection\t\t\t: ");
        printf("X(%.1f, %.1f)\n", point_x[0], point_x[1]);
        printf("Distance and bearing of X from A\t: ");
        printf("%.1f units, %s\n", length_xa, bng_xa);
        printf("Distance and bearing of X from C\t: ");
        printf("%.1f units, %s\n\n", length_xc, bng_xc);
    }

    return 0;
}

/**
 * @brief distance_between function: finds the distance between two points.
 *
 * @param point_1 the (x, y) coordinates of the 1st point
 * @param point_2 the (x, y) coordinates of the 2nd point
 * @return the distance between the two points
 */
float distance_between(float *point_1, float *point_2)
{
    float x_diff = point_2[0] - point_1[0];
    float y_diff = point_2[1] - point_1[1];
    float distance = sqrt(pow(x_diff, 2) + pow(y_diff, 2));
    return distance;
}

/**
 * @brief find_gradient function: finds the gradient of the line between two
 * points.
 *
 * @param point_1 the (x, y) coordinates of the 1st point
 * @param point_2 the (x, y) coordinates of the 2nd point
 * @return the gradient of the line between the two points
 */
float find_gradient(float *point_1, float *point_2)
{
    float x_diff = point_2[0] - point_1[0];
    float y_diff = point_2[1] - point_1[1];
    float gradient = y_diff/x_diff;
    return gradient;
}

/**
 * @brief traingulate function: finds the point of intersection of the line
 * passing through points A & B and the line passing though points C & D.
 *
 * @param a the coordinates of point A
 * @param b the coordinates of point B
 * @param c the coordinates of point C
 * @param d the coordinates of point D
 * @return the point at which the lines intersect
 */
float *triangulate(float *a, float *b, float *c, float *d)
{
    float *intersect = (float *)malloc(2*sizeof(float));

    float g1 = find_gradient(a, b);
    float g2 = find_gradient(c, d);

    if (a[0] == b[0]) {
        intersect[0] = a[0];
        intersect[1] = c[1] + (a[0]-c[0])*g2;
    } else if (c[0] == d[0]) {
        intersect[0] = c[0];
        intersect[1] = a[1] - (a[0]-c[0])*g1;
    } else {
        intersect[0] = ((a[1]-c[1]) + c[0]*g2 - a[0]*g1)/(g2-g1);
        intersect[1] = (a[1]*g2 - c[1]*g1 + (c[0]-a[0])*g2*g1)/(g2-g1);
    }
    return intersect;
}

/**
 * @brief bearing function: finds the compass bearing of point_1 from point_2
 *
 * @param point_1 the coordinates of the point to find the compass bearing of
 * relative to point_2
 * @param point_2 the coordinates of the reference point from which the compass
 * bearing of point_1 will be measured
 * @return the compass bearing of point_1 from point_2
 */
char *bearing(float *point_1, float *point_2)
{
    const float RAD_DEG_RATIO = 180/M_PI;

    float x_diff = point_1[0] - point_2[0];
    float y_diff = point_1[1] - point_2[1];
    float gradient = y_diff/x_diff;

    char *bearing = (char *)malloc(7*sizeof(char));
    if (x_diff == 0 && y_diff > 0) {
        sprintf(bearing, "N");
    } else if (x_diff == 0 && y_diff < 0) {
        sprintf(bearing, "S");
    } else if (x_diff > 0 && y_diff == 0) {
        sprintf(bearing, "E");
    } else if (x_diff < 0 && y_diff == 0) {
        sprintf(bearing, "W");
    } else if (x_diff > 0 && y_diff > 0) {
        float angle = 90 - RAD_DEG_RATIO*atan(gradient);
        sprintf(bearing, "N %.2f E", angle);
    } else if (x_diff < 0 && y_diff > 0) {
        float angle = 90 + RAD_DEG_RATIO*atan(gradient);
        sprintf(bearing, "N %.2f W", angle);
    } else if (x_diff < 0 && y_diff < 0) {
        float angle = 90 - RAD_DEG_RATIO*atan(gradient);
        sprintf(bearing, "S %.2f W", angle);
    } else if (x_diff > 0 && y_diff < 0) {
        float angle = 90 + RAD_DEG_RATIO*atan(gradient);
        sprintf(bearing, "S %.2f E", angle);
    }

    return bearing;
}

Comment: Please try to find out, where exactly your program crashes, read "[How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)" for this. Your debugger will tell you the line of the crash.
Comment: Please provide a more [mre].
Comment: @thebusybee Just tried that. It also runs perfectly fine in the debug console.
Comment: @thebusybee What I can tell you, however, is that when I try to run it from Powershell, it prints the input coordinates and then just exits.
Comment: What are the angles you are getting? For example, if it is 120.22, then it may try to write `"S 120.22 E"`, 10 characters (before considering null terminator), into the address of bearing. But your malloc is `malloc(7*sizeof(char))`
Answer: 3221225477 decimal is gibberish. Translated to hex you get 0xC0000005, which is Windows' error code for access violation (also known as "seg fault"). The most likely cause is array out of bounds access.
The bug is here: malloc(7*sizeof(char)); creates too little memory to contain what your sprintf might produce. This can only hold 6 characters + the mandatory null terminator. Memory is cheap, so change this for something with margins like:
char *bearing = malloc(20);

Why you keep using malloc all over the place to allocate tiny amounts of memory, I have no idea. All you achieve with that is to slow down everything and create potential for memory leaks.
It's better practice to have your function work with caller allocated memory whenever possible. It is not good design to mix up memory allocation and the actual algorithm in the same function.
Comment: "Why you keep using malloc all over the place to allocate tiny amounts of memory, I have no idea. All you achieve with that is to slow down everything and create potential for memory leaks." Would you be able to suggest a better way to do the same thing then? I'm still fairly new to C.
Comment: @KenEly As suggested, caller allocation, local is possible, dynamic in case it is large amounts and the amount needs to be determined in run-time.


Get string inside html tag - VB.Net

Question: So, i have this html code:

    Hello world!

I want to get text "Hello world!". I've tried with my regex code below, yet it didn't work.
Dim findtext2 As String = "(?<=
)(.*?)(?=
)"
Dim myregex2 As String = TextBox1.Text 'HTML code above
Dim doregex2 As MatchCollection = Regex.Matches(myregex2, findtext2)
Dim matches2 As String = ""
For Each match2 As Match In doregex2
    matches2 = matches2 + match2.ToString + Environment.NewLine
Next
MsgBox(matches2)

Comment: Seems to me you're missing an end quote on line 2. Not actually a .NET expert, so I could be wrong :P
Comment: **'** character is used for comments, it doesn't need ending.
Comment: Well, that's confusing. In basically every other language, it's either a syntax error or a string/char literal.
Comment: Just ignore that comment, it's meant to people reading code and it doesn't affect it either.
Comment: Extracting html with regex's is a nuisance and a bit error prone. Maybe try [the html agility pack](http://htmlagilitypack.codeplex.com/). Or if it's xhtml  then use one of the xml api's
Comment: Perhaps the most famous post on SO addresses [Parsing HTML with RegEx](http://stackoverflow.com/a/1732454/1070452)
Comment: You should definitely use HTML Agility Pack rather than Regex to parse HTML.
Comment: I would if i know how to do it.
Answer: As was mentioned in comments don't use ReGex for parsing html code.
Instead use LINQ to XML
Dim html As XElement =

Hello word!

Dim values As String =
    html.Descendants("div").
         Where(Function(div) div.Attribute("class").Value.Equals("keyboard")).
         Select(Function(div) div.Element("p").Value)

For Each value As String in values
    Console.WriteLine(value);
End For

Comment: Gives error (on first line): **Value of type 'String' cannot be converted to 'System.Xml.Linq.XElement**.
Comment: Are you wrapped html code with the quotes? If so remove quotes. [XML Literals Overview (Visual Basic)](https://msdn.microsoft.com/en-us/library/bb384629.aspx)
Comment: I've put it in TextBox and wrote **Dim html As XElement = TextBox1.Text**.
Comment: Then use `Dim html As XElement = XElement.Parse(TextBox1.Text);`

Get string inside html tag - VB.Net


How can I avoid this markup is filtered out from my block?

Question: I generated a widget on pinterest. The result is the following:

pinit.js is included in the theme and is available in the page.
I added a block with the following code.

When I saved the block (I used CKEditor), it cleaned. Actually, I don't know if it is cleaned by CKEditor or the full HTML filter.
How can I find out which of those is cleaned out the markup?

If it's due to CKEditor, how can I solve it? The advanced content filter is disabled.
If it's due to full HTML filter, how can I configure it so that only this non compliant syntax is allowed?

NOTE: In the full HTML filter, the checkbox Correct faulty and chopped off HTML is NOT checked.
Comment: In the Full HTML input format do you have "Limit allowed HTML tags" or any other HTML limiting filters? It is possible to have them enabled even though it is called Full HTML.
Answer: I've had the same issue with CKEditor removing classes in the past, Full HTML is not the issue.
Add the below code to the end of your CKEditors config.js file, which is found within the CKEditor library code.
CKEDITOR.config.allowedContent = true;

You might find that the file is called ckeditor.config.js and that this is the file that needs to be changed rather than the default config.js. This file can be found in the root of the CKEditor module.
Comment: Perfect solution !!!


Show that $\int_{- \infty}^{\infty} \frac{\sin x}{x+i} dx = \frac{\pi}{e}$

Question: This is question 37 from Exercises 6.6.2 from Dennis Zill's An Introduction to Complex Analysis.

Show that $$\int_{- \infty}^{\infty} \frac{\sin x}{x+i} dx = \frac{\pi}{e}$$

I am not sure how to proceed. There is a hint to use $\sin x = \dfrac{e^{ix} - e^{-ix}}{2i}$ for real $x$.
If I try to find the residue of $\dfrac{\sin z}{z+i}$ at $z=-i$, I get $$\text{Res}\left(\dfrac{\sin z}{z+i};-i\right) = -i \sinh 1.$$
But I am not sure what contour to even use, so I cannot relate these numbers to the integral in the question.
I tried to use a semicircular contour in the lower half plane. I see that $|e^{iz}| = e^{-y} \leq e^{R}$ for $z=x+iy$ on a semicircle of radius $R$. I am not sure how to proceed since this would mean the integral does not vanish. Could someone please offer some guidance? Thank you very much.
Comment: You can use a different contour for the $e^{ix}$ piece vs. the $e^{-ix}$ piece.
Answer: I managed to solve it using the hint from Ian.
I split the integral into $2i I_1 = \int_{\mathbb{R}} \dfrac{e^{ix}}{x+i} dx$ and $2i I_2 = \int_{\mathbb{R}} \dfrac{-e^{-ix}}{x+i} dx
.$
For the first integral, consider the contour $\Gamma_R$ consisting of the semicircle of radius $R$, in the upper half plane, denoted $\gamma_R$, and the line segment joining $-R$ to $R$. Note that the function is holomorphic on and inside this countour. Thus, using Cauchy's Integral formula, $$\int_{\Gamma_R} \dfrac{e^{iz}}{z+i} dz = \int_{-R}^R \dfrac{e^{ix}}{x+i} dx + \int_{\gamma_R} \dfrac{e^{iz}}{z+i} dz=0. $$
On $\gamma_R$, we have $|e^{iz}| = e^{-R \sin \theta}$. By the Estimation lemma and Jordan's inequality, the modulus of the integral will converge to $0$ as $R \to \infty$. Thus the integral converges to $0$ as $R \to \infty$. Thus we conclude that $I_1 =0$.
For $I_2$, we can substitute $u = -x$, and thus obtain get $2iI_2 = \int_{\mathbb{R}} \dfrac{-e^{iu}}{-u+i} du$. Note that the function has a residue of $1/e$ at the pole $z=i$. We apply Cauchy's Residue Theorem and the same method as in the earlier part to finally obtain that $$2iI_2 = 2 \pi i/e.$$ We can also use a contour in the lower half-plane, but the substitution we used transforms this into the first case which we already solved.
Hence, we obtain the required answer.


Setting up SSL - https works, http not working

Question: Update: A temp solution I found was to just redirect all http requests to https.
I have been working on setting up SSL on my website. It is like on a Rails.
I use nginx with unicorn. I bought the certificate from GoDaddy. Then I set it up and generated the CSR at /etc/nginx/ssl by following the instructions of this document.
Then I copied the text of the generated .csr file and used it to issue the certificate from GoDaddy. After the certificate was issued I downloaded the key bundle generated on GoDaddy and followed the instruction found on this document.
Then configured my /etc/nginx/sites-enabled/mysite.conf file:
(I added the following lines under the server { ... }
  listen 443;
  ssl on;
  ssl_certificate /etc/nginx/ssl/mysite.crt;
  ssl_certificate_key /etc/nginx/ssl/mysite.key;

(I replaced listen 80 default; to listen 443;)
Then, I restarted the server and got the HTTPS://www.example.com working. The https was with green color and was showing that the certificate is fine.
However when I browse to HTTP://www.example.com I get an error: 502 Bad Gateway - nginx.
I am not sure what is causing this. Any clue?
If you need any other information let me know and I will post them.
My sites config:
/etc/nginx/sites-enabled/example.conf

upstream example {
  server unix:/u/app/example/shared/.sock fail_timeout=0;
}

server {
  listen 80;
  server_name  www.example.com;
  root   /u/app/example/current/public/;
  access_log  /u/app/example/shared/log/nginx.access.log;
  error_log  /u/app/example/shared/log/nginx.error.log;
  client_max_body_size 20M;

  try_files $uri/index.html $uri.html $uri @app;
  location @app {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://example;
        }
}

my /etc/nginx/nginx.conf
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events { worker_connections 1024; }

http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;
        server_tokens off;

         server_names_hash_bucket_size 64;
        # server_name_in_redirect off;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;
        upstream app_server { server 127.0.0.1:8080 fail_timeout=0; }

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_disable "msie6";
        gzip_types text/plain text/xml text/css text/comma-separated-values;

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

and the /etc/nginx/sites-available/default file is:
server {
        root /u/app/example/current/public;
        server_name _;
        index index.htm index.html;

        location / {
                try_files $uri/index.html $uri.html $uri @app;

        }

#       location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mp3|flv|mpeg|$
location ~* ^.+\.(jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|mp3|flv|mpeg|avi)$ {
                        try_files $uri @app;
                }

         location @app {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_redirect off;
                proxy_pass http://app_server;
    }

}

The log file when I had both:
listen 80;
listen 443;
was outputing 18.104.22.168 - - [28/Jul/2014:15:35:53 +0000] "-" 400 0 "-" "-"
Comment: Post the complete `server` blocks for your HTTP and HTTPS sites.
Comment: Can you please paste more details like nginx config file and logs, it will helps to identify issue
Comment: @MichaelHampton i included the config files
Comment: @VaibhavPanmand added the one log entry
Answer: To qoute your question:
 I replaced listen 80 default; to listen 443;

Do not replace listen 80.
Instead add listen 443.
to be more specific:
Qouting Alexander Azarov from stackexchange
The error says it all actually. Your configuration tells Nginx to listen on port 80
(HTTP) and use SSL. When you point your browser to `http://localhost`, it tries to
connect via HTTP. Since Nginx expects SSL, it complains with the error.

The workaround is very simple. You need two server sections:
server {
  listen 80;

  // other directives...
}

server {
  listen 443;

  ssl on;
  // SSL directives...

  // other directives...

}
Comment: Thanks for posting. I tried that before and I was getting this error: "400 Bad Request

The plain HTTP request was sent to HTTPS port"
Answer: You need to use:
listen 80;
listen 443 ssl;

in those virtualhosts where you want to use both https and http.
I would prefer redirect from http to https. The you need to make a separate virtual host for http, that redirects all requests to https version.
Comment: thanks for posting. Getting the same error as per Dennis' Nolte answer.
Comment: Can you post the complete configuration that caused this error?
Comment: I have included my config in the question
Comment: Your question includes only the configuration with `listen 80;` directive. What is the complete configuration when you get the `400 Bad Request` error?


Rotation of a Line Intersecting the Curve $y = x – \log(x)$ as $x \rightarrow \infty$.

Question: Let a straight line ("line 1") in the $xy$-plane have one end fixed at the origin $(0,0)$, and the other at a variable point $(x, x – \log(x))$ on the curve $y = x – \log(x)$. The domain of $x$ is the positive Real Numbers.
Let $A$ be the angle between line 1 and the positive $x$-axis, then $\tan(A) = (x – \log(x))/x$ which approaches 1 from below as $x \rightarrow \infty$. As $A = \pi/4$ is the only solution of $\tan(A) = 1$ in the positive quadrant, it seems line 1 rotates towards the straight line $y = x$ as $x \rightarrow \infty$.
I do not see any problem so far (although there may be one). My problem comes when I try to picture what is happening.
The gap between the curve $y = x – \log(x)$ and the straight line $y = x$, is $\log(x)$ which increases as $x$ increases. It therefore seems line 1 should be rotating away from the straight line $y = x$ instead of towards it.
These conclusions are contradictory. I would appreciate any help in pointing out where the error is.
Answer: This is not contradictory. This means that your intuition (the second argument) is wrong.
Let's denote $f(x)=x-\ln(x)$, $O$ the origin, $B(x,x)$ a point on the line $y=x$, $C(x,f(x))$ a point on the curve $y=f(x)$, and $P(x,0)$ on the $x$-axis.
Your question is: why the angle $\theta(x)=\angle BOC$ isn't diverging to $-\infty$ when the distance $BC$ tends to $\infty$?
That happens because the distance $OP$ is increasing way faster than the distance $BC$?
A clearer situation is when $f(x)=\frac{1}{2}x$. Clearly, the distance $BC$ tends to $\infty$, but the angle $\theta(x)$ is constant.
Comment: Thanks for your answer. I will need to think about it. Note in my question I was not asking about the divergence of the angle BOC. I was asking about the direction angle COP changes as x increases. Your example,  $f(x)=\frac{1}{2}x$, shows the angle COP could be independent of increasing separation from the straight line $y=x$ but I am asking about changes in angle COP when there is a dependence on separation.
Comment: The angle BOP being constant, knowing about the variations of COP is equivalent to know the variations of BOC. Since the question was involving BC, I was hoping that speaking about BOC gives a clearer picture.


iterating through variables within an object in python

Question: OK, this might be a very silly question, but...
I have an object x, which contains a number of pandas dataframes (df1,df2,df3 for sake of argument)
When the program has finished running, I want to export each of these dataframes to its own csv file. At the moment, I have a function within x that looks like this:
def export(self, path):
    self.df1.to_csv(path+"_df1.csv")
    self.df2.to_csv(path+"_df2.csv")
    self.df3.to_csv(path+"_df3.csv")

It works (I can just use x.export(somepath), but I keep having to change it because the data I want to keep in the object changes. Can anybody tell me if there is a way of simply iterating over all of the variables within an object (they are all the same format) and (in this case) dumping them all to their respective .csv files?
Thanks
Comment: @Will Then you could do `self.dataframes = [pd.DataFrame(), pd.DataFrame(), ...]` in `__init__` and instead of accessing `instance.df1` you would use `instance.dataframes[0]`. (Of course, you could also `pop` and `append` from that list.)
Comment: @Will of course a dict will work. Don't be afraid to try.
Comment: Have an instance variable `dataframes`, which is a list holding the dataframes?
Comment: wouldn't I then have to manually add all of the different variables to this list? - that's what I'm trying to avoid. I've only used three in the example, but there are a lot more in the original code!
Comment: At one point you will have to specify which dataframes you want to export. Might as well keep them in a list. I have a sense that your are trying to do something weird and your question is lacking information.
Comment: Then you should add more detail. Do the names follow a pattern, do you create them manually or with some process...?
Comment: why don't you go through all the instance variables and check if its of dataframe type and do what you want on that
Comment: Again, why don't you create that list in `__init__`. At one point you will have to specify which dataframes your object holds ANYWAY, so why not put them into a list from the beginning? (You could also write methods to add or discard from the object wrapping the list)
Comment: so @timgeb I'm a bit confused... I understand (I think) the idea that I should have a list of these variables when I `__init__` but how would that stop me having to type them all out twice? That's all I'm really looking for, so sorry if I've been unclear or it's a daft question.
Comment: @Will I still don't understand why you think you would have to type them out twice.
Comment: @timgeb Perhaps I'm being stupid, but I assumed you have to define the variables self.df1 = pd.DataFrame() self.df2 = ... etc. and then define a list containing each variable [self.df1, self.df2, etc. Have I got this wrong? Or is there a clever way of doing this?
Comment: @Will how do you set the attributes `df1`, `df2` on an instance of your class right now?
Comment: @timgeb, The object is a wrapper for a  lot of similar dataframes.
When I set up the instance I initialise them within `def __init__(self):` so a series of statements like `self.df1 = pd.DataFrame() ` I then have a couple of functions within the object which summarise and export the data. I set the specific data as `instance.df1 = someDataFrame` within the main script
Comment: Thanks @timgeb, I do appreciate you taking the time to explain. I was wondering if this would work as a dict? I'm guessing that I could then keep the halfway sensible naming convention, while maintaining the list functionality?
Answer: You can iterate over __dict__ to retrieve the attribute names and data frame objects.  You can check the object types to avoid calling .to_csv on something that is not a data frame.
Here is some example code that prototypes the solution.
class A():
    def __init__(self):
        self.x = pd.DataFrame([[1,2],[3,4]])
        self.y = pd.DataFrame([[5,6],[7,8]])

    def export(self, path):
        for k, v in self.__dict__.items()
            if isintance(v, pd.DataFrame):
                v.to_csv('{}_{}.csv'.format(path, k)

a = A()
a.export('dataframes')

Comment: @timgeb It doesn't matter if it's inefficient, the difference is less than milliseconds.
Comment: @timgeb, do give us an efficient method
Comment: I downvoted because this is - in my opinion - horrible and inefficient Python. Keep an iterable holding the dataframes. Create it in `__init__`.
Comment: @timgeb, cool, agreed with having a list of all the dataframes.
Comment: @cal97g First of all, you don't know how large the `__dict__` of OP's objects can get, so your estimated time is pure speculation. Second, readability and the principles of duck typing are violated. We can avoid explicit instance checks here and make the code faster at the same time without any cost - so we should do it.
Comment: We don't need to check the instance types, the OP said all attributes are dataframes. Say the OP needs to perform some action on one of the dataframes, a list is much less convenient than an attribute.
Comment: @timgeb I agree with you.  Instantiating the object using an iterable to hold the dataframe references is the most lightweight solution.  However, I was trying to address the original question as posed by the author.
Comment: IMO type consistency of all object attributes is an implementation detail you should never write your code around. You can't extend it reasonably.
Comment: @James I see. I would give you an upvote if you mentioned how OP can solve his problem in a better way. At the moment, you are answering an XY problem in my opinion. (edit: I'll check back later)
Comment: @James, thanks I appreciate you taking the time to answer this, but I'm getting a bit confused. There seem to be a lot of people who think I've misunderstood something important. Have I missed something obvious? I was trying to get round typing out all my instance variables twice, but wouldn't I have to do that if I put them in a list as well?


What is this image stored as?

Question: I want to extract these telephone numbers from the website, either as an image or if possible as a string.
Here is an example from the website: Link
As you can see the telephone number is an image.
However I cant seem to view the image when I open the image source:

But when put into html and viewed in a browser, you can see the image fine.
Comment: This question appears to be off-topic because it isn't about programming.
Answer: It's a solution to prevent people like you from scraping their website :)
The url http://www.callmyname.sg/search/display_phone_number/VUhkVE1WOW5BV1lFWWxSbVhUdFRObGMzQlRBRU9nPT0= leads to a script that generates the image - probably based on the argument.
VUhkVE1WOW5BV1lFWWxSbVhUdFRObGMzQlRBRU9nPT0=
Since it ends with an equals sign, I tried to decode it as base64:
UHdTMV9nAWYEYlRmXTtTNlc3BTAEOg==
Now it looks even more like base64, so I tried another round:
PwS1_gfbTf];S6W70:
So it's clearly not plaintext (or not encoded with base64), which would be ridiculous and would let you extract the number this way. They either use some special cipher, or store the numbers in database with this as identifier.
I don't think you can steal the phone number easily, only using OCR perhaps.

When you visit the URL, you will get garbage, since they do not send proper MIME header
�PNG  IHDR�,���tRNS���7X}4IDATx���_HZo�g�� E��p��l��EHTx!]�DtQ�M�.x3��.dx�*b]Dl"]�D���bQq.B����Z2$��:ȡ�wq��9�s���Cx>W�}���ٳ��ڶ����]���Ǐ�/_���ݿ���ahh���\q����������555�=���*�"�*�*�f�����}uu�e�d2���o����?00p����J%ȴds���BB�˲�`�`0RJy����n�{cc�e�H$b�ۻ����(�~�_����A4�Z��_�V|��J�w�����t:��333.��ƕ������+^����L`���֑��W��3�X�"    y���$p'U"��F���y���z&�ioo��萟�*� ����\�L&Sx����p�e���ׯ_R��y�J%�~����|qq��|e�Z%:�J�{��q��nW�ՉD"�J��~�n4��������̔Ty���qF���>BwGa�z����������8��ߡc�f��B�>!�Ub�N�s���|�F�^/B���Lj��i��NfJ��͛D"����� o!t��`����fvv�eم��V���D)�����x���d2966&�n� ^,0O4��(!D��l�h46�-�~��Tً>B�"�Q�>,�P��ok@U \�BU,�P���=G SA+GIEND�B`�
but it's really just ordinary PNG image:
img http://www.callmyname.sg/search/display_phone_number/VUhkVU5scGlBV1lDWWdFelVEUUhZQWRvQlRZR013PT0=
Answer: It's actually a png-file, generated by a computer before being displayed. You can reference it fine from any other page though, and you should also be able to download it easily (right click, save as ...) Note: I tested this, make sure you save the image with the extension .png and not .html which it will default to.

Answer: It's a PNG image, but the server doesn't specify the right content header. It tells your browser that is't an html page in UTF-8 encoding, so you just see some garbage (including the letters PNG at the start).
The  tag though doesn't know how to display text so it just tries to load it as an image (and with success).
I don't see a way to extract the numbers in any other way than just reading the image. Because it contains only numbers and will have a similar format all the time, maybe you can find a simple way to parse it instead of using a full fledged OCR library.

What is this image stored as?


when finding the highest degree in a polynomial why do we add the exponents of each variable in a term?

Question: For example, in the expression:
$$x^3y^2+4x^2$$Why is the highest degree 5 and not 3? why do we have to add the exponents together when they are different variables to find the highest degree?
Comment: It's really nothing but just definition. The degree of a polynomial is by definition the highest degree of it's monomials. And the degree of monomial is by definition the sum of degrees of all variables that exist in this monomial.
Comment: That depends entirely on what question you are wanting to ask and what meaning of the word "degree" is in this context.  Some times you want to talk about the highest combined degree.  Some times you want to talk about highest degree of $x$ only.  Some times you want to talk about something else entirely.  It all depends on context and context is entirely up to you and/or your teacher.
Comment: It is common practice to consider the sum of degrees here since that way it works like we are used to for single variable scenarios... namely that you have $\deg(f\cdot g)\leq \deg(f)\cdot \deg(g)$.  See [this wiki page](https://en.wikipedia.org/wiki/Polynomial#Classification).
Comment: the context is just to find the degree of the expression. So I interpret that just means what is the highest degree of the expression
Comment: Just to emphasize... when you are in a scenario like this where there are multiple possible interpretations and multiple possible answers... that does not necessarily mean that certain answers and interpretations are incorrect or not useful.  Those are just the right answers to different questions than one another.
Comment: oh, ok thanks I guess I just didn't understand that by definition that's how it is. I thought there was a mathematical reason/explanation behind it
Comment: My guess is that it originally arose from how area and volume units combine. The product of length and width of a rectangle, $LW,$ is an area, the volume of a cylinder is $\pi r^2h,$ the volume of a rectangular solid is $LWH,$ etc. Besides the geometric names which are still used -- square for 2nd power and cube for 3rd power -- higher powers used to have geometric names such as "square-square", "square-cube", "cube-cube", etc. See the various answers and comments to the mathoverflow question [History of powers beyond squares and cubes](https://mathoverflow.net/q/181244/15780).
Comment: See [this post](https://math.stackexchange.com/questions/3555616/degree-formula-for-multivariable-polynomial).
Answer: This is a situation where there are more than
one related but different variants of a concept.
First, for monomials, there is the concept of
the highest degree of the variables. This can
apply to a fixed variable or all of the variables.
The other variation is the total degree of all
of the variables.
These variations make sense and are useful in some
contexts and not in others.
For a a polynomial,
define its degree to be the maximum of the degrees
of its monomials. Thus, there is the total degree
of a polynomial and the highest degree over all of
the variables or the highest degree over a fixed
variable.
For example, your polynomial $\,x^3y^2+4x^2\,$ has
total degree is $5.$ The highest degree over all of
the variables is $3$ which is also the highest degree
over $x$ while the highest degree over $y$ is $2.$


Using StringFormat with XAML Binding to inject folder into image path

Question: I'm trying to allow for multiple icon sizes depending on certain conditions. To do this, I have a bunch folders: 'Images\Icons\...\*.png' where the ... is the size (16, 32, 64, 128, 256, etc.) Each folder contains all the icons optimized for the given size.
My problem  I can't seem to specify a folder in the image source path... i.e.:
<Image x:Name  = "img"
       Stretch = "None"
       Source  = "{Binding StringFormat=Images\Icons\{0}\Multi.png,
                   RelativeSource={RelativeSource Self},
                   Path=Parent.Parent.Tag}" />

For now, I'm just storing the folder name in the grandparent's tag (I will be binding to something else in the future, but right now I'm just trying to piece this bit together). When I try to build the above xaml, I get an error:
The text \Multi.png ... is not allowed after the closing } of a markup extension.

This leads me to beleave that it's seeing the {0} as a markup extension instead of it being a part of my string format. I've read about escaping with {} and using single quotes to specify the string format, but neither works:
Source  = "{Binding StringFormat={}Images\Icons\{0}\Multi.png, ...

The above returns the same error as when I don't escape at all..
Source  = "{Binding StringFormat='Images\Icons\{0}\Multi.png', ...

Source  = "{Binding StringFormat='{}Images\Icons\{0}\Multi.png', ...

The above two prevents the error from occurring, but results in the image source being null.
Does anyone know how to acheive this?
(Just to clarify, if the grandparent's tag is set to '16', then I want the image source bound to Images\Icons\16\Multi.png ... If the tag is set to '32' then I need to bind the source to Images\Icons\32\Multi.png. As a test, I set the grandparents tag to the full path, and excluded the stringformat. The relative binding to the grandparents tag succeeded and the image was shown. It only fails when I try to specify just the folder name with a stringformat to specify the rest of the path).
Answer: The StringFormatter attribute of Binding will only work if the target is of type String. Otherwise, it will simply be ignored.
You can fix this by adding a converter to your binding, which takes the format string and your tag, applies the formatting, and converts it to an ImageSource. In C#, your converter will look something like:
public sealed class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        if (parameter == null || parameter.Equals(String.Empty)) parameter = "{0}";
        string path = String.Format((string) parameter, value);
        return new BitmapImage(new Uri(path));
    }

    public object ConvertBack(object value, Type targetType,
                              object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Once you've got your converter, you can add the following to your Resources in XAML:
<local:ImageConverter x:Key="ImageConverter" />

And modify your Source binding to:
<Image x:Name="img"
       Stretch="None"
       Source="{Binding Parent.Parent.Tag, Converter={StaticResource ImageConverter},
                        ConverterParameter='Images\\Icons\\{0}\\Multi.png',
                        RelativeSource ={RelativeSource Mode=Self}}"
/>

Comment: I don't think that's the issue.. if I use a string format of {}{0}, bind to the tag, and set the tag to the full path, it binds just fine. Isn't this functionally the same as using stringformat to inject the folder into the path? It still resolves to a string, which, as you've said, is automatically converted from a string to an ImageSurce, right? I think the issue is that it's seeing the {0} as the closing } of the markup extension... or am I just plain wrong (which is possible, as I'm relatively new to xaml).
Comment: @Chronicide I made some slight modifications to my code which fixed some of the bugs I had. I tested it to make sure it works.
Comment: Well, I've tried a bunch of tests, and I've confirmed your explanation. It turns out that it was completely ignoring the stringformat... which was why it would always work when the tag had the full path. Doing something similar when binding a text property worked with the string format. Thank you for your help, as I would never have worked that out. Also, thanks for you code. I was hoping to avoid a converter, but it works.


Serialize list of employees in java

Question: I have a simple employee class:
class Employee {

    private int     id;
    private String  firstName;
    private String  lastName;
    private String  streetAddress;
    private String  city;
    private String  state;
    private String  zip;
    private String  cellularPhoneNumber;
    private String  homePhoneNumber;

    public Employee(int id, String firstName, String lastName, String streetAddress, String city, String state, String zip, String cellularPhoneNumber, String homePhoneNumber) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.streetAddress = streetAddress;
        this.city = city;
        this.state = state;
        this.zip = zip;
        this.cellularPhoneNumber = cellularPhoneNumber;
        this.homePhoneNumber = homePhoneNumber;
    }
}

How could I go about serializing multiple employees to a file? I know how to serialize one object, but how could I have multiple ones?
Could somebody point me in the right direction or provide a sample of serializing multiple objects? Would I be better off using a database like SQLite?
Much thanks in advanced.
Comment: First result on this site for "java serialize list": http://stackoverflow.com/questions/1387954/how-to-serialize-a-list-in-java
Comment: See here on sun's site http://java.sun.com/developer/technicalArticles/Programming/serialization/
Answer: The collections in java.util are Serializable. So if you make your Employee class implement Serializable, then put your employees in an ArrayList, then you can serialize the list and it will save the employees.
HSQLDB and H2 are in-memory databases implemented in Java that may be good alternatives to SQLite (meaning easier to use from a Java program). For general learning purposes using a database is a more practical skill, serializing things is not something I do a lot (when my code does use serialized classes the actual serialization is left up to the environment, such as when storing things in an HttpSession).
Comment: It's not for a company or anything, I'm just playing around, trying to learn how to work with classes. Thanks! I'll play around with the array list.
Answer:
add(..) the objects to a List - for example an ArrayList
serialize the list

As for your SQLite question - I can't tell. Generally, you shouldn't use serialization as a database storage, but if your application is simple, it should suffice.
Answer: List<Employee> e = new ArrayList<Employee>() {{

add(new Employee(...));
add(new Employee(...));
add(new Employee(...));
add(new Employee(...));
add(new Employee(...));

}};

Employee implements Serializable {

.....
}

?
Answer: I would recommend to go for serialization using Jackson , JSON .
The benefit is that after serializing, you can atleast see your Data. Java Serialization is limiting in many aspects.

Serialize list of employees in java


Register for an event and create an account on one page

Question: It's been a while since I've used Drupal and I now need to implement the following but can't seem to determine how. I have a site that's set up for event registration and need visitors to be able to sign up for an account as part of that one-page process. They'll then need to be able to edit their registration details and such but that part is in hand. What I'm not seeing is a way to combine account creation with the submission of non-profile form data all in one go.
Any pointers would be greatly appreciated.
Answer: Based on this existing answer, I could find the Inline Registration module. It lets you register while creating a node at the same time (one form). Since this is node-specific, this may allow a "event registration" content type to be defined then assigned to the user registration form.


Please Check my Calculation for any mistake.

Question: Question(T/F).Let $f:[0,\infty)\rightarrow\mathbb{R}$ be a continuous function such that $\lim_{x\to\infty}f(x)=0,$ then function $f$ has a maximum value in $[0,\infty).$
According to me answser is true as $\lim_{x\to\infty}f(x)=0,$ will imply that $|f(x)|\leq\epsilon$ for $x\geq K$ and again $f$ being continuos on compact set $[0,K]$ will attains its bounded. So $f$ must attain its maximum value. So according to  me answer is true. But in answer key it is given false answer. Please suggest me . Thanks in advance.
Comment: What if $f$ is increasing on $[0,\infty)$?
Comment: You only argue that $f$ is bounded.
Comment: @Malcolm Any counterexample?/
Comment: Consider $f(x)=\begin{cases}
1 & \mbox{ if } x\in [0,1]\\
\frac{1}{x} & \mbox{ if } x>1
\end{cases}$. It increases to zero, but never reaches it.
Comment: its decrease to zero...
Answer: It is true that $f$ is bounded, since the bound will be given by the maximum between $\epsilon$ and whatever bound it attains in $[0,K]$.
However, what is definitely not true, is that this maximum needs to be attained. Consider $-e^{-x}$, it clearly approaches $0$ as $x \to \infty$ however it is non-zero at every point.
Comment: ok....maximum zero will not attains?
Comment: No, right? $e^{-x} = 0$ can never happen.


Understanding the key concept

Question: I'm trying to understand the concept of key. After googling for a while I found that key is the same as tonality, and it consists of the set of notes that form a scale (major, minor, ...). But which is the utility of finding the key of a song?
Also, are the notes of a scale arranged in certain order? I mean: are the notes harmonics of the tonic note?
Comment: Just want to clarify that *Key* and *Tonality* are **not** the same thing.  You can have a tonal piece of music that is keyless.  It really just depends on how and which pitches are emphasized over others.
Comment: See this previously asked question. http://music.stackexchange.com/questions/6445/what-does-it-mean-to-write-a-song-in-a-certain-key
Comment: @jjmusicnotes but all keys are tonal because they have an empathized tonic.
Comment: @Dom, actually only music composed to emphasize the tonic would be tonal, it's certainly possible to write using the notes of a key without any such emphasis and be atonal. But I take your point, for the most part the definition of key *should* include emphasis of tonic since we can use other terms to describe diatonic atonality. Still jjmusicnotes is right to correct the OPs conflation of the two terms.
Answer: Key isn't the same thing as tonality, though it is a primary component of common-practice tonality—the primary musical style of Western Europe from 1650 to 1850, very generally. A key is in essence a hierarchy of pitches, in which some notes act like goals of melodic direction, and other notes act like pathways to those goals. One note, often called the tonic, is the ultimate goal and all compositions in this style will ultimately center on it (though often undergoing any number of byzantine and complex routes on the way). This tonic note will also be the note of the name of the key. So if G is the tonic note, we will call the key G Major or G minor.
In standard common-practice western music, there are seven notes that are primary (the technical term is "diatonic") to the key. There will be one version of each letter of the western musical alphabet: A, B, C, D, E, F and G. Different keys might be sharps or flats on some or all of these notes. Sharps raise a pitch by one half-step (one piano key or one guitar fret) and flats lower them by one half-step. For example, in D Major the As and Bs are natural, C is sharp, D and E are natural, F is sharp, and G is natural.
But remember, key defines a hierarchy for these pitches. The tonic of D Major is the note D, and it's important to know that because it should be the primary note of the composition and the ultimate goal of any melodic or harmonic progression. In D Major, A is the next most stable note, meaning it can often be used as a temporary goal. On the other end of the hierarchy, in D Major C# is the least stable note, and it desperately wants to resolve, or ease tension, by moving to D. G would also be a fairly unstable note in that key, and it generally wants to become a more stable note such as F#.
There are multiple ways to order to pitches of a key, but one of the most useful is as a scale. The notes of any key's scale should begin on the tonic, and then go up by alphabet (after G, go to A) until you get to a copy of the tonic one octave higher. Back to the D Major example, this would mean that we start on D—the tonic and name of the key—and move up alphabetically, like:
D E F# G A B C# D
If we number these scale degrees, then we can talk about the hierarchy of pitches just in terms of where they are in the scale. The 1st (and 8th) scale degree is the ultimate goal. The 5th (or dominant) is almost as stable, and the 3rd can be relatively stable as well. The 7th (usually called the leading tone) desperately wants to move to the tonic, and the 4th fairly strongly wants to move to the third. The 2nd wants to move down to the tonic and the 6th either wants to go down to 5 or up (via 7) to the tonic.
This is a big deal, because what it means is that once you know the key of a piece, you know exactly which notes will play these different roles. In F# major, the scale would be:
F# G# A# B C# D# E# F#
Using my earlier paragraph, you can now see that F# is the ultimate goal note, C# and A# can be temporary goals, E# will be the leading tone, etc. This is why it's important to know the key of a piece.
Think of major and minor as two different flavors of key. Major tends to be used for brighter, maybe happier or zanier music, while minor tends to be used for darker, maybe sadder or calmer music. But that's up to the composer. Objectively, they're just different scale patterns. Major, as you could probably deduce from the above examples is a scale where you start with the tonic and then go up like this (W=whole step, H=half step):
W W H W W W H
So if we start on G we get:
G -W- A -W- B -H- C -W- D -W- E -W- F# -H- G.
And then, again, we know which notes have which jobs to perform. For minor keys, the scale pattern is:
W H W W H W W
Although there are some complexities in minor that are beyond the scope of this answer involving variable sixth and seventh scale degrees. Most of the roles of the various scale degrees, however, are the same with only a few exceptions (although they are important)
In closing, it's important to note that these note roles I've been talking about are only tendencies. Individual composers, pieces and musical moments can shift them, change them and play with them in all kinds of fascinating ways. It's like knowing the letters of the DNA alphabet and how they can combine to form proteins. Useful, even necessary, info for someone studying biology, but it's not nearly enough to build a dog or a redwood tree.
Answer: You can think of key a song as the musical description of the song. Using the key you can find the notes that make up the melody and harmony and also the chords used in a song.
If a song is in the key of A major, you know most (if not all) of the notes found in the song are going to be from the A major scale and most (if not all) of the chords will also be built from A major scale. It's a good indicator for any player to know what to expect in the song. For example, you probably won't ever play a D diminished chord in A major, but you'll probably play a D major chord.
Also yes the notes of a scale are in a certain order for a reason. Each scale degree has it's own harmonic function.

Understanding the key concept


Prove that $\hat{\mathbf{F}}$ is a Conservative Field

Question:
If $\hat{\mathbf{F}}$ is a vectorial field defined by:
$\hat{\mathbf{F}}(x, y) = \frac{1}{y} \hat{\mathbf{i}} - \frac{x}{y²} \hat{\mathbf{j}} $
Prove that $\hat{\mathbf{F}}$ is conservative.

My issue with this problem is the fact that the domain of $\hat{\mathbf{F}}$ doesn't appear to be path-connected and, therefore, not simply connected.
Because of this detail, I can't determine this statement by showing that the curl equals zero. Can somebody help me, please?
Comment: The domain is not given, but its conservative on any region avoiding $y=0$ with potential $f(x,y) = x/y$. I think you should split $\mathbb R^2$ into two half-planes(ignoring the $x$-axis), i.e. the implied? domain is not even connected. But its conservative on each component.
Answer: Well, it's the gradient of $\displaystyle f(x,y)=\frac{x}{y}$.
The function and its gradient do not exist on $y=0$, but the only requirement for conservative is that it satisfies being the gradient of another function.
Answer: A conservative vector field is by definition the gradient of a function $f$.
To find the function from the gradient, $F$xy=$F$yx. Which are both equal to $\frac{-1}{y^2}$. This shows that our field is the gradient of a function (the function can be found by integrating each component of the field).
Note that the only property that a field is a conservative is that it the gradient of a function. This means that you do not have to worry about the domain or continuity.


Unable to find the element to check if it exists in the before() hook in cypress.io

Question: I have the following lines of code in my before() hook.
before(() ==> {
cy.get(this.testPopup).then(($el) => {
   if ($el.length) {
      cy.get(this.testPopupCloseButton).click();
      cy.get(this.testPopup).should("not.exist");
    }
  });
});

There will be a popup which will display sometimes and sometimes it will not. I tried to write a logic to close that popup and check if it getting disappeared on closing only when the popup exists.
But I am getting the following error.

Timed out retrying after 30000ms: Expected to find element: #test-popup-element, but never found it.
Because this error occurred during a before all hook we are skipping the remaining tests in the current suite`

I am expecting a soft assert here basically, which will continue to run the rest of the tests even if this assertion fails.
Please advice.
Comment: Does this answer your question? [Dialog that may or may not appear on page start](https://stackoverflow.com/questions/72960188/dialog-that-may-or-may-not-appear-on-page-start)
Answer: You can't resolve the issue using cy.get('body').then(($body) => because the code will finish before the popup appears. There is no retry in that code, it always decides imediately if the popup is present.
Instead, use element polling as shown by Fody here:
How to check for an element that may not exist using Cypress
const ifElementExists = (selector, attempt = 0) => {
  if (attempt === 100) return null           // no appearance, return null
  if (Cypress.$(selector).length === 0) {
    cy.wait(100, {log:false})                // wait in small chunks
    getDialog(selector, ++attempt)           // try again
  }
  return cy.get(selector, {log:false})       // done, exit with the element
}

// Wait for 10 seconds for the popup
ifElementExists(this.testPopup).then($el => {
  if ($el?.length) {
    cy.get(this.testPopupCloseButton).click()
    cy.get(this.testPopup).should('not.exist')
  }
})

This works because it will keep waiting for the popup up to 10 seconds.
Increase  if (attempt === 100) if you need longer waiting time. You have to decide the longest time you need to wait and set attempt limit accordingly.
If it never appears in that time, if ($el?.length) will be false and the close button won't be clicked.
Otherwise, the popup has eventually appeared and the code can go ahead and click the close button.
Answer: The issue is that using cy.get(this.testPopup) contains an implicit assertion that the this.testPopup element exists. So in the case where it doesn't, the test fails because Cypress can't find the element.
From the Cypress Conditional Testing documentation, they recommend using cy.get('body') and then querying for the element (using JQuery's .find().)
before(() ==> {
  cy.get('body').then(($body) => {
    if ($body.find(this.testPopup).length) {
      cy.get(this.testPopupCloseButton).click();
      cy.get(this.testPopup).should("not.exist");
    }
  });
});


Segmentation fault in Linked List code, deletion part

Question: I am trying to code for insertion and deletion in linked list.
Here is my code for basic insertion and deletion of nodes in a singly linked list.
There are no errors in the code, but the output on the terminal shows segmentation fault. Can someone explain why am I getting a segmentation fault? And what changes do i make to remove the fault.
I believe the segmentation fault is in the deletion part. Please help.
// class is a type of user defined datatype
class Node {
    public:
    int data;
    Node* next;

    //constructor
    Node(int data) {
        this -> data = data;
        this -> next = NULL;
    }

    // destructor
    ~Node() {
        int value = this -> data;
        //memory free krr rhe hain
        if(this -> next != NULL){
            delete next;
            this -> next = NULL;
        }
        cout << "memory is free for node with data" << value << endl;
    }

};

void insertAtHead(Node* &head, int data) {

    // creating new node called temp of type Node
    Node* temp = new Node(data);
    temp -> next = head;
    head = temp;
}

void insertAtTail(Node* &head, Node* &tail, int data) {
    // //New node create
    // Node* temp = new Node(data);
    // tail -> next = temp;
    // tail = temp;

    Node* temp = new Node(data);
    if (head == nullptr) { // If this is the first node of the list
        head = temp;
    } else { // Only when there is already a tail node
        tail -> next = temp;
    }
    tail = temp;
}

void insertAtPosition(Node* &tail, Node* &head, int position, int data) {

    // Insert at starting
    if(position == 1) {
        insertAtHead(head, data);
        return;
    }

    // Code for inserting in middle
    Node* temp = head;
    int cnt = 1;

    while(cnt < position-1) {
        temp = temp -> next;
        cnt++;
    }

    // Creating a node for data
    Node* nodeToInsert = new Node(data);
    nodeToInsert -> next = temp -> next;
    temp -> next = nodeToInsert;

    // Inserting at last position (tail)
    if(temp -> next == NULL) {
        insertAtTail(head,tail, data);
        return;
    }
}

void deleteNode(int position, Node* &head) {

    //deleting first or starting node
    if(position == 1) {
        Node* temp = head;
        head = head -> next;
        //memory free start node
        temp -> next = NULL;
        delete temp;

    } else {
        // deleting any middle node
        Node* curr = head;
        Node* prev = NULL;

        int cnt = 1;
        while(cnt <= position) {
            prev = curr;
            curr = curr -> next;
            cnt++;
        }

        prev -> next = curr -> next;
        curr -> next = NULL;
        delete curr;
    }
}

void print(Node* &head) {

    Node* temp = head;
    while(temp != NULL) {
        cout << temp -> data << " ";
        temp = temp -> next;
    }
    cout << endl;
}

int main() {

    Node* head = nullptr; // A list has a head
    Node* tail = head; //  a tail.

    insertAtHead(head, 10); // pass the head
    insertAtTail(head, tail, 20);
    insertAtTail(head, tail, 30);
    insertAtHead(head, 5);
    print(head);  // Print the whole list

    cout << "head" < data << endl;
    cout << "tail" << tail -> data << endl;

    deleteNode(1, head);
    print(head);
}

Comment: Do you know what a debugger is? It can help you to find your problem very easily
Answer: The problem is not with the delete function since even commenting it out leads to segmentation fault.
The problem is that you are initializing tail = head which is set to nullptr at the start. However, when you insertAtHead, you set the value of head but leave the tail to nullptr. You need to do tail = head when adding the first node (when head == nullptr).
Refer below for working code:
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;

// class is a type of user defined datatype
class Node {
    public:
    int data;
    Node* next;

    //constructor
    Node(int data) {
        this -> data = data;
        this -> next = NULL;
    }

    // destructor
    ~Node() {
        int value = this -> data;
        //memory free krr rhe hain
        if(this -> next != NULL){
            delete next;
            this -> next = NULL;
        }
        cout << "memory is free for node with data" << value << endl;
    }

};

void insertAtHead(Node* &head,Node* &tail, int data) {

    // creating new node called temp of type Node
    Node* temp = new Node(data);
    temp -> next = head;

    if (head == nullptr)
        tail = temp; //inializing tail

    head = temp;
}

void insertAtTail(Node* &head, Node* &tail, int data) {
    // //New node create
    // Node* temp = new Node(data);
    // tail -> next = temp;
    // tail = temp;

    Node* temp = new Node(data);
    if (head == nullptr) { // If this is the first node of the list
        head = temp;
    } else { // Only when there is already a tail node
        tail -> next = temp;
    }
    tail = temp;
}

void insertAtPosition(Node* &tail, Node* &head, int position, int data) {

    // Insert at starting
    if(position == 1) {
        insertAtHead(head,tail, data);
        return;
    }

    // Code for inserting in middle
    Node* temp = head;
    int cnt = 1;

    while(cnt < position-1) {
        temp = temp -> next;
        cnt++;
    }

    // Creating a node for data
    Node* nodeToInsert = new Node(data);
    nodeToInsert -> next = temp -> next;
    temp -> next = nodeToInsert;

    // Inserting at last position (tail)
    if(temp -> next == NULL) {
        insertAtTail(head,tail, data);
        return;
    }
}

void deleteNode(int position, Node* &head) {

    //deleting first or starting node
    if(position == 1) {
        Node* temp = head;
        head = head -> next;
        //memory free start node
        temp -> next = NULL;
        delete temp;

    } else {
        // deleting any middle node
        Node* curr = head;
        Node* prev = NULL;

        int cnt = 1;
        while(cnt <= position) {
            prev = curr;
            curr = curr -> next;
            cnt++;
        }

        prev -> next = curr -> next;
        curr -> next = NULL;
        delete curr;
    }
}

void print(Node* &head) {

    Node* temp = head;
    while(temp != NULL) {
        cout << temp -> data << " ";
        temp = temp -> next;
    }
    cout << endl;
}

int main() {

    Node* head = nullptr; // A list has a head
    Node* tail = head; //  a tail.

    insertAtHead(head,tail, 10); // pass the head
    insertAtTail(head, tail, 20);
    insertAtTail(head, tail, 30);
    insertAtHead(head,tail, 5);
    print(head);  // Print the whole list

    cout << "head" < data << endl;
    cout << "tail" << tail -> data << endl;

    deleteNode(1, head);
    print(head);
}

Comment: Thankyou for the explanation, and for resolving the issue as well.
Answer: The segfault is actually in the function insertAtTail(), and is because, while you handle the case where head is a null pointer, you do not handle the case where there is a head node but no tail node. The following code fixes this issue:
void insertAtTail(Node* &head, Node* &tail, int data) {
    // //New node create
    Node* temp = new Node(data);
    if (head == nullptr) { // If this is the first node of the list
        head = temp;
    } else if (tail == nullptr) { // if there's a head but no tail
        head -> next = temp;
    } else {               // Only when there is already a tail node
        tail -> next = temp;
    }
    tail = temp;
}

Comment: Good observation. However, if tail is initialized with head, there will not be any case in which head is null and tail is not. So if we initialize the tail=head in insertAtHead, this issue should resolve itself. Notice that calling insertAtTail before insertAtHead will not cause an error since when head==nullptr, tail is also nullptr.
Answer: If you have a look at this part of your code:
int main()
{
    Node* head = nullptr; // A list has a head
    Node* tail = head; //  a tail.

    insertAtHead(head, 10); // pass the head
    insertAtTail(head, tail, 20);

    return 0;
}

tail is a nullptr as you pass it into insertAtTail(head, tail, 20);
Then in insertAtTail you are going to access this nullptr:
void insertAtTail(Node* &head, Node* &tail, int data) {
    // //New node create
    // Node* temp = new Node(data);
    // tail -> next = temp;
    // tail = temp;

    Node* temp = new Node(data);
    if (head == nullptr) {
        head = temp;
    } else {
        // here you have nullptr access resulting in your segmentation fault
        tail -> next = temp;
    }
    tail = temp;
}


Definir limitação em números aleatórios gerados

Question: Eu preciso criar uma carteira de investimentos aleatória com determinados benchmarks. Inicializei ela com tudo 0.
structure(list(Benchmarks = structure(c(2L, 7L, 6L, 10L, 12L,
11L, 13L, 14L, 15L, 16L, 17L, 1L, 4L, 3L, 9L, 5L, 8L), .Label = c("ALOCACAO",
"DI", "DÓLAR", "IBOV", "IDA - GERAL", "IDKA_IPCA2", "IDKA_PRE2",
"IFIX", "IHFA", "IMA-GERAL", "IMAB", "IMAB - 5", "IMAB - 5 +",
"IRFM", "IRFM - 1", "IRFM - 1 +", "VÉRTICE"), class = "factor"),
    percentual = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0)), class = "data.frame", row.names = c(NA, -17L))

Mas eu tenho as seguintes condições:

A obrigação, soma dos benchmarks = 100%, não pode sobrar ou faltar.
Nem todos os benchmarks precisam estar preenchidos, alguns podem ficar vazios

Abaxio segue a geração de um dos benchs que eu fiz
distribuicaoBenchmark[distribuicaoBenchmark$Benchmarks == "DI", 2] <- runif(1, min = 0, max = 100)

Não consegui pensar nas duas limitações. Pensei em usar um while (totalInvestido < 100), mas nos meus teste, ocorria de sobrar dinheiro OU ele ficar em loop eterno pois nunca consegui satisfazer a condição do while.
Comment: As duas condições não são a mesma? A soma dos benchmarks == 100%?
Comment: Relendo agora sim, farei um edit!
Answer: Para cada peso individual, basta selecionar um número aleatório de qualquer distribuição com suporte nos números não-negativos. Depois, divida cada peso pelo somatório de todos os pesos:
set.seed(1234)
distribuicaoBenchmark <- runif(17, 0, 100)
distribuicaoBenchmark <- distribuicaoBenchmark/sum(distribuicaoBenchmark)
summary(distribuicaoBenchmark)
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max.
## 0.001085 0.032701 0.069609 0.058824 0.076099 0.105501
sum(distribuicaoBenchmark)
## [1] 1

Para obter os pesos entre 0 e 100, basta multiplicar distribuicaoBenchmark por 100.


Django Template comparison inside a loop

Question: I need compare the values of a Model with the result of an aggregate in  my template.
like a :
{% for valor in valores %}
    {{ valor.quantidade }}
{% endfor %}
results of my loop

{{ total.total_quantidade }}
this is the result of my Aggregate

How i can make the comparison of this values?
List of results of my {% for valor ... %}
1000
2000
3000

result of my aggregate
1500

{% if total.quantidade_total >= valor.quantidade %} shows the equivalent value ..and so on, if smaller shows another value
how can i proceed?
Answer: What's the difficulty?
{% for valor in valores %}
    {% if total.quantidade_total >= valor.quantidade %}
        Do something
    {% else %}
        Do something else
    {% endif %}
{% endfor %}


Regex_subtr in oracle sql

Question: I have hit the wall. I need to extract the from: Date and the To: Date from the text below.
It will always start with the date. But the changed from: and changed to: can sometimes be [none] instead of the date pattern.
Column:
"31-Jul-2017 11:29 (GMT+1:00) Date Due was modified by: placeholder, SNO-1234.

**Changed from: 12-Dec-2017**

**Changed to: 01-Jan-2021**

Meaning: Initial Entry
Meaning Comments:"

Wanted output:
Column = From: "12-Dec-2017"
Column = Changed To: "01-Jan-2021"

I have tried
cast(regexp_substr(column:, 'from:\s.*') as varchar(17)) as "From:",

cast(regexp_substr(column:, 'to:\s.*') as varchar(15)) as "Changed To:"

and i end up with..
Column = From: "**From:** 12-Dec-2017"
Column = Changed To: "**To:** 01-Jan-2021"

Anyway to exclude the from: and to: ? so basicly, how can i ONLY get the 11 characters after "from: " and "to: ".
Thanks in advance!
\GloriousWater
Answer: You don't need a regular expression, you can use simple string functions:
SELECT CASE
       WHEN from_pos > 0
       THEN TO_DATE(
              SUBSTR( value, from_pos + 14, 11 )
              DEFAULT NULL ON CONVERSION ERROR,
              'DD-MON-YYYY'
            )
       END AS from_dt,
       CASE
       WHEN to_pos > 0
       THEN TO_DATE(
              SUBSTR( value, to_pos + 12, 11 )
              DEFAULT NULL ON CONVERSION ERROR,
              'DD-MON-YYYY'
            )
       END AS to_dt
FROM   (
  SELECT value,
         INSTR( LOWER( value ), 'changed from: ', 1, 1 ) AS from_pos,
         INSTR( LOWER( value ), 'changed to: ', 1, 1 ) AS to_pos
  FROM   table_name
);

However, if you did want to use (slower) regular expressions then you could use:
SELECT TO_DATE(
         REGEXP_SUBSTR(
           value,
           'changed from:\s*(([012]\d|3[01])-(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)-\d{4})',
           1,
           1,
           'i',
           1
         )
         DEFAULT NULL ON CONVERSION ERROR,
         'DD-MON-YYYY'
       ) AS from_dt,
       TO_DATE(
         REGEXP_SUBSTR(
           value,
           'changed to:\s*(([012]\d|3[01])-(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)-\d{4})',
           1,
           1,
           'i',
           1
         )
         DEFAULT NULL ON CONVERSION ERROR,
         'DD-MON-YYYY'
       ) AS to_dt
FROM   table_name;

Which, for your sample data:
CREATE TABLE table_name ( value ) AS
SELECT '31-Jul-2017 11:29 (GMT+1:00) Date Due was modified by: placeholder, SNO-1234.
Changed from: 12-Dec-2017
Changed to: 01-Jan-2021
Meaning: Initial Entry Meaning Comments:' FROM DUAL

Both output:

FROM_DT             | TO_DT
:------------------ | :------------------
2017-12-12T00:00:00 | 2021-01-01T00:00:00

db<>fiddle here
Comment: Thank you!

I had some problems implementing the string function as it wouldn't recognize the from statement. i exchange "value" with the column containing the text to be parsed and table_name with the original from statement but it gives me some ) errors or wont recognize the columns. In the original from statement i have 1 table and 2 left joins.

Regex_subtr in oracle sql


How do I set the block visibility with PHP?

Question: In a site running Drupal 8, I want to show my block in two cases: when my view page is shown and when a node of my content type is shown.
How do I set the block visibility with PHP?
Comment: is it a custom block??
Comment: No block Added by UI
Comment: Add condition by clicking on  configure block . You can restrict block by mentioning content type as well as page url
Comment: Both Not working together.
Comment: Clear cache and check error Reports also
Comment: Done but not working.
Answer: The core visibility configuration is not so good in combining multiple visibility condition.
The module Block Visibility Groups provides more tools to do this. You can decide whether all condition must pass (logical AND) or only one condition must pass (logical OR) and put the logic in a group and reuse it on different blocks.


How can i use taxonomy name in url page using a view

Question: I have a taxonomy terms like:

christmas
wedding

How can I build a view with url page like this: www.site.com/%
being % christmas or wedding,
If users go to  www.site.com/christmas just display nodes with christmas taxonomy.
If users go to  www.site.com/wedding just display nodes with wedding taxonomy.
I have to do n views with same fields that why I want to do just one generic view.
Comment: Why not just use pathauto and make the aliasing rule [term-name] or whatever the appropriate token is? Also, you can create one view and tell vocab + vocab terms to use that view or views with a module like TVI.
Answer: The PathAuto module allows you to easily change the URLs for the default taxonomy listings (which do what you describe).
Install the module and go to Administration > Configuration > Search and metadata > URL aliases.
You can set a pattern for your vocabulary that is just [term:name] BUT there are good reasons not to do that (for example if a category overlaps with a default path).  Something like holiday/[term:name] is likely a better choice.
For more options on PathAuto see the recipes from Drupal.org.
If you need more control over the display you can override the view that generates term pages.
Comment: Seconded, you _can_ do this but generally you should stick to [vocab-name]/[term-name] as a default alias as acrosman said. Views still work off of taxonomy/term/% path since it is a system path, and you can use someting like TVI to enhance the display of different vocabularies by using rendered entities instead of node fields.


Angular2 Http PUT gives wrong RequestMethod

Question: I can't understand why I can't use http put in Angular2.
When I'm doing http post, it give the correct request method:

However, when I use http put: it give OPTIONS as the request method:

I meant what the heck is this?
Here is the method that I'm using for post:
<code>  let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
  let options = new RequestOptions({ headers: headers });
  var body = 'amount=' + 12;
  this.http.post(this.host + '/orders', body, options)
  .map(res => res.json())
  .subscribe(data => {
    resolve('success')
  });
</code>
Here is the method that I'm using for PUT.
<code>  let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
  let options = new RequestOptions({ headers: headers });
  let body = 'amount=' + 12;
  this.http.put(this.host + '/orders/1', body, options)
  .map(res => res.json())
  .subscribe(data => {
    resolve('success')
  })
</code>
Answer: I think that it's because of CORS. It's not related to Angular2. In the case of your POST method, a simple method will be executed. In the case of PUT, you're in the case of a preflight one so an additional request (an OPTIONS one) will be involved under the hood by the browser. And it seems that you have 404 on this OPTIONS method.
As a reminder:

Simple requests. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.
Preflighted requests. When the "simple requests" use case doesn't apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.

I think that these articles could interest you:

http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/
Comment: But I tested in the update method with Postman, it works fine, also in my server, express, I have enabled all of these: res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); res.setHeader('Access-Control-Allow-Credentials', true);
Comment: Yes, but with Postman, you are in a Chrome plugin so you can have fewer restrictions. That's great for the CORS headers on the server side. But it's not enough regarding CORS preflight requests. You should use the `cors` module in your express application: https://github.com/expressjs/cors#enabling-cors-pre-flight (globally or per request).


Is there a way to show AlertDialog in AsyncTask commonly?

Question: I want to show AlertDialog which is in other class in AsyncTask.
Example>
public class WardListAsyncTask extends AsyncTask<HashMap<String, String>, String, Object> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Object doInBackground(HashMap<String, String>... params) {
      ...
    }

   @Override
    protected void onPostExecute(Object result) {
        ConfirmAlertDialog(ez_WardList.this,"HI?");
        //this method is in another Class & I want to use this method another Asynctask also..
    }

and ConfirmAlertDialog is...
    Context g_ctx;
String g_content;
public void ez_ConfirmAlertDialog(Context ctx, String content) {
    this.g_ctx=ctx;
    this.g_content=content;

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(g_ctx, AlertDialog.THEME_HOLO_LIGHT);
            builder.setMessage(g_content).setPositiveButton(getString(R.string.kor_confirm),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                        }
                    });

            AlertDialog alertDialog = builder.create();
            alertDialog.show();
            alertDialog.getWindow().setLayout(displayWidth / 2, LayoutParams.WRAP_CONTENT);
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.rgb(10, 174, 239));

        }
    });

}

I think g_ctx.class.runonuiThread ... but I can't call runonuithread...
How can I solve it?
Comment: call `#Context.runonuithread`.
Comment: Related: http://stackoverflow.com/questions/13974661/runonuithread-vs-looper-getmainlooper-post-in-android
Answer: runOnUiThread method is present in Activity class. So should pass Activity into your class.
Example:
public class MyClass{

public void ez_ConfirmAlertDialog(Activity activity, String content) {
    this.g_ctx=ctx;
    this.g_content=content;

    if(activity == null){
       return;
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(g_ctx, AlertDialog.THEME_HOLO_LIGHT);
            builder.setMessage(g_content).setPositiveButton(getString(R.string.kor_confirm),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                        }
                    });

            AlertDialog alertDialog = builder.create();
            alertDialog.show();
            alertDialog.getWindow().setLayout(displayWidth / 2, LayoutParams.WRAP_CONTENT);
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.rgb(10, 174, 239));

        }
    });

}

}

Comment: Thanks!! u save my time!!! It is good to me. and I'm just wondering whether It is never call error about activity.. ??

cuiz I'm changing Toast to AlertDialog... It is befor custom Toast

msg = message;
runOnUiThread(new Runnable() {
@ Override
public void run() {
View view = View.inflate(Form_Main.this, R.layout.common_toast, null);
TextView tv = (TextView) view.findViewById(R.id.textViewToast);
tv.setText(msg);

Toast t = new Toast(_context);
t.setView(view);
t.setDuration(Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
 });
Comment: @Adrian you get an error in this case only if activity is null, so you should also check activity if is null in top of method.
Comment: Thanks!! It is perfect to me. I resolved my problem!
Answer: You can call it in main thread using handler
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
             // Your code here
        }
    });


Connect to pgadmin client through reverse proxy

Question: I have a Postgres Database in private subnet on AWS and I want to connect to AWS.
So i create an ec2 with httpd (Apache) as a reverse proxy in public subnet in order to forward my request to RDS database.
User -> pgadmin client -> Reverse proxy on 443 -> RDS.
As information, i can open only 443 and 80 on public subnet.
my Apache configuration :
ProxyPass /rds  http://rds-link.compute.amazonaws.com:5432
ProxyPassReverse /rds  http://rds-link.compute.amazonaws.com:5432

in Postgres pgadmin (my laptop) I tried to connect to database using https://link-of-reverse-proxy/rds as host , but its not wokring.
i receive the error : could not translate host name to address
Did i miss something ?
Thank you in advance
Answer: Make sure your EC2 server has access to RDS. You should grant your EC2 server to connect on 5432 to RDS on security group config.
I personally don't install an apache on proxy EC2 server. I open a tunnel via my EC2 server and map 5432 port to my local.
ssh firstname.lastname@example.com -L 5432:rdshost.eu-west-2.rds.amazonaws.com:5432

Comment: The problem is that i can't use SSH directly to this instance. I have a bastion which is controlled by another department
Comment: So did you check security group config?
Comment: in fact, I can't update the security group and open the ssh to my @IP, i really have a limited access
Comment: You don't have to SSH, that was a suggestion. But you have to update security group as I know. Otherwise your reverse proxy server will not have access to your database.
Comment: In fact, i can only update the security group in order to open a communication between the proxy and RDS, but i can't open the SSH directly from my IP to the proxy


How to find distance between two set of co-ordinates in php

Question: Let suppose i have two set of co-ordinates, i got these co-ordinates from map source through android application and sent it to server, now server side will calculate distance between them and print.
Comment: can you share some of codes
Comment: no sorry i haven't any code i want to initiate now
Answer: Try this:
function calculateDistance($lat1, $lon1, $lat2, $lon2, $unit) {

    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
        return ($miles * 1.609344);
    } else if ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}

and you can call it like:
calculateDistance($latitude1, $longitude1, $latitude2, $longitude2, "K");

Reference
Answer: Try This
<?php

$points = array
(
    "point1" => "0,55" ,
    "point2" => "0,52"
);

function get_distance($inputs)
{
    $count = 1;
    foreach($inputs as $x => $y)
    {
        echo $x." = (".$y.")
";
        $p[$count] = explode(",",$y);
        $count++;
    }

    $x1 = $p[1][0];
    $y1 = $p[1][1];

    $x2 = $p[2][0];
    $y2 = $p[2][1];

    $distance = sqrt(pow(($x2 - $x1) , 2) + pow(($y2 - $y1) , 2));
    echo $distance;
}

get_distance($points);

?>

Comment: Good suggestion, I have edited my answer. Thanks @TobiasF.
Comment: i have tried it with low points i-e "point1" => "0,5" , "point2" => "0,15". And it worked fine thanks
Comment: it gave me output 10 which was my required answer thanks again
Comment: wouldn't it be easier if you include the distance calculation within the function `get_points` rather than seperately splitting the coordinate and calculating the distance?
Comment: I suggest to change it the folllowing way:

    ` "22,55" ,
     "point2" => "55,12"
    );

    function get_distance($inputs)
    {
     $count = 1;
     foreach($inputs as $x => $y)
     {
      echo $x." = (".$y.")";
      $p[$count] = explode(",",$y);
      $count++;
     }
     $distance = sqrt(pow(($p[2][0] - $p[1][0]) , 2) + pow(($p[2][1] - $p[1][1]) , 2));

        return $distance;
    }

    $distance = get_distance($points);
    echo $distance;
    ?>`. (Of course after reformatting :))


Let $f: [0, + \infty ) \to [0,1)$ $f(x) = \frac{x^2}{1 + x^2}$. Find the inverse map $f^{-1}: [0,1) \to [0, + \infty )$

Question: Let $f: [0, + \infty ) \to [0,1)$
$$f(x) = \frac{x^2}{1 + x^2}$$
Show that
i) $f$ is strictly increasing and surjective.
ii) Find the inverse map $f^{-1}: [0,1) \to [0, + \infty )$

i) To be strictly increasing, we must have that the derivative is always positive. Using https://www.derivative-calculator.net/#expr=x%5E2%2F%281%2Bx%5E2%29
we find that the derivative is
$$\frac{2x}{(x^2+1)^2}$$
This function will always be positive in the domain $[0, + \infty )$. So the function is strictly increasing.
For surjective, we need to solve $\frac{x^2}{1 + x^2} = y$. We get $x = \pm \sqrt{\frac{y}{1-y}}$. We have $y \in [0,1)$ so there is no risk to divide by zero or have a negative result under the square root.
I'm a bit unsure for the inverse map, isn't that the same as finding the surjective function ? Why would they ask us to do that if it's the same thing ??
Comment: Drop the minus sign in front of the square root, as the original $\;f\;$ is a positive function from all the non-negative reals. The rest is fine. You'd use the minus sign if you'd have $\;f:(-\infty,0]\to [0,1)\;$...
Comment: I'm not sure I understand what you mean, but finding an inverse map automatically makes the original function bijective, meaning: injective and surjective. CHeck this.
Comment: @DonAntonio What about the inverse map ? Is it the same as the surjective function ?
Comment: @DonAntonio So actually in my post i did not directly prove that it's surjective, but rather that an inverse function exists which automatically shows that it's injective and surjective ?
Comment: @DonAntonio Feel free to post an answer if you want so I can accept it, so the question doesn't appear in the unanswered section
Answer: We do not need to find the inverse map to show that it is surjective.
For example, you can do the following:

Note that $0 \le \frac{x^2}{x^2+1}<1$.
After showing that it is increasing, note that $\lim_{x\to \infty}\frac{x^2}{x^2+1}=1$, by continuity, every $y \in [0, 1)$ has a preimage. Hence it is surjective.

For the preimage function,  since the preimage is nonnegative, $x = \sqrt{\frac{y}{1-y}}.$


Terraform error A value of type string cannot be used as the collection in a 'for' expression

Question: I have created a module to add an AWS.APIGateway route and authoriser.
The module is called depending on how many variables are in the tfsvars file.
This variable is passed through to the module to create the Route name as extprovider.
I need to take this variable and append a suffix to it so that i can then add multiple clientids (audiences) to the authoriser.
Error: Iteration over non-iterable value

  on ../modules/apiresource/locals.tf line 3, in locals:
   3: extprovider_new  = flatten([ for e in var.extprovider : tolist(["${e}odd","${e}even"])])
    ├────────────────
    │ var.extprovider is "foo"

A value of type string cannot be used as the collection in a 'for' expression.

Error: Iteration over non-iterable value

  on ../modules/apiresource/locals.tf line 3, in locals:
   3: extprovider_new  = flatten([ for e in var.extprovider : tolist(["${e}odd","${e}even"])])
    ├────────────────
    │ var.extprovider is "bar"

A value of type string cannot be used as the collection in a 'for' expression.

My code is;
locals.tf

locals {
extprovider_new  = flatten([ for e in var.extprovider : tolist(["${e}odd","${e}even"])])
}

variables.tf
variable extprovider {}

Answer: You are passing a string variable to module but in module you want to use it as list.
You can pass variable like
module "module_name" {
  ...
  extprovider = ["foo"]
  ...
}

and it should work
or
in locals.tf
locals {
   extprovider_new  = ["${var.extprovider}odd", "${var.extprovider}even"]
}

you can use string variable and convert it to list which you need.


Is there any rule that says you can't play with two rackets in badminton?

Question: Is there any rule that says you can't play with two rackets in badminton?
That is, one racket in each hand, so for example you don't have to hit a backhand; you can just do forehands.
Answer: Unlike International Tennis Federation (ITF) which specifically bans using more than one racket under the rule 4. THE RACKET, Case 5:

[TENNIS RULES]
Is a player allowed to use more than one racket at any time during
play?
Decision: No.

Badminton World Federation (BWF) laws don't state anything specific on using more than one racket. However, like ITF, they use the singular form of the noun racket in the laws, based on which we can safely assume using more than one racket is prohibited.
One more thing to consider is would it really help to use two rackets? If you play with two rockets, it will be more difficult to serve effectively (you need to note there is a rule on Service, too) and it might injure your hands when you try to dive to receive a shuttle.
Comment: you don't have to hold both to serve, you could have a sheeth like people have for a sword, and whip out the second racket when there is time. So if in badminton you're returning a serve you could hold both.  Or if a shot is a high clear coming at you then you could whip out the second racket from the sheeth, or better, whip it out while your partner is going for a clear, there's lots of time there.
Comment: perhaps the fact that  tennis has a specific prohibition for it, indicates that they thought that without that specific prohibition, the tennis rules wouldn't clearly prohibit more than one racket.. Thus likewise that'd be the case with badminton, though badminton doesn't have a specific prohibition, so it's not clearly / far from clearly, prohibited.
Comment: @barlop How can you serve holding two rackets in tennis?
Comment: @barlop Yeah. A few more distractions for a player. That's why they don't use two rackets.
Comment: But would you agree that the fact that the tennis people thought it necessary to prohibit two rackets in tennis, suggests that without that prohibition, it'd be allowed or not prohibited. And why wouldn't that logic apply to badminton?
Comment: @barlop Now, I see what's confused you. Why would no badminton player use two rackets if they think they can play better with two rackets? Do table tennis laws have anything about using two rackets?
Comment: Well, there are different possible answers as to why no badminton player has tried playing with two rackets. One is that to do so would go against convention, and they haven't trained for it and the first people to try it would be taking a risk because if after training with it it turns out that they played better with one racket, then they would have wasted some of their training.  And they might also be socially conditioned to not play with two because they don't want to look weird. Clearly the tennis law people thought some might want to and thus thought to add a prohibition against it.
Comment: @barlop Shall we stop here? I think we had enough.
Answer: I'm not an expert but can use either hand effectively. The difficulty I see, is in anticipating a return shot your stance will be set, with one raised racket.
From that point you are restricted in what you can deploy in a fraction of a second. If your body is committed to one racket before your opponent smashes, that's your best option. I have occasionally switched hands in play, more to give my predominant arm a rest than be more competitive.
The other difficulty of having a racket in your free hand is it will get in the way all the time, as that arm is used extensively for counterbalancing both for balance and strength.
There's also no real argument for doing forehand shots all the time, back-hands can be equally powerful with practice.
Comment: you  write " in anticipating a return shot your stance will be set, with one raised racket"  <-- you anticipate a return shot that can come in either direction, that is, to your left, or to your right,  and you raise both rackets in anticipation of a next shot on one or the other side.   Ready to hit a shot on your left hand side, or on your right hand side. Why only raise one racket?
Comment: And putting aside that lots of people have  a weak backhand.. even if they'd practised their backhand,   Is your "backhand smash" as strong as your forehand smash?
Answer:
Not specifically but you can deduce the answer is you are allowed 1 racket per person.

4.3 The racket:
4.3.1:
[The racket] shall be free of attached objects and protrusions, other than those used solely and specifically to limit or prevent wear and tear, or vibration, or to distribute weight, or to secure the handle by cord to the player's hand, and which are reasonable in size and placement for such purposes

Also:

EQUIPMENT COMPLIANCE
The International Badminton Federation shall rule on any question of whether any racket, shuttle or equipment or any prototype used in the playing of Badminton complies with the specifications. Such ruling may be undertaken on the Federation's initiative or on application by any party with a bona fide interest, including any player, technical official, equipment manufacturer or Member Association or member thereof.

I imagine the Federation would rule this illegal.
Comment: well, 4.3.1 is completely irrelevant
Comment: And re equipment compliance, playing with two rackets does not mean that a racket doesn't meet the specifications, one thing has nothing to do with the other.


Looping through facebook api "likes"

Question: Hey all i am trying to get all the likes for a wall post in PHP. The array frame looks like this:
Array (
[data] => Array (
    [0] => Array (
        [id] => XXXXXXXX_XXXXXXXXXXX
        [from] => Array (
            [name] => Bob Barker
            [id] => XXXXXXXXXXX
        )
        [message] => This is a message here!!!
        [story] => We shared a message with others
        [story_tags] => Array (
            [0] => Array (
                [0] => Array (
                    [id] => XXXXXXXXXX
                    [name] => Bob Barker
                    [offset] => 0
                    [length] => 11
                    [type] => user
                )
            )
            [19] => Array (
                [0] => Array (
                    [id] => XXXXXXXXXXXXXXXXXXXXXXX
                    [name] => NAME
                    [offset] => 19
                    [length] => 5
                    [type] => page
                )
            )
        )
        [picture] => [removed]
        [link] => [removed]
        [name] => Timeline Photos
        [caption] => This is just a caption for the post here
        [properties] => Array (
            [0] => Array (
                [name] => By
                [text] => NAME
                [href] => [removed]
            )
        )
        [icon] => https://fbstatic-a.akamaihd.net/rsrc.php/v2/yD/r/aS8ecmYRys0.gif
        [actions] => Array (
            [0] => Array (
                [name] => Like
                [link] => [removed]
            )
        )
        [privacy] => Array (
            [value] =>
        )
        [type] => photo
        [status_type] => shared_story
        [object_id] => XXXXXXXXXXXXXXXX
        [application] => Array (
            [name] => Photos
            [id] => XXXXXXXXXX
        )
        [created_time] => 2014-02-12T21:33:17+0000
        [updated_time] => 2014-02-12T21:33:17+0000
        [likes] => Array (
            [data] => Array (
                [0] => Array (
                    [id] => XXXXXXXXXXXX
                    [name] => John Doe
                )
                [1] => Array (
                    [id] => XXXXXXXXXXXX
                    [name] => Steve Doe
                )
            )
            [paging] => Array (
                [cursors] => Array (
                    [after] => XXXXXXXXXXXXXXXX
                    [before] => XXXXXXXXXXXX==
                )
            )
        )
    )

My current PHP code is:
$feed = $facebook->api('/me/home'); //This is the array above

foreach($feed['data'] as $post) {
  $story = (isset($post['story']) ? $post['story'] : null);
  $id = (isset($post['id']) ? $post['id'] : null);
  $name = (isset($post['name']) ? $post['name'] : null);
  $message = (isset($post['message']) ? $post['message'] : null);
  $post_link = (isset($post['actions'][0]['link']) ? $post['actions'][0]['link'] : null);
  $picture = (isset($post['picture']) ? $post['picture'] : null);

  foreach($post['likes'] as $liked) {
      echo $post['id'];
  }

  echo $name . ' ' . $story . ' it was: ' . $message . ' and ' . $post_link .  ' and
';
  echo '=======================================================================================================';
}

The
foreach($post['likes'] as $liked) {
      echo $post['id'];
}

doesnt seem to be working as-is. What am i missing in order to make it loop through all the "liked" posts in the array?
Answer: Yes
foreach($post['likes'] as $liked) {
      echo $post['id'];
}

will not work since
$post['likes'] elements are again a nested array as
likes => array => data => array=> ..

So you need to do the loop as
if(array_key_exists('data',$post['likes'])){
        foreach($post['likes']['data'] as $liked=>$val) {
            echo '
Like ID: ' .$val["id"].'
' ;
        }
    }

It is always better to do a check if the array key exists before doing the loop, so that if the returned data does not contain the key you do not get undefined index error.
Answer: Try
foreach($post['likes']->data as $like) {
  echo $like->id;
}

Looping through facebook api "likes"


Access file type icons Mac OSX

Question: I am trying to find a way to access the Mac OSX system icons. Does anyone know their default location on a Mac? Or know of a way using Java to have them returned?
There is a method of using JFileChooser for Mac to retrieve an Icon for a file, but the file has to exist on the file system (in my app the file could be streaming from a server so short of creating a dummy file on the system with that extension it wont work).
I can access them on Windows in the following way using SWT (but this bombs on a Mac). The variable "fileType" below for example is ".txt", ".bmp", ".doc", etc:
Program p;
Image image;

//find the correct OS image for the file type and set
//the image to the tree item
p = Program.findProgram(fileType);
ImageData data = p.getImageData();
image = new Image(display, data);

UPDATE: There does not appear to be a clear way to import these. I ended up finding some generic Mac icons online and bundling them with my app to simply use getRecourceAsStream() when on a Mac until a better solution is found.
Comment: http://nadeausoftware.com/node/89 has a lot of decent info on this subject, but your workaround seems to be the only decent way to handle your problem.
Answer: It is late, but maybe somebody else would search for the same problem (like me).
The FileSystemView trick works only for 16x16 images on all platforms. On Mac, you need to use the default Aqua look and feel to make it work.
For Windows, you can use ShellFolder.getShellFolder(file).getIcon(true) to get a 32x32 icon.
For Mac, you can use Quaqua that comes with some Objective-C jni libs that give you the desired/available icon size for any file (16px, 32, 64, 128, 256, 512) :
http://www.randelshofer.ch/quaqua/javadoc/ch/randelshofer/quaqua/osx/OSXFile.html#getIcon%28java.io.File,%20int%29
Answer: On OS X, a FileView works much better than a FileSystemView. I'm using the following to get icons for files:
final JFileChooser fc = new JFileChooser();
//return fc.getFileView().getIcon(f); // will throw a  null pointer
Icon result = fc.getUI().getFileView(fc).getIcon(f);

Answer: I think the FileSystemView and its friends provide way for getting file icons.
Comment: FileSystemView I saw can only return generic file icons. Icons like the hard drive icon on a mac desktop, or a folder. It doesnt support specific file types like MP3, DOC, PPT, XLS, etc.
Comment: Didn't know that as I'm a Win guy. Are you sure it does not work? There is also a weak option to use JNA calls into the OS to get file icons.

Access file type icons Mac OSX