3D 'shooter' jumping algorithm - C++ low level flaw. Two identical doubles do not equal each other when they should. 4.0 != 4.0 apparently

Question:
Possible Duplicate:
Floating point comparison

Well this is a strange one. Ordinarily the following if( 4.0 == 4.0 ){return true} will always return true. In a simple little opengl 3d 'shooter' program I have, when I am trying to add 'jumping' effects, this is not the case.
The idea is fairly simple, I have a terrain of triangle strips, as the 'character' moves/walks you move along a 2d array of heights, hence you walk up and down the various elevations in the hills/troughs.
Outside of the drawScene() function (or if you know opengl, the glutDisplayFunc()), I have an update() function which raises the character up and down as he 'jumps', this is called in drawScene(). In words, as high level as I can explain it, the jumping algorithm is below:
parameters:
double currentJumpingHeight
double maximumJumpingHeight = 4.0
double ypos;
const double jumpingIncrement = 0.1; //THE PROBLEM!!!! HAS TO BE A MULTIPLE OF 0.5!!
bool isJumping = false;
bool ascending = true;

the algorithm:
(when space is pressed) isJumping = true.

if ascending = true and isJumping = true,
      currentJumpHeight += jumpingIncrement (and the same for ypos)

if currentJumpingHeight == maximumJumpingHeight, //THE PROBLEM
     ascending = false
     (we decrement currentJumpingHeight and start to fall until we hit the ground.)

Its very simple, BUT IT ONLY WORKS WHEN jumpingIncrement IS A MULTIPLE of 0.5!!
If jumpingIncrement is, say, 0.1, then currentJumpingHeight will never equal maximumJumpingHeight. The character takes off like a rocket and never returns to the ground. Even when the two variables are printed to the standard output and are the same, the condition is never true. This is the problem I would like to solve, it is absurd.
I don't want any feedback on the jumping algorithm - just the above paragraph please.
please help.
Comment: A duplicate to hundreds of similar questions on the site. Do search.
Comment: Welcome to the world of floating point.
Comment: [What Every Programmer Should Know About Floating-Point Arithmetic](http://floating-point-gui.de/)
Comment: http://stackoverflow.com/search?q=floating+point+equal
Answer: It's just a typical floating point precision problem. In particular 0.1 cannot be represented exactly using binary floating points. Numbers like 0.5 and 0.25 on the other hand can be represented exactly, and thus will probably work. I believe the compiler is still free to make it not work, even in that case.
In your case a solution is using >=:
if ascending && (currentJumpingHeight >= maximumJumpingHeight)
     ascending = false
     currentJumpingHeight = maximumJumpingHeight

You could also use epsilon comparisons, but I avoid them where possible. In your case a simple >= seems cleaner than epsilon equality.
Comment: Yes - thank you very much for your prompt response. Yes it worked well and was a very simple solution. What is an epsilon comparison?

For all other people who have a similar problem - this website may be of use: http://floating-point-gui.de/
Comment: @user1460838 An epsilon comparision is something like replacing `a==b` with `Abs(a-b) <= epsilon` where `epsilon` is a small constant. The problem is that you need to choose a value for epsilon that fits the situation, and that's not trivial.
Answer: As people said, it's a typical floating precision point problem. Look at this
Basically, in the same way you can't code with a finite number of digits 1/3 in base 10
1/3 = 0.3333333333.....

You can't do 1/10 in base 2.
It will be
0.1 = 0x0.0001100110011001100110011001100110011001100110011...

You should never compare floats but check that there difference is smaller than a value, ex
if (fabs(a-b) < 1e-6)

instead of
if(a==b)

Of course in your case, just use '>='.
It work with your 0.5 increment, because 0.5 is 1/2 or 0.1 in binary, so it's coded properly .
That will work for any power of 2 so 0.5 or 0.125, but never with 0.1.
Comment: It might be worth noting that there's nothing fundamentally weird about floating point variables. You can compare them just like any other variable, and you certainly have `0.1 == 0.1`. What is problematic is *arithmetic*: It is *not* necessarily true that `0.1 + 0.1 == 0.2`.
Comment: @MrLister: That's because you're cheating, and `f` is the *result of an operation*. If you say `float f = 0.1f;`, then `f == 0.1f` will be true. You can *not* reliably predict the outcome of a floating point operation.
Comment: @KerrekSB But 0.1 is not always 0.1. An obvious case is `float f = 0.1; if (f==0.1)...` which fails because 0.1 is a double and f is a single. And sometimes, the results can be more subtle and more implementation dependent.


Control Gumstix Overo GPIO

Question: Any suggestions to work with Gumstix Overo Air GPIO pins by Java Library as PI4J
I'm using Pinto-TH shield to interface with the board pins.
Answer: Well that library looks pretty self explanatory, and the example is really good. You just DL the library, copy paste code from the example, and look on the breakout board to see what pin numbers are your LEDs and input pins. I suggest putting male headers on the breakout board so it can either plug into a breadboard or you can wirewrap wires to it.
If you would rather do things yourself, you can refer to: http://wiki.gumstix.org/index.php?title=GPIO. This is what I used in a C++ application. I just wrote and read to the system files to access GPIO.

Control Gumstix Overo GPIO


Should tuples be passed to macro?

Question: The way tuples are handled seems to be not consistent:
defmodule A do
  defmacro a(x) do
    IO.inspect x
    quote do end
  end
end

A.a {:a, :b} prints {:a, :b} as expected, but A.a {:a} prints {:{}, [line: 2], [:a]}
Answer: Macros receive their arguments as quoted expressions, and in Elixir, tuples of length 2 are represented as themselves, and the rest are represented as {:{}, _, [value1, value2, ...]}:
iex(1)> Macro.escape {}
{:{}, [], []}
iex(2)> Macro.escape {1}
{:{}, [], [1]}
iex(3)> Macro.escape {1, 2}
{1, 2}
iex(4)> Macro.escape {1, 2, 3}
{:{}, [], [1, 2, 3]}
iex(5)> Macro.escape {1, 2, 3, 4}
{:{}, [], [1, 2, 3, 4]}

If you inject these values into a quote using unquote, they'll be converted to the actual tuples automatically. We can see that using Macro.to_string/2:
iex(6)> Macro.to_string {:{}, [], [1, 2, 3]}
"{1, 2, 3}"

You can find more information about this in the Quote and unquote -> Escaping Getting Started Guide.

Should tuples be passed to macro?


What circuit capacity will I need for a strand of outdoor lights?

Question: I'm running a strand of lights around my backyard. There's a total of 33 lights. These will only be used in the summer, and taken down in the fall.
What size plug end (amperage Wise), what size circuit, and will I need to change the normal outlet?
Comment: Can you give us more information on the strand of lights?
Comment: Are you in the USA or someplace else?  (Voltage and plug styles vary by country).  In the USA, 33 is a magic number for a string of *LED lights*, but "standard lights" in the title adds confusion if my guess is correct.
Comment: I'm in the US. By standard I simply meant standard E26 size bulb base, not anything else. We're not certain on if we will use Edison style bulbs or LED party bulbs.
Comment: How many watts / lumens will be needed ?
Comment: Find LED bulbs for this.  Regular plug.  350 is long, you want the least total watts possible.  Is this a loop that comes back, or is it a one way run?  If it comes back to the house consider cutting it in half and plugging in two instead of one.
Answer: The limit of 33 bulbs in a string is based on each socket being limited to 40W (it will say that somewhere). 33 x 40 = 1320W, divided by the worst case scenario of 110V (nominal is now 120V, but many places still only provide 110V, so they have to cover that). So 1320W / 110V = 12A, which is the limit of what you can put on a 15A circuit breaker (80% load).
I agree that 350ft is a long distance for a load of 12A, but MOST people in the US will have closer to 120V, so if it drops to 110V, that's still covered. The problem may be if you only have 110V at the outlet, the voltage will drop even more. But on incandescent bulbs that just results in less light, not more current.
If you use LED bulbs however, where the equivalent light of 40W incandescent bulbs will only use 4.5W each, the current will go down significantly (less than 2A total) and there will likely be no perceivable voltage drop.
Answer: 350ft on 14ga wire is going to be some serious voltage drop. With that length, its not a "Let's just run some wire and bulbs and plug it in" thing.
Comment: Hello, and welcome to Stack Exchange. The voltage drop depends on the current draw; it sounds like these lights won't be drawing much current, so the drop shouldn't be too bad. (Plus, if it does, the lights will just get a bit dimmer.)
Comment: @DanielGriscom You want enough fault current to actually trip the breaker on a short, though. That doesn't depend on load, only on total impedance and the current required to trip the breaker.


Data is not being displayed on my listview from the database

Question: I'm trying to display a list of user names from the database in phpmyadmin in my app ,but I keep getting the following
Unable to start activity ComponentInfo{ie.example.artur.adminapp/ie.example.artur.adminapp.ShowUsers}: java.lang.NullPointerException: storage == null

I understand that this means that the data is not being sent sot the activity cannot start when selected ,the list is empty but my question why is the list not filling up wit the data ?
This is my ShowUser Activity
package ie.example.artur.adminapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toolbar;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;

import android.view.View;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import static android.R.attr.name;

/**
 * Created by family on 24/07/2017.
 */

public class ShowUsers extends AppCompatActivity {

    ListView lv;
    //String[] names = {"Amy","John","Joseph","Carl"};
    InputStream is = null;
    String line= null;
    String result = null;
    String temp="";
    String[] arr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.showusers);

        lv = (ListView) findViewById(R.id.lv);

        //Inlfate the list view with the items

        lv.setAdapter(new ArrayAdapter<String>(ShowUsers.this,android.R.layout.simple_list_item_1,arr));

        android.widget.Toolbar toolbar = (android.widget.Toolbar) findViewById(R.id.toolbar);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        //set up the code to fetch data from the database

        try {
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost("http://10.3.2.51/www/");

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            //SETUP THE INPUTSTREAM TO RECEIVE THE DATA (INITIAL)
        }catch (Exception e){
            System.out.println("Exception 1 caught");
        }

        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            // Create a String builder object to hold the data
            StringBuilder sb = new StringBuilder();
            while((line = reader.readLine())!=null)
                sb.append(line+"\n");

            //Use the toString() method to get the data in the result

            result = sb.toString();
            is.close();
            //check the data by printing the results in the logcat

            System.out.println("-----Here is my data -----");
            System.out.println(result);

        }catch(Exception e){
            System.out.print("Exception 2 caught");
        }

        try{

            JSONArray jsonArray = new JSONArray(result);//Create a json array
            int count = jsonArray.length();

            for(int i=0; i<count; i++){
                //create a json object to extract the data
                JSONObject json_data = jsonArray.getJSONObject(i);
                temp +=json_data.getString("name")+":";
                //where name is attribute of the getdata table
                //using ':' as the delimiter

            }

            //Afer receiving everything store the contents in a string array from temo separated using the delimiter
            arr = temp.split(":");
            //set the list adapter with the array arr

            lv.setAdapter(new ArrayAdapter<String>(ShowUsers.this,android.R.layout.simple_list_item_1, arr));

        }catch(Exception e){
            System.out.println("I am really bored of writing all these exception blocks");
        }

    }
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        {
            switch (item.getItemId())
            {
                case R.id.action_settings : startActivity (new Intent(this, ShowUsers.class));
                    break;
            }
            return super.onOptionsItemSelected(item);
        }}

}

This is the table users from the database in phpmyadmin :

Also this where I have my tut.php file saved:

tut.php :
<?php

$con=mysql_connect("localhost","root","");
mysql_select_db("socialmedia_website",$con);

$r=mysql_query("select name from users where 1";

while($row=mysql_fetch_array($r))

    {

        $out[]=$row;
    }

    print(json_encode($out));
    mysql_close($con)

*Also I'm using an Android device to do this project
This is what I'm getting back :
Comment: don't used mysql_* . only used mysqli_*
Comment: **mysql** is deprecated and completely removed in PHP 7. Use **mysqli** or **PDO** instead
Comment: @B.Desai Yes ,I know about I just didn't realize because I was following a video tutorial
Answer: You have an error here . you missed )  closing bracket
$r=mysql_query("select name from users where 1");

Note: use mysqli_* functions.
Comment: I think I will choose this as the right answer because ,you solved my first issue which was the the missing `)` ,then I need ask another question
Comment: Yes I have fixed that but ,a blank screen simply appears ,its empty :/
Comment: does query returns values?
Comment: i think this might help : https://stackoverflow.com/questions/16777829/java-lang-runtimeexception-unable-to-start-activity-componentinfo-java-lang-nu
Comment: The issue is that I'm not getting back any errors now as well,so I don't know what the issue is now
Comment: i'm really sorry i really want to help you more.. but i don't do android..
Answer: $r=mysql_query("select name from users where 1";

You have something wrong with your query, you missed the closing bracket.
Your query should look like this.
$r=mysql_query("select name from users where 1");

Comment: WHERE 1 is a synonym for "true" or "everything."
Answer: setAdapter line duplicated two times.so remove first one because that time arr value is null thats why you are getting NullpointerException
 lv = (ListView) findViewById(R.id.lv);
 lv.setAdapter(new ArrayAdapter<String>(ShowUsers.this,android.R.layout.simple_list_item_1,arr)); //remove this


Schrödinger's wonder

Question: I just had to construct a wonder I already finished. Or did I?
The following confuses me a bit:

Either I finished it and I no longer need to construct it, or I still need to construct it and can't have it finished. For some reason my wonder is both constructed and still in progress (Schrödinger's wonder?). How do I avoid such a situation in the future?
This occurred during a simultaneous multi-player Civ V game (incl. DLC).
Comment: I've noticed with multiplayer that the game can get confused when you have enough production to finish that turn.  You might be able to mouse over your city's gold generation to verify if the building is contributing or not.
Comment: @IllusiveBrian I suspect it wasn't, since it took another turn to complete the building. On the other hand, I never received the notification of having finished the wonder. Not even the 'second' time I finished it.
Comment: Are you using Enhanced UI?
Comment: @IllusiveBrian I have no clue what that is, so, uh, no?
Comment: @Kelexin I posted this question 2 weeks ago and it was a multi-player game not hosted by my. I have no idea whether there still is such a log and where it is.
Answer: Did you happen to build or conquer a new city that turn? The cost of the wonder goes up the more cities you have, so maybe you increased the cost on the same turn it should have been completed?
Comment: This sounds like the most probable explanation so far.
Answer: If you build a new city or conquer one (without the needed building in it) and you are currently building the national wonder, then the production cost goes up and you are no longer able to build it, as you don't have the required buildings to complete it.
As for seeing finished, that is just something Civ V does, devs don't care and it doesn't really cause an issue. Most people just see it as oh it finished working, because it can't work on it more right now.
My usual work around is either paying attention to national wonders to avoid settling/conquering for the turn or two it has left. OR just immediately buying the necessary building(s) to resume wonder production.

Schrödinger's wonder


What is the strength of a TV signal at the antenna?

Question: When understanding signal attenuation along a coaxial cable from an antenna to the television (e.g., signal loss from splitters, coaxial connections, etc), it's also important to understand what the signal power at the starting point is (i.e., at the antenna).
How can we determine signal power at the antenna, before it travels down to the TV?
For instance, my TV antenna has around 12 decibels of antenna gain (it's not amplified). Would this pretty much be the "starting" signal power before it heads for the TV, or is the signal strength calculation more complicated than just using the antenna gain figure? (e.g., depends on the noise margin of the particular TV channel).
Comment: You cannot "guess" the input power - it varies due to many factors which is why meters exist to measure it, so that the system losses can be evaluated.
Comment: Your 12 dB of antenna gain means 16 times as much power is being received compared to the case where you had an omnidirectional antenna (which has 0 dB gain). That still doesn't tell you how much power you are dealing with in absolute terms.
Answer: The signal strength at the antenna is measured in dBm, decibel-milliwatts. A 0 dBm signal corresponds to 1 mW, -90dBm is 1picowatt (pW), one billionth the strength of 0 dBm.
Given the power of the transmitter, transmitting antenna gain, distance, receiving antenna gain and a few other parameters, such as obstructions and frequency, it's possible to calculate the approximate power at your receiving antenna. A television may need -65 dBm or stronger signal for clear reception.
An example of signal-strength calculation is shown at Mathworks.
Some stations make public a chart showing the signal strength at various locations on a map. If you can't find one for a local broadcaster, contact the station for info.


Can't for loop through a whole list in python

Question: I'm trying to code in python to filter a list of the first n integers that when divided have a remainder of 1.  However, it looks like it's not checking every integer in my list according to the print statements I have.  I have no idea why. I'm just starting to learn code, so please be patient with me.  I suspect its something obvious I'm not seeing.
Below is my code I have so far:
def main():
    checkUpTo = 20
    listOfInts = list(range(checkUpTo))
    filterList = [3]
    boolList = []

    for d in filterList:
        print("checking list: " + str(listOfInts) + " for rem=1 when divided by " + str(d))
        for x in listOfInts:
            print("checking: " + str(x))
            isDivisible = checkIfDivisible(x,d)
            if isDivisible==False:
                listOfInts.remove(x)
        print("got list: " + str(listOfInts))

    print(listOfInts)

def checkIfDivisible(number,divisor):
    remainder = number % divisor
    print(str(number) + "%" + str(divisor) + "=" + str(remainder))
    if number % divisor == 1:
        return True
    if number % divisor != 1:
        return False

if __name__ == "__main__":
    main()

Thanks for the help
edit: my output:
checking list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] for rem=1 when divided by 3
checking: 0
0%3=0
checking: 2
2%3=2
checking: 4
4%3=1
checking: 5
5%3=2
checking: 7
7%3=1
checking: 8
8%3=2
checking: 10
10%3=1
checking: 11
11%3=2
checking: 13
13%3=1
checking: 14
14%3=2
checking: 16
16%3=1
checking: 17
17%3=2
checking: 19
19%3=1
got list: [1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16, 18, 19]
[1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16, 18, 19]

not sure why it's not checking 1,3, etc.
Comment: Can you provide an example input and the expected output?
Comment: a list of ints from 0 to n and a filter list.  for example, if the filter list is [2,3] and i'm checking the integers 1 to 10.  first i get [3,5,7,9] because each one is one more than a divisor by 2.  then, checking 3, it would be [7] because it is one more than a divisor of 7.  I'll add the output i get into the post.
Comment: You should not modify the list while you are iterating over it. Have a look at this question and ist answers: https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating
Answer: listOfInts.remove(x) changes the object (listOfInts) you're iterating over in for, which will change the number of iterations in the loop.
Consider:
l = [1, 2, 3, 4, 5]

for index, value in enumerate(l):
    print(l)
    l.remove(value)

print(index + 1) # 3, not 5.

Rather than removing elements from listOfInts, iterate over x in range(checkUpTo), and if you find a value that is divisible by d, add it to a set.
Comment: I see that listOfInts.remove(x) changes the list, but I'm not worried about the number of iterations changing.  but from output it looks like it's not checking 3%3=0 when it does the inner for loop over listOfInts.
Answer: Look at For loop, listOfInts.remove(x) removes element from list. Therefore, your list dose not have those element whose remainder is one.
 for x in listOfInts:
        print("checking: " + str(x))
        isDivisible = checkIfDivisible(x, d)
        if isDivisible == False:
             listOfInts.remove(x)

Lets understand what is hapening in for loop,

List contain element from 0 to 19.

for loop takes 0 and pass it to checkIfDivisible function.

0%3=0 returns False.

isDivisible == False, so listOfInts.remove(x) removes element from position 0.

for loop now fetches next item, since we have removed item from 0 position now at 0 position we have element 1 at 1 position we have elemt 2 and so on.

therefore print statement doesnot display element 1.
 for x in listOfInts:
     print("checking: " + str(x))
     isDivisible = checkIfDivisible(x, d)
     print(isDivisible)
     if isDivisible == False:
         print(x)
         print(listOfInts)
         listOfInts.remove(x)

checking: 0
0%3=0
False
0
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
checking: 2
2%3=2
False
2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Comment: isDivisible is returning True if the remainder is 1, yes? (because number % divisor == 1) so why would it execute the if statement?
Comment: I have explain it above.   Sorry could not format code. getting error.
Comment: Awesome, that's really helpful! Thanks!


Prove that $P(X(n) ≤ k\ln(n)) = 0$ for $k < 1$ and that $P(X(n) ≤ k\ln(n)) = 1$ for $k > 1$

Question: Let $X_1,X_2,\ldots,X_n$ be a collection of independent exponentially distributed random variables each with rate parameter equal to $1$ ($ = 1$).
Also for each integer $n ≥ 1$, let $X_{(n)}$ = $\max\{X_1,X_2,\ldots,X_n\}$.
Show that for $k < 1$,
$$\lim_{n\to\infty} P(X_{(n)}≤k\ln(n)) = 0$$
Also show that for $k > 1$,
$$\lim_{n\to\infty} P(X_{(n)}≤k\ln(n)) = 1$$
I know how to figure out the CDF of the $X_{(n)}$ , which is (with $ = 1$)
$$F_{X_{(n)}} = P(X_{(n)}≤x) = [1-e^{-x}]^n$$
But I got stuck here. I am not sure how to proceed to show the two separate limit values.
Help is much appreciated. Please and thank you.
Answer: So taking $x=k\ln(n)$, you have, for any $k>0$,
$$P\Bigl(X_{(n)}\le k\ln(n)\Bigr)=\left(1-\mathrm e^{-k\ln(n)}\right)^{\!n}=
\exp\left(n\ln\Bigl(1-n^{-k}\Bigr)\right).$$
Since $\ln(1-n^{-k})\sim-n^{-k}$ as $n\to\infty$, the last expression is $\exp\bigl(-n^{1-k}+o(n^{1-k})\bigr)$. Can you conclude?
Comment: Sorry, but I am having trouble understanding. I understand how you got up to exp(nln(1-n^-k)), but I don't really understand how you went from that to the last expression is exp(-n^(1-k) + o(n^(1-k)). Would you please expand a bit more? Thank you.
Comment: @passerby I updated my answer. Basically, $\ln(1+x)\approx x$ for $x$ small (the logarithm of $1+x$ at $0$ is best approximated by its tangent).
Comment: If you want, you can form $$n\ln\Bigl(1-n^{-k}\Bigr)=\frac{\ln\Bigl(1-n^{-k}\Bigr)}{n^{-k}}\cdot n^{1-k}$$ and use that $$\frac{\ln\Bigl(1-n^{-k}\Bigr)}{n^{-k}}\xrightarrow[n\to\infty]{}-\frac{\mathrm d}{\mathrm dx}\Bigl[\ln(1-x)\Bigr]\Big|_{x=0}.$$
Comment: Thank you for your expansion. I understand it a bit better now and get the -n^(1-k) portion, but what is that o(n^(1-k))? I don't understand that notation and/or why it is there. I am sorry for troubling you. If you could let me know what that topic/technique is I can also look it up. Furthermore, for your second comment with the d/dx, is that just l'hospital?
Comment: It's [little-o notation](https://en.wikipedia.org/wiki/Big_O_notation#Little-o_notation). But you can forget about that and check my other comment.
Comment: I am not really following the second line of the second comment and I am not sure how to proceed unfortunately.
Comment: @passerby it's $(f(x)-f(0))/(x-0)$ for $f(x)=\ln(1-x)$ and $x=n^{-k}\to0$, so it tends to $f'(0)$. However I put a minus sign which shouldn't be there, sorry.


How can one translate an orthogonal vector along parallel lines to a desired location?

Question:
Question:
How can one translate a perpendicular along parallel lines to a given point?
Here is the problem. Given a curve $\mathscr{C}$ (blue), a point $A\in \mathscr{C}$, the tangent line $T_A$ (green) at $A$, the line $L_A$ (orange) going through the origin parallel to $T_A$, and the orthogonal projection $P(A)$ of the plane onto $T_A$, and a point $B$ not on $\mathscr{C}$, and $E=P(A)A$ and $D=P(A)B$, the orthogonal projections of the points $A$ and $B$ onto $L_A$. Find the point $C\in T_A$ such that $DC$ is orthogonal to $T_A$ (and hence $L_A$), where again $D=P(A)B$. In otherwords, extend the line $DB$ down to $T_A$, maintain the perpendicularity.
Intuitively, we are translating the line $AE$ along the line $T_A$ until one of the endpoints reaches $D=P(A)B$. How do we do this?
Answer: While writing out the question here, I believe I figured it out algebraically so I figured a Q&A cannot hurt. The answer is that
$$C(B) = P(A)(B-A)+A$$
is the orthogonal projection of the plane $\mathbb{R}^2$ onto the tangent line $T_A$ of the curve $\mathscr{C}$ at $A$.
Proof: Indeed, we need the translation of $E=P(A)A$ to land at $D=P(A)B$. That is we need a point $T$ such that $E+T=D$. It follows that $x_T = x_D-x_E$ and $y_T = y_D-y_E$, hence
$$T=D-E=P(A)B-P(A)A=P(A)(B-A),$$
but this needs to be applied to the point $A$ to translate along $T_A$ instead of along $L_A$. Thus, we set
$$C=A+T=A+P(A)(B-A),$$
proving the claim.
Here is the picture reproduced with the output point $C$ as defined above:


One entry point in WORKSPACE for managing various python project requirements

Question: My Bazel project structure is like this
├── BUILD
├── WORKSPACE
├── example.py
├── reqs.bzl
└── requirements.txt

I have created my WORKSPACE like this
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "rules_python",
    sha256 = "a30abdfc7126d497a7698c29c46ea9901c6392d6ed315171a6df5ce433aa4502",
    strip_prefix = "rules_python-0.6.0",
    url = "https://github.com/bazelbuild/rules_python/archive/0.6.0.tar.gz",
)

load("reqs.bzl","load_reqs")
load_reqs()

I did that as I want to have one entry point in WORKSPACE from where I can manage dependencies for various python based projects. my reqs.bzl looks like this
load("@rules_python//python:pip.bzl", "pip_parse")
load("@rules_python//python:pip.bzl", "compile_pip_requirements")

def load_reqs():
    compile_pip_requirements(
        name = "pyreqs",
        requirements_in = "//:requirements.txt",
        visibility = ["/visbibility:public"]
    )

My BUILD file looks like
load("@pyreqs//:requirements.bzl", "requirement")

py_binary(
   name="example",
   srcs=["example.py"],
   deps=[
      requirement("absl-py"),
      requirement("numpy"),
      requirement("scipy"),
      requirement("matplotlib")
   ],
   visibility=["//visibility:public"]
)

This above setup is obviously failing to build my example.
I tried compile_pip_requirement as I couldnt pip_parse, load and invoke install_deps() from  the load_reqs() function of reqs.bzl
Appreciate any input from the community on how this has to be done correctly.
PS: Still climbing that Bazel learning curve and trying to figure out best practices. The primary motivation behind above project setup is, I have to add lot of python targets and I don't want to have a large WORKSPACE file and frequently make edits to it.
requirements.txt
absl-py==1.4.0
cycler==0.11.0
kiwisolver==1.4.4
numpy==1.24.2
pillow
matplotlib==3.3.4
python-dateutil==2.8.2
pyparsing==3.0.9
pytz==2022.7.1
scipy==1.10.1
six==1.16.0
requests

bazel build //:example gives error
ERROR: Traceback (most recent call last):
        File "/home/ubuntu/bazel-tests/python-ex-2/WORKSPACE", line 11, column 10, in <toplevel>
                load_reqs()
        File "/home/ubuntu/bazel-tests/python-ex-2/reqs.bzl", line 5, column 29, in load_reqs
                compile_pip_requirements(
        File "/home/ubuntu/.cache/bazel/_bazel_ubuntu/7d424a81034067ed3c4b3321d48bbdb4/external/rules_python/python/pip_install/requirements.bzl", line 40, column 21, in compile_pip_requirements
                native.filegroup(
Error in filegroup: filegroup cannot be in the WORKSPACE file (used by //external:pyreqs)
ERROR: Error computing the main repository mapping: error loading package 'external': Package 'external' contains errors

Comment: Try clean and rebuild the project. make sure all the external dependencies are properly downloaded or not. Try adding --verbose_failures and --verbose_explanations to understand more clearly the logs
Answer: compile_pip_requirement is a rule that should be used in BUILD files, not WORKSPACE file.
Seems there is no way to load a .bzl file other than load().
new_local_repository doesn't work because it won't evaluate WORKSPACE in external workspace.
If you can accept one single load() and install_deps, maybe you can write a repository rule that merge all requirements.txt into one file, then call pip_parse, load() and install_deps once in your workspace root.
Otherwise, you can only figure out how pip_parse work and write your own.


developing a windows service in C++ without Visual Studio template?

Question: I have a version of Visual Studio 2005 that doesn't include a Windows Service project template.  Can I just build a (C++) console application and install it as a service without doing anything special within the application code itself.
Answer: All the service project template does is supply you with some source code to get started. Although you can't take an ordinary console application and make it a service app, you can implement the ServiceMain function following the instructions on that reference page.


Nvidia graphic driver is installed but the graphic card is not used!

Question: It seems like the system has successfully installed the nvidia proprietary driver as shown in the below image

However it seems like the system is not using the graphic card.

I am not sure what should I do from here. I followed almost every step required to use the graphic driver but it is still not using it.

BTW, there should be some way to configure to use graphic card on nvidia-x server settings but it is not showing up on my machine.
Also, the output of glxinfo clearly shows that my system is not utilizing the nvidia graphic card.
jaebum@jaebum-laptop:~$ glxinfo | grep renderer
    GLX_MESA_multithread_makecurrent, GLX_MESA_query_renderer,
    GLX_MESA_multithread_makecurrent, GLX_MESA_query_renderer,
Extended renderer info (GLX_MESA_query_renderer):
OpenGL renderer string: Mesa DRI Intel(R) HD Graphics 530 (Skylake GT2)

Any help is welcomed :)
Note that my system is ubuntu 16.10.
(* it is a laptop so I am pretty sure I didn't make mistake like My drivers recognize my graphics card, but nvidia settings do not )
EDIT
I also added the result of the following command
jaebum@jaebum-laptop:~$ lspci -k | grep -EA3 'VGA|3D|Display'
00:02.0 VGA compatible controller: Intel Corporation HD Graphics 530 (rev 06)
    DeviceName:  Onboard IGD
    Subsystem: Micro-Star International Co., Ltd. [MSI] HD Graphics 530
    Kernel driver in use: i915
--
01:00.0 3D controller: NVIDIA Corporation GM107M [GeForce GTX 960M] (rev a2)
    Subsystem: Micro-Star International Co., Ltd. [MSI] GM107M [GeForce GTX 960M]
    Kernel modules: nvidiafb, nouveau, nvidia_375_drm, nvidia_375
02:00.0 Network controller: Intel Corporation Wireless 3165 (rev 81)

EDIT2
output of the following command
root@jaebum-laptop:/usr/lib/x86_64-linux-gnu# dkms status
bbswitch, 0.8, 4.4.0-79-generic, x86_64: installed
bbswitch, 0.8, 4.8.0-54-generic, x86_64: installed

Comment: Disable Secure Boot in BIOS.
Comment: already did that :)
Comment: Please [edit] your question and add output of `lspci -k | grep -EA3 'VGA|3D|Display'` terminal command.
Comment: I just added the output of that command @Pilot6
Comment: The kernel module is not loading for some reason. What does `prime-select query` output? It is either a Secure Boot issue, or the driver is incorrectly installed.
Comment: prime-select query returns unknown. Hmm weird. I am sure that I turned off the secure boot. Should I try reinstalling driver then?
Comment: Run `sudo apt purge 'nvidia.*'` then `sudo apt install nvidia-375 nvidia-prime`.
Comment: @Pilot6 I have done that. Will check after reboot. Thanks for your help anyway.
Comment: Did you notice any error messages?
Comment: No there was no error message.
Comment: I guess my laptop is doomed to not accept nvidia graphic card :(
Comment: So does it work now? If not post the output of `dkms status`.
Comment: root@jaebum-laptop:/home/jaebum# dkms status
bbswitch, 0.8, 4.4.0-79-generic, x86_64: installed
bbswitch, 0.8, 4.8.0-54-generic, x86_64: installed
Comment: Please post it to your question. Is this the full output?
Comment: yeah that was full output
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/60052/discussion-between-jaebum-and-pilot6).
Answer: Most probably you have a Secure Boot option enabled, and that feature is preventing nVidia's kernels from loading, thus Ubuntu will use the integrated card only.
Try temporarily disabling the Secure Boot feature, and test if the nVidia card is being utilized.
Disabling the Secure Boot should be possible via your UEFI BIOS (I access mine with F2 when the system starts booting).
If that turns to be the case, you have to sign the nVidia driver, which is a saga in itself.
Answer: Your lap-top has hybrid graphic. It switches to nvidia gpu when applications needs more video memory.
You need to install bumblebee to render graphic. F.e.
optirun firefox >/dev/null 2>&1 &.
Please check this resource:
Bubmlebee for Ubuntu
How to install nVidia drivers with Bumblebee on Ubuntu 14.04
Comment: Is there way to run every program solely on nvidia drivers, not using the stupid intel thingy?


Checking and deleting multiple occurrences of the same value in an array using javascript

Question: This is what I've been trying, but something is wrong with the last part, can sy please tell me whats wrong, or show me an other method of doing this. Thanks in advance.
function removeSpaces(string) {
  var str = string.replace(/^\s*|\s*$/g,'')
  str = str.replace(/[^a-z|A-z|\r\n]/g,'');
  while (str.indexOf("\r\n\r\n") >= 0) {
    str = str.replace(/\r\n\r\n/g, "\r\n");
  }
  words = str.split("\r\n");
  var i = 0;
  var j = 0;
  for (i = 0; i < words.length; i++) {
    for (j = i; j < words.length; j++) {
      if ((i != j) && (words[i] == words[j])) {
        words.splice(j,1);
        j--;
      }
    }
  }
  str = words.join("\r\n");
  return str;
}

Comment: This question is similar to this one: http://stackoverflow.com/questions/6940103/how-do-i-make-unique-array/6940165#6940165
Answer: You could use the filter function. The filter function of an array is returning an array containing elements which pass to a certain filter.
var isLastElement = function(element, index, array){
    return (index == array.lastIndexOf(element));
};
words = words.filter(isLastElement);

In this example, the filter function goes through the elements of the initial array ad add this element to the new array only if isLastElement(element, elementIndex, initArray) return true.
The isLastElement function returns true only if the element is not present a second time in the end of the array.
Comment: Note that IE (don't know which versions) does not support `indexOf` and `lastIndexOf` for arrays.
Comment: Im sorry, I don't really see what this does. could you please explain?
Comment: @Gabor Magyar: I edited my answer, to explain what is the function doing.
Comment: @Gabor Magyar: You're welcome. Glad it helped you. However as Felix Kling said, it might not work on all browser, you can have a look at the link I posted as a comment to your question for other solutions.


How do you edit your name in War of the Roses?

Question: I can't find where the user name gets set. How do I change it from the default?
Comment: I beleive it just utilizes your Steam name, but I'm unsure how the name is determined in the non-Steam version (or whether there is a non-Steam version, for that matter)
Answer: You have to buy the full version of the game in order for you to change the name settings. Go to "Manage Soldier" and you have the option of changing your name. Name changes can only occur though every 60 days.


Time difference (timeIntervalSinceDate)

Question: I am having trouble with this bit of code, the output is always -596523 hours, -14 minutes.
any ideas?
<code>NSDateFormatter *Formatter = [[NSDateFormatter alloc] init];
[Formatter setDateFormat:@"HH:mm"];
NSDate date1 = nil;
if (count == 0) {
    date1 = [NSDate date];
    _startTime.text = [Formatter stringFromDate:date1];
    [sender setTitle:@"Stop" forState:UIControlStateNormal];
}else {
    NSDate date2 = [NSDate date];
    _stopTime.text = [Formatter stringFromDate:date2];
    _startStopLabel.hidden = YES;

    long diff = (long)[date2 timeIntervalSinceDate:date1];
    diff /= 60; //Convert to minutes
    _totalTime.text = [NSString stringWithFormat:@"%d hours, %d minutes", diff/60, diff%60];
}
</code>
Comment: The else branch will always measure the difference between date2 and nil.
Comment: NSLog your two NSDate values.
Comment: @danh Move your comment to the answer section.
Comment: Thanks @danh, sorry for the late reply :)
Answer: The else branch will always measure the difference between date2 and nil.

Time difference (timeIntervalSinceDate)


MVC LabelFor to replace underscores with CamelCase

Question: my DB model has the column name with  "_" in the field name.
is there a way to dislay these values in Camel Case when displaying in the form? like
"BusinessName"
i am using asp.net MVC3 with Razor
@Html.LabelFor(model => model.business_name)

Answer: Could you not just use the DisplayAttribute?
Comment: +1, that's the correct way. Add to your answer that view models should be used instead of some EF autogenerated domain entities into the views and your answer will be perfect. Also instead of saying *Could you not just use ...* you should say *You should use ...*.
Comment: i am using Edmx file with db first. how can i use disaplyattribute
Comment: Yes, I would have said, "You should", but I guess I answered in the form of a question because I wanted to share that tidbit of info, but also ask if it was appropriate for his application. I also totally agree about using View Models, which is what I do. I do not like decorating my domain entities with attributes, but rather create View Models and decorate those. Thanks for the +1.
Answer: You need a new metadataprovider which can inherit from the default one like this:
using System;
using System.Web.Mvc;
using System.Collections.Generic;

public class MyMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        if (metadata.DisplayName == null)
            metadata.DisplayName = GetDisplayNameFromDBName(propertyName);

        return metadata;
    }

    private string GetDisplayNameFromDBName(string propertyName)
    {
        return ...;
    }
}

Register it in global.asax like this:
ModelMetadataProviders.Current = new MyMetadataProvider();

You just need to provide the implementation of GetDisplayNameFromDBName to provide the correct display name given the property name
Answer: Why don't you just use @Html.Label("Business name")?


panda df: Subset frame by condition in 2 columns

Question: I want to subset my df based on the condition of 2 columns:
Date and Person
Condition:
Date must be NON-BLANK except when Person =='Peter'
Tried the code but doesn't work, it removes ALL rows with blank in Date
df= df[ (df[df.columns[1]]!='peter') & (pd.isnull (df[df.columns[0]])!=True)]

INPUT

Date        |  Person  |
            | tom      |
            | peter    |
            | jack     |
2010-10-4   | harry    |
2010-12-4   | sarah  |

DESIRED OUTPUT

Date        |  Person  |
            | peter    |
2010-10-4   | harry    |
2010-12-4   | sarah  |

Comment: You "and" the conditions together. So there has to be *and* a non-null date, *and* a name that is not peter. tom and jack have null dates, so they will also be removed.
Answer: Chain condition by | for bitwise OR by columns names:
df = df[df['Person'].eq('peter') | df['Date'].notna()]

Or by positions - selected columns by DataFrame.iloc:
df = df[df.iloc[:, 1].eq('peter') | df.iloc[:, 0].notna()]
print (df)
        Date Person
1        NaN  peter
3  2010-10-4  harry
4  2010-12-4  sarah

Answer: You need to use | (boolean OR):
  # keep if peter               OR    if the data is NOT null
df[df[df.columns[1]].eq('peter') | ~df[df.columns[0]].isnull()]


How can i get my ul element bullet point start from left corner

Question: I would like my bullet point start from left corner. Below image shows my bullet point adding some padding or margin on the left corner.

CSS
.midContent {
overflow:hidden;
}
 .midContent div {
min-height: 200px;
padding: 10px;
}
#leftDiv {
float:left;
width:49%;
}
#rightDiv {

 }
.midContent ul{
margin:0;
padding-left: 1em;
list-style-position: inside;
}

HTML

 Manufacturing;

Professional services;

 Manufacturing;

Professional services;

Answer:

Coffee

Tea

Milk

Comment: `.midContent ul{
 margin:0;
 padding-left: .5em;
 list-style-type:disc;
}`
Comment: The above code worked well to me. Thanks @anshual gera
Answer: Add style padding-left: 1em; to your ul


How to saw inground lumber

Question: My townhouse has some outdoor stairs built out of 6" x 8" lumber. A couple of the steps are rotten and I need to change the lumber. There is also a perpendicular long piece of lumber that crosses underneath the steps, more or less flush with the ground (highlighted in yellow, in the first image below). While I am replacing the lumber for the rotten step I think it would be a good occasion to replace that other rotten piece as well. I don't want to dismantle the whole staircase for that, but I am hoping to cut off the lumber at the base of the second step, so that the new piece extends below the first step (so it is not apparent that the lumber was cut) (the red line in the second picture).

I am assuming that this piece of lumber is not structurally important (it's pretty rotten right now, and the rest of the staircase is still standing), and there will be no other negative side effect to my plan. Does anyone disagree?
What is the best way to cut it off? Maybe it's so rotten that just hacking at it with a hammer / crow bar might do it... but I am not sure.
What is the best way for preventing this from rotting again? It is pressure treated, but it rotted anyway. Is there some sort rubber sheet/lining that I should use between the lumber and the soil?
Comment: Lumber in contact with the ground, will eventually rot.
Comment: It's important to keep water from pooling against the wood. Even pressure-treaded lumbar will rot if it's constantly wet. Typically wood should not be in contact with the ground at all, but if you must keep this general layout, make sure water isn't collecting.
Answer: I would cut off the timber in the ground using a Sawzall type tool (reciprocating saw) that has a long rough cut blade installed. You can get blades as long as 12 inches that can easily reach into tight spots and cut the wood. Soil will wear the teeth away fairly quickly and so be prepared to replace the blade.
I've used this technique to cut roots free from stumps when removing a tree. Works very well.
Answer: I would use a chain saw myself, but if you dig out adequate clearance, even a hand saw will work. You'd have to also dig clearance for a chain saw, running the chain in dirt is a bad thing. Thoroughly clean the chain after doing this work.
You may find the wood is rotted beyond where you plan to cut. It's important to remove all rotted wood or else it will spread into competent wood, it's sort of like cancer. Thus you will be cutting into competent wood, so simply prying out rotted wood is not enough. Go with your plan, but be prepared for the scope to grow substantially.
There are different levels of pressure treatment, foundation grade is the highest treatment level and really the only level suitable for direct burial. Barrier materials will help to some degree, but ultimately all wood in the ground will rot, as Tester101 points out.
You might consider using concrete or masonry materials anywhere the structure is in contact with earth to avoid this.

How to saw inground lumber


I know there is a pressure vacuum breaker here, but what is the rest?

Question: First, a labeled picture of the situation:

There are three ends, two in the ground and one in the house. How can I figure out which way the water is flowing?
There are four labeled valves (and one hose bib valve I left unlabeled). I'm guessing C and D are part of the pressure vacuum breaker, but I don't know what any of them are for. What is the purpose of each valve? Turning them all off does not seem to affect water in my house (I only ran water for about 15 seconds). Does that mean water is flowing out of my house at end 2 and into the ground at both ends 1 and 3?
Some additional context: this setup is on the back of my house. I have a pool and an in-ground irrigation system. There is a double check valve in front of my house that I would expect to control my irrigation system, but maybe it only controls the zones in front of my house (I'll be buying a valve handle soon to test it).
Comment: Is your water main even on this side of the house?  i suspect its fed on the other side and the two pipes going to the ground (1&3)  feed the irrigation(3) and the pool(1) from the one coming out of the house (2).When you turned all valves off and still had pressure in the house this was confirmed.  C and D are the Irrigations pressure breaker.  A is pool shut off. and B is shut off for irrigation... maybe...
Comment: looks like the vacuum breaker is incorrectly installed ... valves B and C should not be there if they disable the vacuum breaker  from operating for `1` and for the garden hose
Comment: Nice job of labeling - it's made the discussion _so_ much easier!
Comment: The main is on the other side of the house, before the double check valve. I wouldn't be surprised if the PVB is incorrectly installed. If 1 is going to the pool, then the PVB was probably added after, when the irrigation system was installed, and they were too lazy or the owner didn't pay for them to reconfigure the existing pipe.
Comment: B seems to be turned off, but my back sprinklers work. If I turn B on, water starts leaking out of the PVB. Does that mean the PVB is broken? Besides irrigation, where could that water be going?
Answer: In my area, it is common for PVB to break if incorrectly winterized, but local water code requires these to be installed and inspected annually, with an inspection report filed with the city water authority. I see duct tape on the PVB so this is likely cracked and causing the leak you mentioned in a comment.
I'd hazard a guess that water does come from the house at (2), flows toward (A), (B) and the hose bibb from there. You can verify this by closing (A) and (B) and running the hose bibb to ensure it still works. Run it long enough to be sure you have flowing water and not just clearing the pipe.
With (A) and (B) turned off, you can also test-run anything that you think is attached to them. Once the water in the pipes (1) and (3) is drained, they should no longer run (and if it's a pool and irrigation as suspected, you'd notice lack of pressure even before the lines are fully drained). You mentioned you may have a separate irrigation line so it's possible that one or both of these don't go where you expect. Specifically, if any of (B), (C), (D) are turned off and irrigation still runs, it's not fed from 3.
(B) (C) and (D) may seem redundant as they all feed or cut off the pipe (3). In my system, (B) is located inside the house to cut water off before it flows outside, so the system can be winterized. (C) and (D) are also for winterizing by pumping compressed air through each zone to clear out any water and prevent it from freezing. The shutoffs prevent air from escaping into the house as the lines are pressurized with air.
Comment: The duct tape is just to hold the insulation on. Based on the comment at 1:16 of [this video](https://youtu.be/D6SJFppq23Y?t=76), I'm concluding that the PVB broke during a freeze and that I need [this kit](https://www.amazon.com/gp/product/B00JKXE0G8/) to fix it (the leak is only out of the bonnet). I should have realized this earlier, but A and 1 go to my outdoor kitchen. All my sprinklers work with B closed, so 3 might go to my pool. I'll find out after I fix the PVB.


Constructing a polynomial with certain zeroes.

Question: I want to construct a polynomial $f(x)$ that has zeroes at $-9,\,-5,\,0,\, 5,\, 9$.
Can somebody provide a method (or perhaps some hints) for solving this?
Answer: And nowhere else, I guess, otherwise the zero polynomial will do. And I assume your are working over the rationals, say.
Just use the fact that $f(x)$ has a zero at $a$ if and only if $x - a$ divides $f(x)$.
Answer: Zeroes at $-9$, $-5$, $0$, $5$, $9$... This means that the polynomial will be of the form:
$$f(x)=a(x)(x+9)(x+5)(x-5)(x-9)$$
Where $a$ is a constant. Any value of $a$ will work here. These are all correct answers:
$$f(x)=x(x+9)(x+5)(x-5)(x-9)$$
$$f(x)=\sqrt 2(x)(x+9)(x+5)(x-5)(x-9)$$
$$f(x)=\pi x(x+9)(x+5)(x-5)(x-9)$$
How did I construct this? The zeroes are $-9$, $-5$, $0$, $5$, $9$, which means that these $5$ values of $x$ will make $f(x)$ equal to $0$. Anything times $0$ will make the product $0$. These $5$ values will make $1$ factor equal to $0$, which makes $f(x)=0$.
Comment: In fact $a$ can be any polynomial.  If it has roots, there will be some more, but this is not prohibited by the question.  Of course, it is simplest to take $a=1$ as you did in your first answer.
Comment: Great answer. Thank you very much!
Answer: If you want a polynomial that lies in $\mathbb{Z}[x]$ consider $f(x)=x(x+9)(x-9)(x-5)(x+5)$. This is the polynomial with the minimal degree such that it has zeros at $0,\pm 9,\pm 5$.
Answer: Try this:
$$f(x):=(x-5)(x+5)(x-9)(x+9)x$$


Call a function in AppDelegate?

Question: Following the solution (the highest-voted answer actually) at UITextField Example in Cocos2d, I managed to do it except the line
[[[UIApplication sharedApplication] delegate] specifyStartLevel];

I have placed it in my scene, I get this warning:

Instance method '-specifyStartLevel' not found (return type defaults to 'id')

Why is that? I clearly have -specifyStartLevel defined in the header and implementation of my AppDelegate...

Edit: Declaration of specifyStartLevel
#import <UIKit/UIKit.h>

@class RootViewController;

@interface AppDelegate : NSObject <UIApplicationDelegate,UITextFieldDelegate> {
    UIWindow            *window;
    UITextField *levelEntryTextField;
    RootViewController  *viewController;
}
- (void)specifyStartLevel;
@property (nonatomic, retain) UIWindow *window;

@end

And implementation:
- (void)specifyStartLevel
{
    [levelEntryTextField setText:@""];
    [window addSubview:levelEntryTextField];
    [levelEntryTextField becomeFirstResponder];
}

Comment: Please provide the code of the declaration of specifyStartLevel.
Answer: Right now, your class doesn't know anything about your delegate's methods.  You need to import your delegate into your implementation, not your interface (to avoid cycled imports).
For example,
#import "AppDelegate.h"

Then you should cast the returned delegate in your nested method call to be your delegate type.  For example:
[(AppDelegate *)[[UIApplication sharedApplication] delegate] specifyStartLevel];

Comment: Thanks - no more warnings. However, the keyboard does not appear when I call it from the scene. Yet, if I call the function right inside the AppDelegate, it does. Got ideas?
Comment: That's odd.  Please either set a breakpoint or put a log inside the `specifyStartLevel` function to see if it is even run when called from within your subclass.
Comment: It seems it is being called after all. However, the keyboard doesn't seem visible at all.
Comment: Well that's odd.  I'd just create a new question here on SO with your problem instead of trying to figure it out here.
Comment: Ah! I was creating the UITextField *after* running the scene. And the scene was trying to open the keyboard from the init method... Thank you sir.
Comment: Glad you fixed it!  Best of luck on your project. :)
Comment: One little question: how can I change it so it is landscape instead of portrait?
Comment: Change what so it's portrait?  The app?  You can do that in your Xcode project settings.
Comment: I mean the UITextField itself. You see, my game is landscape, but for some reason the above code gives me a textfield with portrait-like orientation (I write vertically).
Comment: Whoops, looks like I didn't see your question. Perhaps that'd be better answered in a new question.
Answer:
Add your method in AppDelegate.h file such as:
- (void)Welcome

Implement the method in AppDelegate.m file such as:
 - (void)Welcome
 {
     NSLog(@"Welcome")

 }

Set the UIApplication delegate in method such as:
AppDelegate *appDelegate=[UIApplication sharedApplication] delegate];

[appDelegate Welcome];

Answer: You need to import the AppDelegate into the .m file where you use
[[[UIApplication sharedApplication] delegate] specifyStartLevel];

I like to import it with a header that gives me a shortcut.
GlobalData.h

#import "AppDelegate.h"
#define APPDELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]

Then when I use it in any class I just
#import "GlobalData.h"

// to gain access to the delegate
AppDelegate * appDelegate = APPDELEGATE;

I use this approach because I can then store more #define's to some global constants
(ie soundFXVolume - #define SOUND_FX_V 0.6)
Comment: +1 for the macro.  Normally I'd say they're evil, but in this case it's useful.
Answer: -[UIApplication delegate] returns an object of type id<UIApplicationDelegate>, so the compiler only knows the methods that objects of that type respond to, even thought your custom delegate responds to specifyStartLevel. You can either ignore the warning, or cast the return value of -[UIApplication delegate]:
[(YourCustomAppDelegate *) [[UIApplication sharedApplication] delegate] specifyStartLevel];

Comment: yup it is totally innocent until you change the method signature and forget to update elsewhere in code. If you had removed the original warning you would then get a nice new one telling you about this. If I had my way I would always compile with `-Werror`
Comment: Casting would be preferred over ignoring the warning. Warnings are called warnings for a reason and it can lead to subtle bugs if you get into the bad habit of ignoring them.
Comment: @Paul.s: True, but in this case, it's definitely safe to ignore.
Comment: @Paul.s: One of the drawbacks of working with a dynamically-typed language. Unit tests should practically prevent such errors. But, you can cast if you're so inclined, so best of both worlds.

Call a function in AppDelegate?


Use Google managed ssl certificate with dockerized uwsgi app

Question: I am using Terraform to deploy the infrastructure for my app.
One of the modules is this: https://github.com/terraform-google-modules/terraform-google-lb-http to create a Load Balancer with a registered domain and everything.
My app works perfect in HTTP mode, but once I want to use SSL, TF creates the certificates on GCP and redirects all traffic to HTTPS.
The problem is that the app is not responding and getting 503 all the time with the error malformed HTTP request
I guess I have to run uwsgi inside the container in HTTPS mode but for that I need the certificate and private key files to be available locally inside the container.
According to GCP support, right now we cannot download these files.
Is there any solution or workaround that I can do?
Comment: If you are using a Google HTTP(S) load balancer, the backend is configured only for HTTP. That way you do not need certificates on the backend. However, if you require full encryption, you can use a self signed certificate on the backend.
Comment: So, you're saying the backend can stay HTTP and it should work?
Comment: Yes, you can configure backends to use either HTTP or HTTPS or both. The load balancer supports each configuration type.
Comment: @JohnHanley this actually worked. If you post it as answer, I'll mark it.
Comment: Give the award to @paumanel since he did post the correct answer.
Answer: As commented by John, if you want to configure your application for HTTPS traffic using a Google Cloud External HTTP/S Load Balancer, you can keep the backend using HTTP meanwhile the external clients can still connect using HTTPS to the Load Balancer Frontend.
This would look something like this:
Client --- (HTTPS) ---> Load Balancer --- (HTTP) ---> Backend
If you want to also encrypt the private traffic from the Load Balancer to your docker application, you will need to use your own self signed certificate on the application itself.


HP Officejet Pro 8720 with Ubuntu 20.04 can't scan from PC

Question: Ubuntu 20.04LTS --
Printing works fine so I don't want to mess that up since I print more often than I scan.
There are 58 items in usr/share/hplip/ including a folder called scan with 3 items.
Simple scan does not find a scanner.
This would be nice to have but I can work around it by plugging a USB stick in and capturing the scan there.
If anyone has gotten this to work, I'd be interested in the solution.
Thanks!
Comment: This post should not be on here. There is a Stack for a problem of this sort. Here is the link: https://stackapps.com/questions
Comment: I use a multi-function HP 8740 with Ubuntu, and printing and scanning (with simple-scan) work flawlessly. Please Edit your question an let us know how had you originally installed and setup your printer?
Comment: @PJSingh The printer was here before the computer and printing and scanning has been working fine with both MS Windows and Mac OS. The Ubuntu laptop found the network printer during its initial set up without me doing anything. However, I have never been able to scan from the computer. I'm new to Linux but did have a chance to work with UNIX on a RISC 6000 machine in the early 1990's so if my comment isn't helpful, that's why. I'm wondering if I'm just missing part of HPLIP?
Answer: The HP Linux Imaging and Printing site lists all supported printers.
The good news is that "HP OfficeJet Pro 8720 All-in-one Printer" is listed as a supported printer. Additionally the 7th column shows that "Scan to PC" is also supported for this model.
Install HPLIP (HP Linux Imaging and Printing)

Open a terminal
(Although most things in Ubuntu can be done using a GUI interface, I'll list the commands because it's more expedient and also easier to document the exact steps).

Ensure you have the software repository enabled
sudo apt-add-repository universe

This will automatically update your repositories, but you can also execute sudo apt update to manually update, if needed.

Install HPLIP
sudo apt install hplip

Optionally, install HPLIP GUI tools
sudo apt install hplip-gui

Setup your printer (HP OfficeJet Pro 8720 All-in-one Printer)

Get your printer's network name
On your printer's LCD control panel, drag the gray top-bar down, tap the network icon, and write down the Host Name.
The network name may be something like "HP_OfficeJet_Pro_8720".
(You can use your printer's IP address, but I highly recommend setting up your printer using its network name, because IP addresses can change).

Setup HPLIP to use your printer
On your Ubuntu computer, execute the following command.
Replace "HP_OfficeJet_Pro_8720" with the actual network name of your printer from the previous step.
Be sure to add .local at the end, as shown!
sudo hp-setup -i HP_OfficeJet_Pro_8720.local

Supply the following information when requested:

Please enter a name for this print queue (m=use model name:'psc_2500'*, q=quit) ?:
HP_8720_Printer

Does this PPD file appear to be the correct one (y=yes*, n=no, q=quit) ?
y

Enter a location description for this printer (q=quit) ?
If you want to leave this blank, just press Enter

Enter additional information or notes for this printer (q=quit) ?
HP OfficeJet Pro 8720 Printer

Please enter a name for this fax queue (m=use model name:'psc_2500_fax'*, q=quit) ?
HP_8720_Fax

Enter a location description for this printer (q=quit) ?
If you want to leave this blank, just press Enter

Enter additional information or notes for this printer (q=quit) ?
HP OfficeJet Pro 8720 Fax

Would you like to perform fax header setup (y=yes*, n=no, q=quit) ?
n

Would you like to print a test page (y=yes*, n=no, q=quit) ?
n

Make the printer default

In Ubuntu, open System Settings app
Select Printers in the left pane
Click the gear icon next to "HP_8720_Printer"
Check-mark "Use Printer by Default"

Test Scanning

Launch Simple Scan (aka. "Document Scanner")
Wait for "Searching for Scanners" to complete
You should see the message "Ready to Scan"
Select "HP HP_OfficeJet_Pro_8720" from the drop down
Click the Scan button in the header bar
Comment: Thanks! I didn't notice the check-mark earlier. It's now been clicked. (Did click the up arrow but I haven't been around long enough to vote.) Yeah, forgot about Bonjour... and it is shared from different computers on my network.
Comment: It's working just fine! Scanning and printing perfectly. I installed the GUI and see that I can get to all the options that exist in the drivers for MS Windows. Thanks so much for your help! Just one question - in settings there are now multiple printer and fax entries. The default printer is the one with the network name appended but I also have the original entry as well as an entry with the printer appended to the name of the computer. Same with fax entries. What's with that?
Comment: I'm glad it is working. Please click the grey check-mark next to this answer to accept it. Regarding multiple printer and fax entries, this question may have been answered; you can search for answers to this question on AskUbuntu or ask a new question if you don't find an answer. This printer may be shared from different computer(s) on your network, it's possible the printer was previously configured on your computer with a different name, and/or you are seeing it via Bonjour. You can optionally disable Bonjour on your printer (https://askubuntu.com/a/973710/100356).
Comment: Ubuntu 22 it works for OfficeJet Pro 7720!
Answer: @PJ Singh has given a very full answer in the context of HPLIP. My answer is in the context of of fitting your present modern printing setup into a modern scanning method.
Basically: Nothing of HPLIP is needed. This will come as a shock to all the users who advocate its use. However, things have moved on in 2021.
Install sane-airscan (main page).
Debian packages are here.
I would be very interested in the outputs of scanimage -L and airscan-discover and whether you can now scan.
Comment: HPLIP seems to be working but I'll definitely keep this note for future reference. Thanks for the information.
Answer: I solved my printer problem by turning the printer's power off and then back on.


Swiper 9 Element with Angular 15

Question: I followed the official documentation on:
swiperjs doc
I created a method to configure and initialize the swiper only when I have to show images
this is the HTML:
 <swiper-container #swiperRef init="false">
      <swiper-slide *ngFor="let src of srcPhotos">

      </swiper-slide>
    </swiper-container>

this is the ts:
_initSwiper() {
    const swiperEl: any = document.querySelector('swiper-container');

    const swiperParams = {
      slidesPerView: 1,
      breakpoints: {
        640: {
          slidesPerView: 2,
        },
        1024: {
          slidesPerView: 3,
        },
      },
      on: {
        init() {
          // ...
        },
      },
    };

    // now we need to assign all parameters to Swiper element
    Object.assign(swiperEl, swiperParams);

    // and now initialize it
      swiperEl.initialize();

the swiper is created and works correctly, but in the console, I always get this error:
console error
referring to this event:
swiperEl.initialize();
I can't figure out where the problem is.
I tried to initialize the swiper in various ways but the error that comes out is always the same
Answer: If you're using Angular you can use ViewChild instead of querySelector. Add this to the top of your class:
@ViewChild('swiperRef', { static: true })
protected _swiperRef: ElementRef;

Then replace:
const swiperEl: any = document.querySelector('swiper-container');

with
const swiperEl = this._swiperRef.nativeElement;

Also don't forget to only run _initSwiper() after srcPhotos has values

Swiper 9 Element with Angular 15


XP bar not resetting to zero after a snowball is thrown

Question: I am trying to use the xp bar as a shot reloader where it gives a player a snowball when it reaches 1 xp level. It then stops adding xp points until the player throws the snowball, after which it will be set back to 0 xp. After that, it will load until it reaches 1 xp and give the player another snowball. The command sequence I'm using is:
Command block 1, impulse, activated by redstone circuit:
xp add @p[level=0] 1 points

Command block 2, impulse, always active:
give @p[level=1] snowball

Command block 3, impulse, always active:
xp set @p[nbt={Inventory:[{id:"minecraft:snowball",Count:0b}]}] 0 level

It works until the player throws the snowball. Once the snowball is thrown the xp level won't be set back to zero, meaning the player can't get snowballs again.
Comment: What does "it doesn't work" mean? Error message? Computer explodes? Chickens everywhere? Also, can you please reword the first paragraph? It's a bit hard to understand with its 61 words and three "and".
Comment: Sorry for the confusion, I changed it and hope it's easier to understand now.
Answer: You're testing for a stack size of 0. That can't ever happen. Change it to Count:1b.
Comment: That would make it work but I don't want the bar to reload until the player has thrown the snowball.
Comment: I think I figured out how to make it work, I just need to add a scoreboard objective once the player throws the snowball, the objective resets if the player throws the snowball and only players who don't have that objective have their xp bar refilled.
Comment: You're old solution should work without that, but your new solution is better.


Counting number of zeros per row by Pandas DataFrame?

Question: Given a DataFrame I would like to compute number of zeros per each row. How can I compute it with Pandas?
This is presently what I ve done, this returns indices of zeros
def is_blank(x):
    return x == 0

indexer = train_df.applymap(is_blank)

Answer: Use a boolean comparison which will produce a boolean df, we can then cast this to int, True becomes 1, False becomes 0 and then call count and pass param axis=1 to count row-wise:
In [56]:

df = pd.DataFrame({'a':[1,0,0,1,3], 'b':[0,0,1,0,1], 'c':[0,0,0,0,0]})
df
Out[56]:
   a  b  c
0  1  0  0
1  0  0  0
2  0  1  0
3  1  0  0
4  3  1  0
In [64]:

(df == 0).astype(int).sum(axis=1)
Out[64]:
0    2
1    3
2    2
3    2
4    1
dtype: int64

Breaking the above down:
In [65]:

(df == 0)
Out[65]:
       a      b     c
0  False   True  True
1   True   True  True
2   True  False  True
3  False   True  True
4  False  False  True
In [66]:

(df == 0).astype(int)
Out[66]:
   a  b  c
0  0  1  1
1  1  1  1
2  1  0  1
3  0  1  1
4  0  0  1

EDIT
as pointed out by david the astype to int is unnecessary as the Boolean types will be upcasted to int when calling sum so this simplifies to:
(df == 0).sum(axis=1)

Answer: You can count the zeros per column using the following function of python pandas.
It may help someone who needs to count the particular values per each column
df.isin([0]).sum(axis=1)

Here df is the dataframe and the value which we want to count is 0
Answer: Here is another solution using apply() and value_counts().
df = pd.DataFrame({'a':[1,0,0,1,3], 'b':[0,0,1,0,1], 'c':[0,0,0,0,0]})
df.apply( lambda s : s.value_counts().get(key=0,default=0), axis=1)

Answer: Given the following dataframe df
df = pd.DataFrame({'A': [1, 1, 1, 1, 1, 0, 1, 0, 0, 0],
                     'B': [0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
                        'C': [1, 1, 1, 0, 0, 1, 0, 0, 0, 0],
                            'D': [0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
                                'E': [0, 0, 1, 0, 1, 0, 0, 1, 0, 1]})

[Out]:

   A  B  C  D  E
0  1  0  1  0  0
1  1  0  1  0  0
2  1  0  1  0  1
3  1  0  0  0  0
4  1  1  0  0  1
5  0  0  1  0  0
6  1  0  0  1  0
7  0  0  0  0  1
8  0  0  0  1  0
9  0  1  0  0  1

Apart from the various answers mentioned before, if the requirement is just using Pandas, another option would be using pandas.DataFrame.eq
df['Zero_Count'] = df.eq(0).sum(axis=1)

[Out]:

   A  B  C  D  E  Zero_Count
0  1  0  1  0  0           3
1  1  0  1  0  0           3
2  1  0  1  0  1           2
3  1  0  0  0  0           4
4  1  1  0  0  1           2
5  0  0  1  0  0           4
6  1  0  0  1  0           3
7  0  0  0  0  1           4
8  0  0  0  1  0           4
9  0  1  0  0  1           3

However, one can also do it with numpy using numpy.sum
import numpy as np

df['Zero_Count'] = np.sum(df == 0, axis=1)

[Out]:

   A  B  C  D  E  Zero_Count
0  1  0  1  0  0           3
1  1  0  1  0  0           3
2  1  0  1  0  1           2
3  1  0  0  0  0           4
4  1  1  0  0  1           2
5  0  0  1  0  0           4
6  1  0  0  1  0           3
7  0  0  0  0  1           4
8  0  0  0  1  0           4
9  0  1  0  0  1           3

Or even using numpy.count_nonzero as follows
df['Zero_Count'] = np.count_nonzero(df == 0, axis=1)

[Out]:

   A  B  C  D  E  Zero_Count
0  1  0  1  0  0           3
1  1  0  1  0  0           3
2  1  0  1  0  1           2
3  1  0  0  0  0           4
4  1  1  0  0  1           2
5  0  0  1  0  0           4
6  1  0  0  1  0           3
7  0  0  0  0  1           4
8  0  0  0  1  0           4
9  0  1  0  0  1           3


What is the name of this mechanic that some turn-based games use?

Question: Back in the days some games offered a kind of hot seat multiplayer mode, where both players didn't need to be online/available at the same time to play.
One player would finish his turn whenever, and the other player got a notice to start his turn, not unlike chess by mail.
Is there a certain name for this kind of feature?
Answer: It depends upon whether the players are on the same system or not, and the exact mechanism by which the moves are communicated to each other.
If they are on the same system, then that's likely a hotseat game:

Hotseat or hot seat is a multiplayer mode provided by some turn-based video games, which allows two or more players to play on the same device by taking turns playing the game. The term was first used as a reference to playing a PC game and trading seats with the other player, but the mode dates back to early 1980s arcade games.1 A notable example of games that use this mode is the Heroes of Might and Magic series, which allows up to 8 players to play locally on the same computer.

If they are communicated via email, then you could call it a play-by-mail game:

Play-by-mail games, or play-by-post games, are games, of any type, played through postal mail or email.
Play by mail games are often referred to as PBM games, and play by email is sometimes abbreviated PBeM—as opposed to face to face (FTF) or over the board (OTB) games which are played in person. Another variation on the name is Play-by-Internet (PBI) or Play-by-Web (PBW). In all of these examples, player instructions can be either executed by a human moderator, a computer program, or a combination of the two.

If they are communicated over the web, then that can be called play-by-web:

An increasingly popular format for play-by-email games is play-by-web. As with play-by-email games the players are notified by email when it becomes their turn, but they must then return to the game's website to continue playing what is essentially a browser-based game.
Increasingly, this format is being adopted by social and mobile games, often described using the term "asynchronous multiplayer".


Precision matrix of AR(2) matrix

Question: I am trying to construct the inverse covariance matrix of an AR(2) process of the form $X_t=\theta_1 X_{t-1}+\theta_2 X_{t-2} + \epsilon_t$ with i.i.d. $\epsilon_i$, $\mathbb{E} \epsilon_i =0$, $\mathbb{E}\epsilon_i\epsilon_j=\sigma^2 \delta_{i,j}$. We assume the process to be stationary.
I have already calculated the variance  $Var(X_t)=\frac{(1-\theta_2)\sigma^2}{(1+\theta_2)((1-\theta_2)^2-\theta_1^2)}$ and the autocorrelation coefficients $\rho_1=\frac{\mathbb{E}X_t x_{t-1}}{Var(X_t)}=\frac{\theta_1}{1-\theta_2}$, $\rho_2=\frac{\mathbb{E}X_t x_{t-2}}{Var(X_t)}=\theta_2+\frac{\theta_1^2}{1-\theta_2}$ and $\rho_s=\theta_1 \rho_{s-1}+\theta_2 \rho_{s-2}$ for $s>2$.
How do I now proceed to construct the inverse covariance matrix? I tried to calculate it analytically but it did not work out.
EDIT: For fix $T$ I am looking for the inverse matrix of the covariance matrix $\Phi$ with entries $\Phi_{ij}=Cov(X_i,X_j)$, $i, j = 1,\dots,T$. The entries of this covariance matrix are already given by the autocorrelation coefficients above since the process is assumed to be stationary.
Any help would be very appreciated!
Comment: Can you please define the covariance matrix you are looking for? I'm not quite sure what variables make up its dimensions from your description. Also, why do you believe that inverse covariance would have a closed-form analytic expression?
Comment: @AleksejsFomins I have specified the covariance matrix in my question. I know that the inverse covariance matrix has a simple form since I have found it in a book but I have no idea how to calculate it.
Comment: Thanks, I'll think about it for a bit
Comment: @AleksejsFomins There are certain conditions for $\theta_1$ and $\theta_2$ under which the process is stationary and I think that stationarity in particular implies that $\mathbb{E} X_t^2$ does not depend on $t$. I basically followed the calculations given under the following link: https://www.uni-kassel.de/fb07/fileadmin/datas/fb07/5-Institute/IVWL/Kosfeld/lehre/zeitreihen/AR-Modelle.pdf Unfortunately, the source is German but they get the same result like I have.
Comment: No worries, I think I get it now. You wait until the probability distribution of $X_t$ is the same as for $X_{t-1}$. And you need the covariance for some $X_t$ that is not at the start of the experiment, but somewhere far in the future when initial conditions have been long forgotten. Would it be difficult for you to present your proof for variances and covariances if it is not too long? For now, I will continue by assuming that your equations for the correlation matrix are correct
Answer: Ok, so this is not the full solution, but I will present how to get the explicit form for $\Phi$, maybe somebody figures out how to invert it. So, according to the above notation, $\Phi_{ij} = \rho_{|i-j|}$, where $\rho_0 = 1$ and $\rho_1$ and $\rho_2$ are specified in the question
We will now solve the recurrence relation $\rho_s = \theta_1 \rho_{s-1} + \theta_2 \rho_{s-2}$ with help of generating functions
Define $G(x) = \sum_{i=1}^{\infty}\rho_ix^i$, then use recurrence relation
$G(x)
= \sum_{i=1}^{\infty}\rho_{i+1} x^i
= \rho_1 + x \rho_2 + \sum_{i=2}^{\infty}x^i \theta_1\rho_{i} + \sum_{i=2}^{\infty}x^i \theta_2 \rho_{i-1}
= \rho_1 + x(\rho_2-\theta_1\rho_1) + x \theta_1 G(x) + x^2 \theta_2 G(x)
$
Let $c_1 = \rho_2-\theta_1\rho_1 = \theta_2$. Solving for $G(x)$, we get
$$G(x)
= \frac{\rho_1 + x c_1}{1 - \theta_1x-\theta_2x^2}
= \frac{\rho_1 + x c_1}{-\theta_2 (x-k_1)(x-k_2)}
= \frac{\rho_1 + x c_1}{\theta_2 (k_1 - k_2)}(\frac{1}{x-k_2} - \frac{1}{x-k_1})
= \frac{\rho_1 + x c_1}{\theta_2 (k_1 - k_2)}(\frac{1}{k_1}\frac{1}{1-\frac{x}{k_1}} -\frac{1}{k_2}\frac{1}{1-\frac{x}{k_2}})
$$
Here we have factored the quadratic equation, resulting in solutions $k_{1,2} = \frac{1}{2 \theta_2}(-\theta_1 \pm \sqrt{\theta_1^2 + 4 \theta_2})$
Now we substitute the series $\frac{1}{1-x}=1+x+x^2+...$
$$G(x)
= \frac{\rho_1 + x c_1}{\theta_2 (k_1 - k_2)} (\frac{1}{k_1}\sum_{i=0}^{\infty} \frac{x^i}{k_1^i} - \frac{1}{k_2}\sum_{i=0}^{\infty} \frac{x^i}{k_2^i})
= (\rho_1 + c_1 x) \sum_{i=0}^{\infty}a_ix^i
$$
Where
$$a_i = \frac{1}{\theta_2(k_1-k_2)}(\frac{1}{k_1^{i+1}} - \frac{1}{k_2^{i+1}})$$
Finally,
$$\rho_{i+1} = \rho_1 a_i + c_1 a_{i-1} = \rho_1 a_i + \theta_2 a_{i-1}$$
So the next step is to try to simplify the explicit form of $\Phi_{ij}$ to see if it is somehow invertible. I'm sure there probably is a faster way to do this, if one somehow exploits some known symmetry of the matrix, but that's beyond me atm

Precision matrix of AR(2) matrix


Android trigger notification code even if the user only clicks app button

Question: So here is my code that sets a notification that the user is bieng called via the zoom service. However if the user does not click the notification and instead just hits the app icon directly the extras are not captured correctly. I am a little lost on how to extract the extras from this pending intent in on resume.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); //build the new notification
                                mBuilder.setSmallIcon(R.drawable.ic_launcher);
                                mBuilder.setContentTitle(getString(R.string.incoming_zoom_meeting_title));
                                mBuilder.setContentText(String.format(getString(R.string.incoming_zoom_meeting_message), pushObject.getZoomCall().get(CIConstants.ZOOM_TITLE)));
                                mBuilder.setSound(Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.constellation)); //This sets the sound to play
<code>                            Intent resultIntent = new Intent(this, MainActivity.class); //set notification click behavior
                            resultIntent.putExtra(CIConstants.ZOOM_MEETING_ID, pushObject.getZoomCall().getString(CIConstants.ZOOM_MEETING_ID).trim());
                            resultIntent.putExtra(CIConstants.ZOOM_USER_ID,pushObject.getZoomCall().get(CIConstants.ZOOM_TITLE).toString());

                            PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                            mBuilder.setContentIntent(resultPendingIntent);

                            int mNotificationId = 001;
                            NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                            mNotifyMgr.notify(mNotificationId, mBuilder.build());
</code>
This is then retrived in the main activity via.
<code>    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        mMeetingNumber = extras != null ? extras.get(CIConstants.ZOOM_MEETING_ID).toString() : null;
        mMeetingCallerName = extras != null ? extras.get(CIConstants.ZOOM_USER_ID).toString() : null;
        //if there is a meeting id in the intent
        mZoomCallIncoming = mMeetingNumber != null && !mMeetingNumber.isEmpty();
    }
</code>
Any help is really appreciated =D.
Answer: In case anyone stumbles on this the easiest way to do this was to go ahead and just put it into a static variable to be retrieved later in the onResume in case the user does not click the notification it will be populated in onResume anyway.
<code>    Intent i = getIntent();

    String meetingId = i.getStringExtra(CIConstants.ZOOM_MEETING_ID_KEY);
    String userId = i.getStringExtra(CIConstants.ZOOM_USER_ID_KEY);
    if (meetingId != null && !meetingId.isEmpty()) {
        CIConstants.ZOOM_MEETING_ID = meetingId;
        CIConstants.ZOOM_CALL_INCOMING = true;
        i.putExtra(CIConstants.ZOOM_MEETING_ID_KEY, "");
        i.putExtra(CIConstants.ZOOM_USER_ID_KEY, "");
    }
    if (userId != null && !userId.isEmpty())
        CIConstants.ZOOM_USER_ID = userId;

    if (CIConstants.ZOOM_CALL_INCOMING) {
        if(!CIConstants.ZOOM_CALL_NOTIFICATION_SOUND_PLAYING) {
            NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setSound(Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.constellation));
            manager.notify("", CIUtility.NOTIFICATION_ZOOM, builder.build());
        }

        createZoomCallDialogue(CIConstants.ZOOM_MEETING_ID, CIConstants.ZOOM_USER_ID);
        CIConstants.ZOOM_CALL_INCOMING  = false; //reset the zoom uri so that it is not called again when activity is resumed from zoom
        CIConstants.ZOOM_CALL_NOTIFICATION_SOUND_PLAYING = false;
        CIConstants.ZOOM_MEETING_ID = null;
        CIConstants.ZOOM_USER_ID = null;
    }
</code>


How to check if there is an active session or not in appwrite?

Question: Like firebase we can check if there is an active session by FirebaseUser. How can we check on start of my MainActivity that if a user is logged in or not. I am working with java, i have not found any proper solution. Appwrite says to use get() but i am not able to understand how to use it. Any help
Comment: 12:02:56.031  W  io.appwrite.exceptions.AppwriteException: User (role: guests) missing scope (account)
12:02:56.032  W   at io.appwrite.Client$awaitResponse$2$1.onResponse(Client.kt:490)
12:02:56.032  W   at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
12:02:56.032  W   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)
12:02:56.032  W   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)
12:02:56.032  W   at java.lang.Thread.run(Thread.java:1012)
12:02:56.032  I  No sessions Found
Comment: above was the error on appwrite
Answer: As you mentioned, in Appwrite, the typical approach is to call account.get() and if it executes successfully, there is an active session and you can send the user to the home page. If account.get() throws an exception, there is no active session so you should send the user to the log in page.
Related discussion: https://github.com/appwrite/appwrite/discussions/3938#discussioncomment-3746725
Answer: Let me give you a short example ;)
Future<User?> getUserIfExists() async {
  try {
    final user = await this.account.get();
    return user;
  } on AppwriteException catch (e) {
    if (e.code != 401 || e.type != 'general_unauthorized_scope') rethrow;
  }
  return null;
}

So it just catches the Exception if was thrown only because of a non existing session - otherwise you could not tell if it was something else what caused the exception like "no inet connection"
Hope this helps!


How to Calculate Maximum Amps for a Cable over a certain Distance?

Question: Different calculators all seem to give me different results. And What am I supposed to put for Voltage for the standard 240 V North American Power? in NA power one wire is 240 volts relative to the second wire, but only 120 volts relative to neutral.
I have 4-4-4 Aluminum Underground Direct Burial with an Ampacity of 125 amps.
I want to use it to move standard 240 V power about 150-180 feet away.
I cannot figure out the maximum amperage.
Answer: The limit's ampacity, not voltage drop
In your case, voltage drop is insigificant for 240V power over a mere 180' of distance, but you are limited to a 70A breaker (65A actual ampacity) on 4AWG Al by the NEC Table 310.16 ampacity chart, assuming your terminations are rated for 75°C.  (The 125A number you gave for the cable is likely only for electrical utility use.)
Comment: I think you read the copper number? It looks like it is 55-65 in the chart to me.
Comment: How do we know that 180' is insignificant? These table does not list the distance I can draw these amps over, which from my understanding is an important aspect of the calcuilator.
Comment: @Jonathon -- the rule of thumb is that if the distance is less than the voltage, you don't have to worry about the voltage drop.  The 55A number you're seeing is for 60degC terminations, by the way
Comment: "if the distance is less than the voltage" or less than half the voltage? Neat rule of thumb btw!
Comment: @P2000 "if the distance is less than the voltage" -- IIRC, Harper gets the credit for introducing me to it
Answer: The only time you're allowed to use 3-wire for 120/240V is on the service entrance -- that's from the utility drop, through your electric meter, to the very first disconnect switch or breaker.
Beyond that, you must assign 1 wire to safety ground.  With 4-4-4, that leaves only 2 wires, so you'll either have 120V only, or 240V only (no neutral).

If you run in 240v only mode, then at wire redline (65A) you'll have 4.5% voltage drop.  That's "not great, not terrible" - I wouldn't sweat it.  In the US you are not required to sweat it.
In Canada, you are required to limit to 3.75% voltage drop (literally: 3% drop at 80% ampacity, but, same thing). That calls for a 55A circuit (3% happens at 44A).

If you run in 120V mode, then you'll be at the horns of a decision.  You can run 65A of draw at an alarming 9% voltage drop.... or you can run proportionally less amperage at proportionally less voltage drop.
Canada rules would limit the circuit to 25A. Ouch.
Comment: @Jonathon Grounds, for up to 100A #6Al should do it.  For up to 200A #4Al.
Comment: @Jonathon by Canadian Code.    Because *voltage drop* is decided by current and resistance only (VD = C x R) and is absolute: it *does not know* what circuit voltage is.   If you have 12V voltage drop on a 120V circuit, that is 10% drop.  If you have 12V voltage drop on a 240V circuit, it is only 5% drop.
Comment: Ya, I will have to add a wire for ground. Thanks for all the information. Do you know what the ground wire would have to be? It can be a smaller gauge than the main wire, right?
Comment: I have been thinking over this, because I am still confused at the theory behind this and how the power knows it is 240v when the individual separate wires are not 240 V.

Are you saying: If I were to add a ground, and sent standard residential 240v power over these wires. By code I could use a total of 55A in 240V power, but only ever use a total of 25A per per hot wire in 120V mode (totaling to 50A)?


Depth of 4X4 Fence Post?

Question: I would like to repair a  wooden fence, in Florida, similar to the one in the photo below:
Is there a rule of thumb (ratio) for the amount of post exposed to the amount buried underground?
Home Depot  has the  option for 8,10 & 12 foot posts.
Comment: Jim Stewart's answer is a general guideline - I can tell you 2 feet under is difficult to remove.. If it were me - I would not use a wood fence in Florida unless I liked replacing it every 4 years. PVC based will last much longer - like 20 years longer and still look really good - the wood fence will rot due to the high humidity and high temperature. Also that fence in the picture is touching the ground - it will draw that moisture and rot .. if using wood keep it off the ground a couple inches.
Comment: @Ken I agree wood is not a good choice: I neglected to mention that the fence was erected in the late eighties and that two recent hurricanes have snapped the posts
Comment: yes as an added advantage to hollow PVC posts - you can pour concrete down the middle (I did) posts have been fine through the hurricanes (100MPH plus) . Fencing on the other hand replaced it once and repaired it another time.
Comment: do it however you want, but anything less than "all the way down" is insufficient.
Answer: I always have used 2' underground so use an 8' post for a 6' fence. I don't know if this would be adequate for a taller fence, but it would probably do at least for an 8' fence.
Once while replacing termite eaten cedar 4x4" posts I encountered a soft limestone 14" or so below ground. I dug 4" or 6" deep into the limestone with a steel digging bar and stopped. I put in the post and then cut 6" or 4" off the top.
Comment: When we moved into our house in Dallas 39 years ago some of the cedar 4x4 posts in concrete were already damaged by termites. I replaced some of them with PT 4x4s 8' long. I got a heavy steel digging bar with a spade on one end, and a tamper on the other, and used it to break up the concrete which I removed with post hole diggers. I filled the holes around the new posts with soil and tamped. I didn't think concrete was necessary with 4x4s in Dallas.
Comment: I decided not to use concrete around the 4x4" posts I put in because I thought that eventually I would replace the fence entirely and didn't want to deal with getting concrete out of the ground if I wanted to use the same holes for the posts. In most 'lower end' professional jobs I see they cut the posts off at the ground and put the new posts in different locations. But I was replacing the damaged posts and re-nailing the panels. Also, I wanted to be minimalist--use the least energy consuming materials and procedures that would produce an acceptable result.
Comment: What region of the world?  Did you anchor the post with cement?
Comment: You're going to want a 3' hole for a 8' fence in Florida especially because of the high winds you are likely to see from storms and the occasional hurricane/tropical storm.  Your area has special roof requirements for high winds, so you don't want to skimp on fences either.
Comment: @JPhi1618 High winds in FL will not affect the posts as much as the fencing itself. I have posts that have had 100MPH hurricanes and the only issue I have ever had was with the fencing itself. My posts are hollow - 8' - PVC buried (@18 inches) - filled in with about 1' concrete. Posts have made it through with no problems - fencing on the other hand I have had that replaced/repaired twice. After a certain point a big flat fence catching the wind will either snap his 4 x 4's or bend the posts - even steel posts can bend. I have seen large signs with steel posts bent over backwards.
Answer: General rule of thumb is 1/3 the post should be below grade.

4' fence = 2' in the ground
6' fence = 3' in the ground

But it's just a rule of thumb. If you have a 6' fence with an open panel design (ie, not solid) then 2' in the ground is likely just fine.
Comment: @Ken That's not how you calculate it. The 1/3 is based on the *total* height of the post--not just the part you see. 9' post with 6' showing (2/3) will have 3' in the ground (1/3)
Comment: You should proof read your answer - seriously 6' x  1/3 = 2 NOT 3.
and 4' x 1/3 = 16 inches.
Comment: Actually, after some googling, another way to phrase the rule of thumb is: you want 1/3 - to 1/2 the height above ground to be in the ground. So yea, in general, if you have a 4' fence, you want 16" - 2' in the ground. 6' fence? 2'-3' in the ground. (1/2 the height above ground = 1/3 the total height of the post)
Answer: You also have the option if pouring concrete footer with galvanized bolts, then use a galvanized base to keep the posts up off the ground. When a post needs to be replaced, unbolt it and bolt another one in. Code in Kentucky requires this method for porch posts if they are mounted to a concrete slab.
Comment: Please consider posting a photo / link to a photo to clarify
Answer: This also depends on if you have a frost line.  If you do, as in NJ, then your 6' post needs 3' underground for a total of 9'.  Trim the excess from the top to level the post.  Also, no need for concrete.  It just hastens rot due to trapped water.  Gravel allows drainage and tight fit.
The spruce rails will rot (if untreated) faster than the posts or pickets.
Answer: Re-wooden fence posts. If the bottom of the posts  have rotted in the concrete base the rotted wood can be removed by drilling or other means and the holes reused saving a lot of effort and time and expense. I have used this method.

Depth of 4X4 Fence Post?


Get hardware id with inno setup script to prevent piracy

Question: I just finished my program,  now I want to build a setup with Inno-setup that gets the hardware id and and stores it into a file in the CD so that the program can be installed in only one computer with only one license. Unfortunately i am not good at all at Inno-setup scripting language. Anything you guys can do to help me will do, anything, even small hints,
Please help i am out of options right now.
Comment: What's the hardware-id?
Answer:
I want to build a setup with Innosetup that gets the hardware id and and stores it into a file in the CD so that the program can be installed in only one computer with only one license.

You want to create a unique Installer and CD for every client?
Wow, that's a lot of work. It only makes sense for a really small business.
Anyway, in regard to getting a hardware-id:

There is no function in InnoSetup to get a "hardware id".
You probably mean some kind of identifier, like a hard-disk or motherboard serial number, right? You could decide to fetch some serial numbers or identifiers by querying the WMI.

But wait? You compile Innosetup on the developer machine, right?
The only hardware-ids you could possibly get at that time are IDs from your own developer machine. How do you get the hardware-id of your client, which is later trying to install your software from CD?

The whole approach doesn't make much sense and is flawed.
In general, doing this kind of protection in the installer is kind of useless.
Please handle your protection in the application, not in the setup.
You might use one of the following approaches: "API-Key" or "license-code" or "license file" or "hardware-dongle".
In other words: its always the same installer on multiple CDs, but the additional separate license code makes the difference - not during, but after the installation. The user simply enters the key or loads the license-file into the application and gets "Application registered to XY".
Comment: First of all all of this things that are written here i have thought months ahead so you guys haven't said anything new.

Anyway i managed to solve the problem using batch files and the  `getmac` command. The logic behind is very simple and very far from not working.