Where did I go wrong? Integration by parts

Question: So I was looking at the integral of $\int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx}$ and I got the following using the DI method (for those who don't know it search DI bprp on youtube):
choosing f(x) for D and $\frac{d}{dx}(\frac{df(x)}{dx})$ for I we get on the first row $\frac{df(x)}{dx}$ for both D and I, and continuing another row (and switching the sign from + to -) we get $\frac{d}{dx}(\frac{df(x)}{dx})$ for D and f(x) for I, and by using the rules of DI method we would get:
$\int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx} = f(x)\cdot\frac{df(x)}{dx} -\int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx}$
by adding $\int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx}$ to both sides we get:
$2\int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx} = f(x)\cdot\frac{df(x)}{dx}$ and so:
$\int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx} = \frac{f(x)\cdot\frac{df(x)}{dx}}{2}$
but this is clearly wrong as even just looking at $f(x)=x^2 -> f'(x)=2x -> f''(x)=2$ we can see that the "formula" I got is wrong as on the integral side we get $2x^3/3$ and on the right-hand side we get $x^3$.
So I thought to myself maybe I used the DI method wrong and I tried normal I.B.P and so I wrote:
(1) $\int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx} = f(x)\cdot\frac{df(x)}{dx} - \int{\frac{df(x)}{dx}\cdot\frac{df(x)}{dx}dx}$
and if we look at that last integral and integrate it by parts we would get:
$\int{\frac{df(x)}{dx}\cdot\frac{df(x)}{dx}dx} = f(x)\cdot\frac{df(x)}{dx} - \int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx}$
plugging this back into (1) we get:
$\int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx} = f(x)\cdot\frac{df(x)}{dx} - \int{\frac{df(x)}{dx}\cdot\frac{df(x)}{dx}dx} = f(x)\cdot\frac{df(x)}{dx} - (f(x)\cdot\frac{df(x)}{dx} - \int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx}) = f(x)\cdot\frac{df(x)}{dx} - f(x)\cdot\frac{df(x)}{dx} - \int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx}$
So overall:
$2\int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx}=0 -> \int{f(x)\cdot\frac{d}{dx}(\frac{df(x)}{dx})dx}=0$
Which is even more wrong ??? please tell me where I went wrong with both methods??
Answer: With the DI method, you will get
$$\begin{array}{ccc}
+&f(x)&f^{\prime\prime}(x)\\
-&f^\prime(x)&f^{\prime}(x)\\
+&f^{\prime\prime}(x)&f(x)
\end{array}$$
And so
$$\int f(x)f^{\prime\prime}(x)\,\mathrm dx=f(x)f^\prime(x)-f^\prime(x)f(x)+\int f(x)f^{\prime\prime}(x)$$
which is true, but an useless equation. You have made sign errors in your attempt.
If you carefully go through your second solution as well, you will notice that you took the wrong sign in the last equation and so instead of the integral cancelling, it instead added up to give something like $2\int(\cdots)=0$.
Hope this helps. :)
Comment: omg I'm so stupid thanks!
Answer: Here's my DI table: $$ \array { & \text D & & \text I \\ & --- & & --- \\ + & f ( x ) & & f ' ' ( x ) \\ & & \searrow \\ - & f ' ( x ) & & f ' ( x ) \\ & & \searrow \\ + & f ' ' ( x ) & & f ( x ) } $$
So the top row is $ + \int f ( x ) \, f ' ' ( x ) \, \mathrm d x $, which is the integral that we're evaluating.  Then next we follow the first arrow to get $ + f ( x ) \, f ' ( x ) $.  Then we follow the next arrow to get $ - f ' ( x ) \, f ( x ) $.  There are no more arrows, so we finish with $ + \int f ' ' ( x ) \, f ( x ) \, \mathrm d x $.
Conclusion: $$ \int f ( x ) \, f ' ' ( x ) \, \mathrm d x = f ( x ) \, f ' ( x ) - f ' ( x ) \, f ( x ) + \int f ' ' ( x ) \, f ( x ) \, \mathrm d x \text , $$ which is true but useless.
When you did this, it seems like you forgot to include the term from the second arrow.
When you did it the non-DI way, you neglected to distribute a minus sign.  The last term should have been $ - - = + $, but you left it $ - $.
Comment: thanks! I don't know how I missed that


Filter file lists to get specific type files

Question: I got the following code to list files in videos library:
<code>    var files = await Windows.Storage.KnownFolders.VideosLibrary.GetFilesAsync();
    foreach (StorageFile file in files)
    {
        textBox1.Text += file.Path + "\n";
    }
</code>
Can I filter the files to get only specific file type files such as mp4 files only?
I know I can filter by using "if condition" in the foreach loop - I believe there's better solution and that's why I ask here.
Thanks
Answer: <code>var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".mp4" });
queryOptions.FolderDepth = FolderDepth.Deep;
var query = Windows.Storage.KnownFolders.VideosLibrary.CreateFileQueryWithOptions(queryOptions);
var files = await query.GetFilesAsync();
</code>
Answer: Yes you can by calling the overloaded constructor and using CommonFileQuery.
Comment: Can u give me full example?


Can I share "C" wire on two thermostats?

Question: I am wiring a second thermostat right next to the original one. The new needs a C wire. Can I share it from the old one?
Old: 8 wires, used to run heat pump (w/ heating and AC) and backup oil. Now only runs AC from heat pump on occasional summer day.
New: Has 2 wires run to it. Controls instant on hot water heater for radiant system.
The new thermostat says, "WILL NOT OPERATE WITHOUT WIRE TO 'C'". Can I take the C wire from the existing thermostat and bridge it to the new thermostat? Can two thermostats share this C wire?
According to Can I piggyback a thermostat with a C Wire hookup on a furnace?  I think the answer is "Yes", but when I try it, the new thermostat does not have power.
Comment: The `R` wire going to the new thermostat, does it come from the same place as the `C` wire on the old thermostat? Or is there an `R` wire from the heat pump to thermostat 1, and an `R` wire from the boiler to thermostat 2?
Answer: You can only share the C wire, if you're also sharing the R wire.  If the R wires come from different equipment, the C wires must also come from the different equipment.
Comment: Is there any reason I shouldn't also share the `R` wires? Based on https://diy.stackexchange.com/questions/10482/how-can-i-add-a-c-wire-to-my-thermostat I think so, but I wouldn't want one system to start interacting with the other. Just share power.
Comment: You should not share the control wiring between separate systems.
Comment: According to graphics in the link I gave above, the loop only closes when `W` is triggered. It seems like if `C` and `R` were each wired to two systems, the circuits would still be incomplete until `W` triggered, and then only the circuit with the `W` would be active...
Comment: @mankoff The loop from `R` to `C` does not rely on `W` at all. That's why those two are used to supply constant power to the thermostat.


Row Operations and Eigenvalues of $\begin{bmatrix} 2 & 0 \\ 2 & 3 \end{bmatrix}$ and Other Matrices.

Question:
Let the matrix $A$ be given by:
  \begin{bmatrix}
    2 & 0 \\
    2 & 3
\end{bmatrix}
  And let the matrices $B$, $C$, and $D$ be given by row operations: $R_2 \rightarrow R_2-R_1$, swap rows, and $R_2 \rightarrow -2R_2$, respectively. What are the eigenvalues of $A$,$B$, $C$, and $D$

I sorta guessed the rows and columns, for the transformation matrices. Is there a systematic way of doing this? Also can I compute these eigenvalues without evaluating $A$,$B$, $C$, and $D$?
Answer: We have $\sigma(A) = \{2,3\}$ because the matrix is lower-triangular.
We have $B = \begin{bmatrix} 0 & 0 \\ 0 & 3\end{bmatrix}$ so $\sigma(B) = \{0,3\}$ because the matrix is diagonal.
We have $C = \begin{bmatrix} 2 & 3 \\ 2 & 0\end{bmatrix}$ so the characteristic polynomial is $x^2-2x-6$ so $\sigma(C) = \{1-\sqrt7, 1+\sqrt7\}$.
We have $D = \begin{bmatrix} 2 & 0 \\ -4 & -6\end{bmatrix}$ so $\sigma(D) = \{2,-6\}$ because the matrix is lower-triangular.
I don't know of an easy way to get the eigenvalues without calculating the matrices.


Install hooks to the ceiling of balcony

Question: Long story short: Live in an apartment building, top floor. Balcony overrun with pigeons. Literally a quarter inch of bird feces covering the floor.
I bought a bird net and want to hang it up. Unfortunately, I am not sure how I can attach it to the ceiling of the balcony.
Cross section looks like this:
<code> __
|
|_|
</code>
The gap is where I want to put the net, with the hooks of some sort attached to the ceiling. My initial idea was to use eyelet screws; however, I've tried the following to no avail:

Drill(hammer drill) with masonry and metal drill bits of various
sizes. Can't even make a dent.
Hammer in nail (RIP nail)
Tape (Used
double-sided, cause that was the strongest I had. Still peeled off)

My next attempt might be to buy regular adhesive hooks (from a dollar store) and then use cement glue or sorts to try and keep them on the ceiling. If anyone has any advice on what I can do to attach the net to the ceiling (that doesn't require a big investment), please let me know.
Thank you
Answer: Sounds like concrete?
A standard impact hammer drill will generally struggle and definitely not with HSS drill bits.
You would need a rotary hammer drill with SDS masonry bit.
Then have various fastener options.
Nails would be extremely difficult, you need masonry nails, but masonry nails from a nail gun can work easily into concrete.
If not concrete one of the only other things as tough is compressed cement sheeting.
Photo of the surface might help.
Also double sided tape does not work well on certain surfaces but quality is also important. Something like 3M VHB is insanely strong.
Comment: You are absolutely right! Mounting gorilla tape combined with dollar store plastic hooks is more than enough to get the job done! The previous time I used double sided tape just didn't work on the surface and wasn't meant for exterior use.
Answer: If buying/renting a rotary hammer isn't that interesting, you could get 3 sticks of 2x4. Roll the netting in the one that's as wide as your balcony, and then put a stick at each end to jam it in place. If your cut isn't perfect for a tight-tight friction fit, then use wood shims to make it tight. (So, shims under the post, and shims jamming the top beam in place.) If you feel you need to secure it more, put an L-bracket at the inside of each corner.
(Additional benefit: when you move, nobody will be yelling at you about the holes you drilled...)

Install hooks to the ceiling of balcony


Measure how long a rendered frame takes to arrive on a client from the cloud

Question: Say I am running a game in the cloud and I am playing that game on my client (the game is being streamed from the cloud to the client), be it a laptop, phone or calculator.
How can I work out how long a frame (of the game being played) takes to arrive at the client?
Comment: This seems to have a couple of problems. a) It's not entirely clear whether you're the developer or just a player of the game (in the latter case, this is clearly off-topic, as this site is about computer graphics *programming* and *research*). b) If you are the developer this doesn't seem to be actually about graphics but more about the network code of your game. In that case, you might want to try [GameDev.SE](http://gamedev.stackexchange.com/) or [so] but be sure to read their respective help centres to make sure your question is of high-quality and on-topic.
Answer: Try putting a timestamp over some key frames as the last step on your render pipeline. Then compare it to the local systems time. If both clocks are correct you should get a delay in ms (using unix rime-stamps).
Another idea to measure the round-trip-delay (might be important for UX reasons):
input to server,
server render,
result from to server on your screen
is to have a bot give an input than measure the time till the result is back
Comment: How would I go about accessing the key frames? I'm not really sure where to start. The game would be streamed from the cloud to a client. Thanks
Comment: maybe try to record it and than search them by hand. I know this is far away from any kind of automated test or even realtime feedback, but it seemed to be the rather uncomplicated


Bash declare associative array through function gives non-associative array

Question: I tried to declare an associative array through a function, and I found that the associative array becomes a plain array. The test code goes like this:
bash-5.0$ cat test.sh
#!/bin/bash

createArr(){ declare -A "$1"; }

# create array using `createArr'
name=array1
createArr $name
array1[1]=1
echo "${!array1[@]}"
array1[a]=1
echo "${!array1[@]}"
declare -p array1

# create array directly
name=array2
declare -A $name
array2[1]=1
echo "${!array2[@]}"
array2[a]=1
echo "${!array2[@]}"
declare -p array2

And executing the code gives the following result:
bash-5.0$ ./test.sh
1
0 1
declare -a array1=([0]="1" [1]="1")
1
1 a
declare -A array2=([1]="1" [a]="1" )

I'd like to know why the results are different, thanks! (My bash version is 5.0.11)
Answer: help declare says

When used in a function, declare makes NAMEs local, as with the local command.

That means outside of createArr, array1 is not declared. And an assignment like array1[1]=1 where array1 is unset, implies that array1 is a regular, indexed array.
Using the -g flag in your function fixes this though
createArr() { declare -gA "$1"; }


Business application - pessimistic concurrency using messaging

Question: We are using messaging in a project of ours to implement pessimistic concurrency. This means that if messaging goes down (channel goes down), concurrency goes down.

Is this done in other business applications?
Do you close the application (log out the user) if messaging goes down?

I'm thinking more of combining the optimistic and pessimistic concurrency. Then if pessimistic concurrency goes down, there's still a backup optimistic concurrency...
thx, Lieven Cardoen
Answer: As usual, I think the answer depends on the nature of the business application that you are building.  What are the SLAs for your application?  How mission critical is it?
If your messaging infrastructure faults, does the application continue to function aside from the lock service?  If so, then you probably have an obligation to make sure your concurrency control mechanism isn't the single point of failure.
Furthermore, the topic of achieving a truly distributed, fault-tolerant pessimistic locking mechanism requires one to address the problem of consensus.  Most pessimistic locking algorithms rely on there being a single, serialized authority that can respond to requests for locks (i.e. there's a "lock" table or perhaps there's a singleton lock server).
Such a design has single point of failure written all over it.  To answer your first question--Yes, I've seen business applications use messaging to provide pessimistic locking.  However, fully solving the fault tolerance problem seems like overkill for most business applications I've encountered.
Optimistic concurrency control does not have this problem by its nature which is why it's generally preferred in distributed, fault-tolerant applications.  However, I realize that business requirements frequently win out over ease-of-implementation.
If the topic interests you, Google has published an article on their Chubby Lock Service which leverages the Paxos consensus protocol.


How to pass an argument in the run method while doing multi-Threading in Java

Question: I was learning to use multi-threading by using the Runnable interface.
This is how i am trying to do it
public class ExampleClass implements Runnable {

public static void main(String[] args)
    {
           Thread object = new Thread(new ExampleClass());
           object.start();
    }
public void run(String[] args){
System.out.println("ExampleClass running");
   }
}

However this doesn't work because my assumption is that the start method calls run() however since i have that method as run(String) in my example above, it doesn't work. The program compiles but then just exits.
Please can you advise what am I doing wrong?
Comment: The program compiles? It doesn't say that it's missing a no-arg `run()` method?
Comment: It's really weird that it compiles for you. I'm getting this error while trying to compile it: com.company.ExampleClass is not abstract and does not override abstract method run() in java.lang.Runnable
Comment: @Amongalen - you need to add unimplemented methods, you should see the suggestion next to the compilation error
Answer: You can pass the arguments in the constructor of ExampleClass.
public class ExampleClass implements Runnable {

    private String[] args;

    public ExampleClass(String[] args) {
        this.args = args;
    }

    public static void main(String[] args) {
        Thread object = new Thread(new ExampleClass(args));
        object.start();
    }

    @Override
    public void run() {
        System.out.println("ExampleClass running, args: " + Arrays.toString(args));
    }
}


How to perform an upward wall slide?

Question: Every once in a while, when trying to wall jump, Meat Boy does an upward wall-slide instead of another jump. Is that a kind of "bug" or is it possible to perform an upward slide while sliding?
I guess it depends on the right timing you press A while approaching the wall, but I'm not sure.
And no, I don't mean the classic wall sliding that you get from the vertical momemtum of a normal jump.
Does anybody can explain this?
Answer: It is a known glitch.
From http://smb.thecybershadow.net/Bugs_and_problems

Inability to wall jump under certain circumstances
As shown in this video, you can sometimes end up wall jumping directly up the wall you're currently sliding on. This also happens when at the bottom of a vertical conveyor belt pushing you downwards.

The video in question is this one:

As for how to reproduce the glitch, it seems it's not consistent and is related to pressing jump in a particular frame just before touching the wall, as you described
Comment: Well, that's unfortunate...

How to perform an upward wall slide?


How can I protect my CIFS attached shares from accidential deletion like 'rm -rf /'?

Question: I have a Synology NAS and I have 2 folders from it attached in /mnt/nas-XXX via /etc/fstab like so:
//192.168.178.100/BackUps /mnt/nas-backups cifs uid=0,credentials=/home/user/.smb,iocharset=utf8,vers=3.0,noperm    0 0

How can I protect them from accidential deletion like rm -rf / or others.
Comment: **Backup** everything that you cannot afford to lose.
Comment: Well, yeah, I do that. I just want some extra protection.
Comment: I have an alias for 'remove',  `alias rm='rm -i'` which makes it ask for confirmation. The alias can be escaped by `\rm ..`.
Comment: Do as much as possible with your standard user ID. Use sudo only when absolutely necessary and double-check before launching sudo commands.
Answer: You need to be always aware of what you are typing, Although its not a scalable solution but it can help you To protect them from accidental deletion, You can add immutable attribute to files.
chattr +i path_to_files
Comment: Yea, that's one way, but I was thinking more along the line of applying something like that to `/mnt/nas-backups` no matter what I would do, `/mnt/nas-backups` would never be deleted unless I explicitly say YES or something.

I guess you can: https://www.tecmint.com/chattr-command-examples/ not just files, but folders too. But being immutable... does that mean nothing can be done to `/mnt/nas-backups`
Comment: If you set immutable on dirextory then you can not delete or modify the directory and its files , So, what else do you want?


Proper display converted SQL resultset into JSON

Question: I'm trying to implement java method for web service that should retrieve data from table and return the result in json format. For this I use json_agg() function that converts query result into json which I want to display, but it displays in wrong format so far. Here is the method itself:
public String GetRowsFromTable() throws SQLException {

    Connection connection = null;
    String result = "";
    try {
        connection = Connection.getConnection();
        PreparedStatement prepStmt = conn.prepareStatement("SELECT json_agg(table1) FROM table");
        ResultSet rs = prepStmt.executeQuery();
        result += rs;
        System.out.println(rs);
    } catch (SQLException sqlex) {
        sqlex.printStackTrace();
    } finally {
        connection.close();
    }

    return result;
}

The console displays the following result:
org.postgresql.jdbc.PgResultSet@5179f609

Any help would be appreciated.
Comment: also that is the default output of `.toString()` on `Object` and not the correct thing to call on `ResultSet`, just look at the source code for `ResultSet`, it just does the default on `Object`. I think you need to read the documentation on what you are trying to do, or again if you already have.
Comment: *but it displays in wrong format so far* this means absolutely nothing.
Answer: You need to iterate through the ResultSet and retrieve each column. The ResultSet instance is not your actual result it's a container for the result. Your query returns one column, so you can access the content of that through the index 1 (JDBC column indexes start at 1, not 0 as usual in Java). To move the result set to the next row you need to use next()
ResultSet rs = prepStmt.executeQuery();
if (rs.next()) {
    System.out.println(rs.getString(1));
}

Typically you would use a while() loop to iterate over all rows in the ResultSet but your query will only return a single row due to the aggregation so that's not necessary. Are you sure you really want all rows of the table as a single huge JSON document. What if the table contains a million rows?
This is all explained in the Java JDBC tutorial:

http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html
http://docs.oracle.com/javase/6/docs/technotes/guides/jdbc/getstart/GettingStartedTOC.fm.html


I want to run a bash script when Tomcat deploys my web application from its .war file - is this possible?

Question: (Tomcat version 5.5, in case it matters.)
I have a library in one of my web applications that needs to be configured with a machine-specific license before use.  I don't want to put this library in shared/lib because at some point I may want to run multiple web applications with different versions of the library.
Right now the .jar files are stored in WEB-INF/lib.  Thus, when I build the .war file and upload it to the server, the .jar file would still be the one bound to my PC.  I would like to put a bash script somewhere in the webapp that Tomcat would automatically run when deploying the .war file - this script would then run the configuration script and bind the server's license file to the .jar.  Is this possible?  Is there a nicer way of doing what I want?
Answer: You could create a ServletContextListener to do that in the contextInitialized() method. And from that listener you can run the "configuration script" directly, no other script required.


Matrix unit-vector multiplication and the resulting norm

Question: Is it true that $\|Ax\| = \|A\|\|x\|$ when $\|x\| = 1$ and why?
Comment: No and almost any example other than a multiple of the identity will show that this is not true.
Comment: $\| A \| \| x \|$ is by definition as big as $\| Ax \|$ can be. For most $A$, $\| Ax \|$ varies depending on which direction $x$ points.
Answer: No, because by definition $\lVert A\rVert=\sup_{\lVert x\rVert=1}\lVert Ax\rVert$. Therefore your claim is not reasonable to expect.


console.log is not showing correct values

Question: I am trying to console an object although it's not throwing any error but the result i want is shown after some time and I am not able to retrieve it.
It shows an i icon which says 'value below was evaluated just now' and I am not able to get that values .
OUTPUT: Promise {$$state: {…}}
        $$state:
        status:1
        value:"Modifier"
        __proto__:Object
        __proto__:Object

And I need that value:"MODIFIER" in a variable. How to get it. Thanks in advance.
console.log($translate('MODIFY'));
I am using angular-translate inside a controller.
When I use console.log($translate('MODIFY')['$$state'].value) it shows undefined just because of the reason "value below was evaluated just now". I need the later values or any way to get them before.
Comment: show us what you have done so far...
Comment: please add some code, that seems to be a `promise object` rather than an `object`
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
Comment: seems you need to know how to get a value from an asynchronous call - which is easy with a Promise - but as you've shown **absolutely zero code** then there's not much more can be said
Comment: Thanks all, I really don't know much about promises and this helps me  lot
Answer: What you have here is a promise, which will return you values asynchronously(i.e out of the flow of execution). The correct way to handle this is as follows:
promiseObj.then(function(value){//you're code here})
When i was staring out this here helped me understand promises.
http://andyshora.com/promises-angularjs-explained-as-cartoon.html
Hope this helps,
Cheers!
Comment: Thanks this helps me


Prove all numbers in a sequence $a_{n+3}=15a_{n+2}-15a_{n+1}+a_n$ are perfect squares

Question: $a_{n+3}=15a_{n+2}-15a_{n+1}+a_n$, here $a_1=a_2=1,a_3=9$
Prove all numbers in a sequence are perfect squares.
My attempt is first to use the general formula of $a_n$.
It is $a_n=\frac{1}{6}\left((2+\sqrt3)^{2n-3}+(2-\sqrt3)^{2n-3}+2\right)$
But I still cannot prove every number in the sequence is a perfect square.
Comment: Needs more context, please provide and attach the source of this problem, thank you for finding the explicit form. Also see [this](https://artofproblemsolving.com/community/c4h1108610p5037455) for a similar question, maybe an educated guess using the explicit form might be useful.
Answer: Consider the sequence $(b_n)$ defined by
$$ b_{n+2} = 4b_{n+1} - b_n, \qquad b_1 = b_2 = 1. $$
It is clear that every term of $(b_n)$ is an integer. To prove the claim, it is thus sufficient to establish:

Claim. $a_n = b_n^2$ for all $n$.

Indeed, it is easy to check that the claim is true for $n = 1, 2, 3$. Now suppose the claim is true for $n$, $n+1$, $n+2$. Then
\begin{align*}
a_{n+3}
&= 15a_{n+2} - 15a_{n+1} + a_n \\
&= 15b_{n+2}^2 - 15b_{n+1}^2 + b_n^2 \\
&= 15b_{n+2}^2 - 15b_{n+1}^2 + (-b_{n+2} + 4b_{n+1})^2 \\
&= 16b_{n+2}^2 + b_{n+1}^2 - 8b_{n+1}b_{n+2} \\
&= (4b_{n+2} - b_{n+1})^2 \\
&= b_{n+3}^2,
\end{align*}
and so, the claim is true for $n+3$ as well. Therefore the claim follows by the principle of mathematical induciton.

Motivation. The choice of the sequence $(b_n)$ is motivated by the fact that OP's formula for $(a_n)$ simplifies to
$$ a_{n} = \left[ \frac{\sqrt{3}-1}{2\sqrt{3}}(2+\sqrt{3})^{n-1} + \frac{\sqrt{3}+1}{2\sqrt{3}}(2 - \sqrt{3})^{n-1} \right]^2. $$
Using this, I reverse-engineered the recurrence relation with the characteristic equation having $2\pm\sqrt{3}$ as roots, namely $x^2 - 4x + 1 = 0$.


Three listviews together with one scroll listener are not clickable

Question: I have three listviews. They scroll together (if I scroll one, then the other scrolls too). But I want each list be clickable separately, because if I click now it get firstly operation one then operation two if I click one more time. So if I scroll one list, then all three of them are scrolled (this is implemented in the code below), but if I click on one of them, I want to do one operation, if I click on other list, then there should be done other operation (and if on the third, then third).
When I tried just to add item listener for each list then it starts the operation #1, #2, #3 consecutively no matter which listview is clicked.
I tried to use getId, but it returns the same id.
Don't know what to do.
public void setUpListeners(final ListView listView, final ListView listView2, final ListView listView3)    {

    final View[] clickSource = new View[1];
    final View[] touchSource = new View[1];
    final int offset = 0;

    listView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (touchSource[0] == null)
                touchSource[0] = v;

            if (v == touchSource[0]) {
                listView.dispatchTouchEvent(event);
                listView3.dispatchTouchEvent(event);
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    clickSource[0] = v;
                    touchSource[0] = null;
                }
            }

            return false;
        }
    });

    listView3.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (touchSource[0] == null)
                touchSource[0] = v;

            if (v == touchSource[0]) {
                listView.dispatchTouchEvent(event);
                listView2.dispatchTouchEvent(event);
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    clickSource[0] = v;
                    touchSource[0] = null;
                }
            }

            return false;
        }
    });

    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if(view == clickSource[0])
                listView2.setSelectionFromTop(firstVisibleItem, view.getChildAt(0).getTop() + offset);
        }
    });
}

Answer: Solved it myself (so this is triple, or double if you remove one, list that scrolls synchronously but each list has its own clicklistener):
final View[] clickSource = new View[1];
    final View[] touchSource = new View[1];

    listView.setOnTouchListener(new View.OnTouchListener() {
        float touched;
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (touchSource[0] == null)
                touchSource[0] = v;

            if (v == touchSource[0]) {
                listView2.dispatchTouchEvent(event);
                listView3.dispatchTouchEvent(event);

                if (event.getAction() == MotionEvent.ACTION_UP) {

                    if(Math.abs( touched - event.getY() ) < 10) {
                        int position = listView.pointToPosition((int) event.getX(), (int) event.getY());
                       ///operation #1
                    }
                    touchSource[0] = null;
                }
                else if(event.getAction() == MotionEvent.ACTION_DOWN)   {

                    touched = event.getY();

                }
            }

            return false;
        }
    });

    listView2.setOnTouchListener(new View.OnTouchListener() {
        float touched;
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (touchSource[0] == null)
                touchSource[0] = v;

            if (v == touchSource[0]) {
                listView.dispatchTouchEvent(event);
                listView3.dispatchTouchEvent(event);
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    AbsListView alv = (AbsListView) v;
                    if(Math.abs( touched - event.getY() ) < 10) {

                        int position = listView.pointToPosition((int) event.getX(), (int) event.getY());
                        clickOnLocation(position);
                       ///operation #2
                    }
                    touchSource[0] = null;
                }
                else if(event.getAction() == MotionEvent.ACTION_DOWN)   {

                    touched = event.getY();

                }
            }
            return false;
        }
    });

    listView3.setOnTouchListener(new View.OnTouchListener() {
        float touched;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (touchSource[0] == null)
                touchSource[0] = v;

            if (v == touchSource[0]) {
                listView.dispatchTouchEvent(event);
                listView2.dispatchTouchEvent(event);
                if (event.getAction() == MotionEvent.ACTION_UP) {

                    if(Math.abs( touched - event.getY() ) < 10) {

                        int position = listView.pointToPosition((int) event.getX(), (int) event.getY());
                        clickOnLocation(position);
                       ///operation #3
                    }
                    touchSource[0] = null;
                }
                else if(event.getAction() == MotionEvent.ACTION_DOWN)   {

                    touched = event.getY();

                }
            }
            return false;
        }

    });


Is Ubuntu unstable or is it just my computer?

Question: Three days ago, Ubuntu crashed (not responding), and I typed  ALT  +  Print  +  Reisub , it restarted as usual, but displayed a System is running in low-graphics mode message.
When I type my login and password in the terminal, a message blinks (so fast that I couldn't read it) and then it asks me to type in the login and password again.
I formatted my computer using Windows 7, and now as I run it, it is very slow. Ubuntu was far faster than, even though it is not as stable.
Anyway, is there a solution to use Ubuntu (or any other Linux distro), and prevent these system crashes and low-graphics messages from reappearing?
I really love Linux, but apparently it's unstable on my machine. What about the other distros?
Comment: @SmootQ it's Intel Integrated Graphics. WDDM is the type of driver (it can support Aero). Since you have an Acer, I'm going to say there is a problem with your computer. My Acer Aspire killed itself after about 3 years. During its lifetime, though, it just got worse and worse, to the point where it would freeze up and crash every 10 minutes, no matter what OS was on it.
Comment: How old is the computer?  Several years?
Comment: What is the Ubuntu version?
Comment: I bought it 2 years ago (2013), it's an aspire 5732Z
Comment: @Pilot6 Ubuntu version is 14.04
Comment: What is the video adapter?
Comment: @Pilot6 apparently it's WDDM
Comment: What is WDDM???
Comment: @Pilot6 When I check my graphics card it shows : " Express Mobile Intel(R) 45 (Microsoft Corporation WDDM)
Comment: @Pilot6 Apparently, windows 7 doesn't detect my graphics card :(
Comment: @Zacharee1 well, I guess I have no choice, but wait for other 2 years to say Goodbye to this computer :D
Comment: Which version of Ubuntu are you running? It seems like a hardware fail issue here.
Answer: I have an Acer and had to change the hard disk after a couple of years.
Try running a smartctl test on the drive and see what it reports. Check out:

https://apps.ubuntu.com/cat/applications/natty/gsmartcontrol/ for the graphical version, (that seems to be for natty),
https://apps.ubuntu.com/cat/applications/smartmontools/ for the command line version.

If the hard disk is messed up, things won't work well regardless of the OS. Changing the hard disk in my Acer Aspire, was very simple but I can't speak for your one. You need to check it first though.
Comment: Good man!  An edit and an upvote! (Oh, and kids nowadays don't call them OpSys any more: just OS...)  **;-)**
Comment: This way of adding comments and making changes after the event is new to me... or maybe it's old and I've forgotten it. One or the other :D
Comment: Thank you so much for this precious answer, I'll check it out for sure.


How to make responsive banner in vegas slider

Question: i already add css for responsive banner vegas slider for my portal. The problem is the recommended size for the banner is 1800X600px and it display nicely in 1280X1024 of monitor resolution but the banner will be stretched and the banner look ugly in 1860X1020 of monitor resolution. If i view it via mobile phone, the banner will be squeeze to fit the screen. Below is the css that i add.
.vegas-slide-inner {
    background-size:100% 100% !important;
}

Is there any other way to make the banner fit in any resolution of display?
Comment: can u add a  preview !
Comment: you can go to https://www.yp.com.kh/ and look at the first image of the slider. My concern is the yellow book in my image.
Comment: i suggest to change a responsive slider this is an example : http://pgwjs.com/pgwslider/
Answer: Use cover instead of giving it 100%
background-size: cover;
Comment: hi Anmol, i've try your method but it seems doesn't work.
Comment: Hello Iqmal, i see background-size: 100% is overriding cover. I think you should apply bakground-size: cover !important. It will work definately


eGalax touchscreen detects no input in upper part of the screen

Question: According to xinput, the touch sensor in question is an EXC7200-7623v1.000, and is recognized as two slave pointers, one of wich is of type "Pen".
With xinput test 12 (the non-pen part has the id 12), I get regular event outputs, and Ubuntu even recognises multitouch gestures correctly, but above a certain border, no input is registered. For example, swiping from the bottom to the top of the screen ends in this output:
motion a[0]=13744 a[1]=9520
motion a[0]=13744 a[1]=9552
motion a[0]=13744 a[1]=9552
button release 1 a[0]=13744 a[1]=9552

At that point, my finger is still on the screen, but moving it has no effect. Tapping in that area has no effect either. The end is variable, too. It lies roughly between  a[1]=8600 and a[1]=10200, depending on the speed of the swipe.
I tried to calibrate the screen with xinput_calibrator, but it does not respond to taps on the first crosshair, which is in the upper left part of the screen.
Is this a driver issue, a problem with X, or could my sensor be broken?
Answer: After testing the display on windows with the same results, I came to notice a hardware defect. The FPC from the sensor to the controller is torn on the lanes that are responsible for the upper part of the screen.


ggplot2: mixing simple and grouped bars in a single bar plot

Question: I have a data.frame :
df <- structure(list(sample = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("A",
"B", "C"), class = "factor"), replicate = c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L),
    treatment = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L,
    2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("V0",
    "V2", "V4", "V6"), class = "factor"), mean = c(72.5, 66.4,
    60.3, 56.3, 90.7, 86.9, 68.8, 64.6, 73.3, 69.8, 62.3, 68.7,
    77.1, 73.6, 65.9, 65.3, 75.7, 73.8, 65.9, 66.8), sd = c(5.4,
    6.1, 3.5, 4.7, 1.2, 4.9, 8.4, 6.1, 7.3, 3.5, 5.9, 2.2, 3.2,
    3, 3.1, 4.2, 4.2, 2.4, 2.2, 2.6)), .Names = c("sample", "replicate",
"treatment", "mean", "sd"), class = "data.frame", row.names = c(NA,
-20L))

For some samples I have replicates while for others I don't :
> head(df, 15)
   sample replicate treatment mean  sd
1       A         1        V0 72.5 5.4
2       A         1        V2 66.4 6.1
3       A         1        V4 60.3 3.5
4       A         1        V6 56.3 4.7
5       B         1        V0 90.7 1.2
6       B         1        V2 86.9 4.9
7       B         1        V4 68.8 8.4
8       B         1        V6 64.6 6.1
9       C         1        V0 73.3 7.3
10      C         1        V2 69.8 3.5
11      C         1        V4 62.3 5.9
12      C         1        V6 68.7 2.2
13      C         2        V0 77.1 3.2
14      C         2        V2 73.6 3.0
15      C         2        V4 65.9 3.1

I would like to plot means in a faceted bar plot for each sample value. I would like to get grouped bars when replicates > 1. Is it possible with ggplot2 ?
What I get so far :
g <- ggplot(df, aes(x=treatment, y=mean, fill=sample))
g <- g + geom_bar(position="dodge")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position="dodge")
g <- g +  facet_grid(. ~ sample)

g

EDIT
Following the suggestion of @Tyler Rinker, I get :
g <- ggplot(df, aes(x=treatment, y=mean, fill=replicate))
g <- g + geom_bar(position="dodge", stat="identity")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position="dodge", width=0.25)
g <- g +  facet_grid(. ~ sample)

However, I would like to get the bars for the 'C' sample replicates displayed side-by-side.
EDIT2 Very close to ...
Simply by adding group = replicate :
g <- ggplot(df, aes(x=treatment, y=mean, group=replicate, fill=replicate))
g <- g + geom_bar(position="dodge", stat="identity")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position="dodge", width=0.25)
g <- g +  facet_grid(. ~ sample)

However there is a remaining problem with the position of the error bars. I guess I have to play with dodge ? But I don't know how ...
EDIT3 Eventually... thanks to @joran
dodge <- position_dodge(width = 0.9)

I checked that other values than 0.9 did not lead to a correct positioning of the error bars
g <- ggplot(df, aes(x=treatment, y=mean, group=replicate, fill=replicate))
g <- g + geom_bar(position="dodge", stat="identity")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position=dodge, width=0.25, color="black")
g <- g +  facet_grid(. ~ sample)

Comment: I haven't read carefully but I think you want `geom_bar(position="dodge", stat="identity") +`  Not sure about the rest of what you want.
Comment: What do you mean by grouped bars?
Comment: @Maiasaura For one x-value, I get several bars. In my example, I expect to have 3 bars for each x-value for the 'C' sample.
Comment: @TylerRinker Thanks for your suggestion. That brings me one step further but I get the bars superposed and not presented side-by-side as expected...
Answer: Try this and experiment a bit:
dodge <- position_dodge(width = 0.9)

g <- ggplot(df, aes(x=treatment, y=mean, group=replicate, fill=replicate))
g <- g + geom_bar(position=dodge, stat="identity")
g <- g + geom_errorbar(aes(ymax=mean+sd, ymin=mean-sd), position = dodge,width = 0.25)
g <- g +  facet_grid(. ~ sample)
g

I think the different dodging in each panel was confusing the width setting. I'd have to read up a bit on the details of dodging (and there are several people around these parts who may be able to weigh in more easily than myself...) but I think that when you set the dodging "locally" in each geom, ggplot is deciding things about widths based upon information in each layer separately. So the trick here seemed to be to ensure a "global" dodge setting.
Comment: Thanks ! It works... I don't really understand why we have to set this 'width' value to 0.9 but it does the job !
Comment: @ptocquin It's not the specific width; experiment a bit changing it. As I noted in my edit, I think the key part is ensuring that ggplot is using the same width for dodging in each layer, rather than choosing a width "by default" for each layer.


Drainage for level driveway

Question: I am thinking of replacing my asphalt driveway with granite paving. The problem is that if I build a mortar bed for the granite blocks it will be level, so that water will sit on top of the driveway and not drain off.
In professional road building the road surface is crowned to provide for water shedding.
How can build the driveway so that water sheds off?
Comment: A mortar bed completely defeats the environmental and practical benefits of a permeable surface like granite blocks. Use something else that drains naturally.
Answer: You don't need to crown the driveway, just make sure that the runoff slopes away from the house at to one and a half inches per ten feet; so if your driveway is 20ft long, the bottom should be 3inches lower than the top. If possible, pitch in two directions, so water runs to the bottom and to the side. (the recommended minimum is 1" to 10', but I like to play safe)
You don't set granite blocks in a mortar bed - it's too rigid and brittle. Use blocks designed for a vehicle driveway (they're thicker than the normal pavers you can buy). Put a good base below that - 8 to 12 inches, compacted. Anything less will not take the weight of the cars for too long. Spend a lot of money and time getting the base right, and the block part of it will be fun.
The internet has a lot of help on how to build and install driveways. My advice is only as follows;

Prepare your base such that it extends sideways 50% of the depth. So if you're working on a 12" base, you want to prepare an area 6" extra all round (so a 10'x20' drive needs an 11' x 21' base)
Rent, or buy, a vibrating plate compactor. It's worth it for the speed and quality of finish.
Don't think that you can get away with a thinner base because you have hard ground. You may get away with it, but it's better to be absolutely sure that the base you've built is to your specifications, not Mother Natures.
Comment: Other than poly sand I agree, poly sand is much more expensive and I find it to only last 1-2 years longer without needing additional sand added at 2-3x the cost.
Comment: How do I slope the base? If I add stones to a sloped surface, won't they crack due to unequal pressures?
Comment: Building a driveway is a massive subject - lots of videos on the internet. Basically, you dig out to the depth that you need, put woods forms around the area you need to build (use the forms to set the slope), and set their top edge to your final height. Add roadbase in 2" lifts. Compact each. The last layer is sand, which is also compacted, and leveled to the top of the forms. Then place the blocks on top of the sand (make sure they're constrained at the edges. Fill the gaps with polymeric sand, and you're done.

Drainage for level driveway


dynamic object creation and function call

Question: The problem is to call Honda class display method. Which class method will be called depends upon the string variable that will be passed at runtime. Here I have used one parent class of Honda so that I can achieve  runtime polymorphism. But then I am getting ClassNotFoundException even that is included in the throws clause of main. Unable to figure what to do.
Here is the code of all the three classes which are there in the same package.
Vechicle.java
package com.company;

public class Vehicle {
    public void display() {
        System.out.println("Random text");
    }
}

Honda.java
package com.company;

public class Honda extends Vehicle{
    public void display()
    {
        System.out.print("honda called");
    }

}

Main.java
package com.company;

import java.lang.reflect.InvocationTargetException;

public class Main {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

            String className = "Honda";
            Class cls = Class.forName(className);
            Vehicle v = (Vehicle) cls.getDeclaredConstructor().newInstance();
            v.display();
    }
}

The error which I am getting is :
Exception in thread "main" java.lang.ClassNotFoundException: Honda
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:315)
    at com.company.Main.main(Main.java:10)

I think I need to handle the ClassNotFoundException in Honda class also but extends and throws can't work simultaneously. Please help me in finding the issue.
Answer:
But then I am getting ClassNotFoundException even that is included in the throws clause of main.

A throws clause doesn't stop an exception happening - it just specifies that the method might throw that checked exception.
The problem is that Class.forName accepts a fully-qualified class name, and you don't have a class with a fully-qualified name of Honda. You have a class with a fully-qualified name of com.company.Honda.
If you change the start of your code to:
String className = "com.company.Honda";

... then I expect that will solve the problem.
Comment: @sakshisinghal: I would suggest using this as an opportunity to think about your diagnostic process - think about what questions you could have asked yourself to work out the problem. Exceptions (as opposed to compile-time errors) are never *caused* by a `throws` clause etc. When an exception occurs, use the message and the stack trace to work out what has caused it.
Comment: Amazing. Thanks a lot


Error running pwntools on Ubuntu 18

Question: I'm on Ubuntu 18 with 64b.
To install pwntools, I've run:
$ sudo apt install python3 python3-pip python3-dev git libssl-dev libffi-dev build-essential
$ sudo python3 -m pip install pwntools

When I run pwn, it gives me the following error(s):
$ pwn
Traceback (most recent call last):
  File "/usr/local/bin/pwn", line 5, in <module>
    from pwnlib.commandline.main import main
  File "/usr/local/lib/python3.6/dist-packages/pwnlib/__init__.py", line 43, in <module>
    importlib.import_module('.%s' % module, 'pwnlib')
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/usr/local/lib/python3.6/dist-packages/pwnlib/args.py", line 61, in <module>
    from pwnlib import term
  File "/usr/local/lib/python3.6/dist-packages/pwnlib/term/__init__.py", line 5, in <module>
    from pwnlib.term import completer
  File "/usr/local/lib/python3.6/dist-packages/pwnlib/term/completer.py", line 6, in <module>
    from pwnlib.term import readline
  File "/usr/local/lib/python3.6/dist-packages/pwnlib/term/readline.py", line 7, in <module>
    from pwnlib.term import term
  File "/usr/local/lib/python3.6/dist-packages/pwnlib/term/term.py", line 167
    def goto((r, c)):
             ^
SyntaxError: invalid syntax

How should I fix this to run pwntools?
Answer: TL;DR: run
sudo python3 -m pip install --upgrade git+https://github.com/Gallopsled/pwntools.git@dev3

The pip version of pwntools is not up to date, I currently see version 3.12.2 in pip. This old version does not work properly with python3.
The installation instructions suggests installing directly from the git repo: https://github.com/Gallopsled/pwntools/#installation
The fix was done in this commit:
https://github.com/Gallopsled/pwntools/commit/6c794022d50fcb5c9eeafec3cfc5bdf7728f8a5e
I had the same issue, and this question page was the first Google result. Hope it helps someone! :)
Comment: Even if this link may solve the issue, Link-only answers aren't recommended, due to the risk of seeing these ones die, so could you gather important steps from these links?
Comment: @damadam I agree, thanks for making me a better contributor.

However, in this case the problem is that the `pip` version of `pwntools` is outdated. The solution is to install `pwntools` from source, and the links are to the source.

I have gathered the single relevant instruction; the command line to install from source with `pip`. This wont work if the links die. (They all point to the same github repository.)

I'm not sure it would help to gather the source code here. ;)

Error running pwntools on Ubuntu 18


How can I determine the manufacturer of my diverter?

Question: I'm currently experiencing the same situation as this post:how-do-i-prevent-this-bath-faucet-from-leaking-while-the-shower-is-running My bath faucet's lever to redirect the water to overhead shower does not fully stop the water.
My plumber is having a difficult time determining the manufacturer to be able to order the nozzle. What are some ways to determine the maker of the nozzle?
Asking since I can't just replace it with the standard chrome or brushed metal ones. My current nozzle is gold-plated (or gold-painted) and the wife would like its replacement to match. Therefore, I need to know the maker to be able to order the part.
Comment: I wouldn't worry about getting the exact one. Even if you could find the make/model, who knows if they still make it or if it is identical (designs change over the years).  go find something similar that your wife likes and install it.
Answer: Finding the manufacturer/model could be difficult.  Is This close enough?  Or
This?


How to display loaded data after page refresh in vue, the data is displayed in the console but not in theview

Question: I'm loading notifications from an api using get request, the data is there i can see it in the console but it's not displayed in the view here is my code :

            Notifications

            {{ notifications.length }} New

<vue-perfect-scrollbar v-once :settings="perfectScrollbarSettings" class="scrollable-container media-list scroll-area" tagname="li">

            <template #aside>

            </template>

                    {{ notification.data.message }}

            {{ notification.created_at | formatDate}}

</vue-perfect-scrollbar>

here is the method :
data() {
        return {
            notifications: []
        }
    },

    mounted() {
        this.getNotifications();
    },
    methods: {
        getNotifications() {
            axios.get(apiHost + '/notification')
                .then((response) => {
                    for (let i = 0; i < response.data.length; i++) {
                        this.notifications.push(response.data[i])
                    }
                    console.log(this.notifications)
                })
                .catch(resonse => {
                    console.log(resonse);
                })
        },
    },

I just get the length of the array but i can t display the data:
Comment: no nothing change
Comment: @zerbene you can't use computed for async functions
Answer: please try just this:
data() {
        return {
            notifications: []
        }
    },

    async mounted() {
        await this.getNotifications();
    },
    methods: {
        async getNotifications() {
            await axios.get(apiHost + '/notification')
                .then((response) => {
                    this.notifications = response.data
                    }
                })
                .catch(resonse => {
                    console.log(resonse);
                })
        },
    },

otherwise please show us the response from the api, if you like mocked of course
Comment: i removed v-once and it worked ! thank you !!


How facebook and google can detect my device

Question: I was wonder how facebook and google redial different links for different devices and also they redial there lite veesion to the android or IOS opera mini too. So i research a little bit and got some idea about detection user agent with java script but I can't find any real answer or code so that I can use it for my website.
So anyone know how its done and get me that code and I also think the php code would be the best if its possible cause user could disable there javascript.
Comment: what you want ?? device detect from website??
Comment: http://mobiledetect.net/ this is a simple library i think this will help you
Comment: http://blog.teamtreehouse.com/exploring-javascript-device-apis
Comment: Yea i wana detect there device user agent and redial three different version of my website like destop, mobile and lite version.
Comment: Thanks the Mobiledetect.net website was a great help..
Answer: Using PHP:
var_dump( $_SERVER['HTTP_USER_AGENT'] );

More at: PHP.net
Using Javascript:
alert( navigator.userAgent );

More at: W3School.com


2 to 1 dimension in linear PDE with non-constant coefficients

Question: I have a question that can majorly help in my physics.
Problem
Say, we have a linear PDE
\begin{equation}
\hat{D}~F(x,y)=0,
\end{equation}
with $\hat{D}$ being a (second order) differential operator, containing, in general, non-constant coefficients, $\partial_x$, $\partial_y$, $\partial_x^2$, $\partial_y^2$ and $\partial_{xy}$.
Suppose, I know a solution $F(x,y)$ - surface, and I want to cut it with a curve $y=f(x)$, so that I get a function $\psi(x)=F(x,f(x))$.
Question
Is there any general way, to transform the $\hat{D}$ 2D operator to $\hat{D'}$ 1D operator, containing $x$, $\partial_x$ and $\partial_x^2$, so that
\begin{equation}
\hat{D'}~\psi(x)=0.
\end{equation}
Would much appreciate any close answer or even a probable reference where could I read about this.
Comment: Use the chain rule for partial derivatives, assuming $y$ is a function of $x$ to rewrite any derivatives with respect to $y$ in the $2D$ operator to derivatives with respect to $x$.
Comment: I thought so, but... What would you take for $\partial_{xy}$? If $f(x)$ is not linear, then $\partial_{xy}\ne \partial_{yx}$.
Comment: Even more, the ODE would not be correct in any case. Say, we have $(\partial_x + \partial_y)F(x,y)=0$. We substitute $y=f(x)$, $\psi(x)=F(x,f(x))$; $\partial_y\rightarrow (f')^{-1}\partial_x$. And so we get $((f')^{-1}+1)\psi'(x)=0$. And $\psi=const$, as $f(x)$ is arbitrary.

But $F(x,f(x))$ is NOT $const$ for all $f(x)$.
Answer: My answer will be very vague. But you need to find invariants of this equation and after you find  go to canonical coordinates and it will reduce the dimensionality of the equation(will make it ODE)
Prof. Bluman is one of the most prominent scientist in the field of symmetries you can check out books on his website for more information.
https://www.math.ubc.ca/~bluman/
I recommend this book:
Bluman, G, Cheviakov, A & Anco, S, Applications of Symmetry Methods to Partial Differential Equations, 417pp. Springer, New York, Vo. 168, Appl. Math. Sci. 2010.
Comment: Answers on this site should not be vague. Post a good answer, or don't post at all. Also, since the majority of your post is vague promotion ("*hey, I can't answer your question, but buy this book*"), this post should be flagged as spam.
Comment: Well, yes, symmetries and invariants in general indeed reduce the dimension of PDE. The problem is, that I need to do it for any $y=f(x)$, or in general parametric form $x=f(t)$, $y=g(t)$. But maybe I'd be able to work out from that way, so I'll take a glance at those books. Thanks = )
Comment: Mike, don't worry, I'm not going to buy this book, I already found it [free](http://bookfi.org/book/1065448) :)
Comment: Dear Mike, It's not my book. The book is free. And the answer may be there. It is better to have a look there and maybe find the answer.


Do cards that have been unlocked earlier than the actual release appear in the shop?

Question: If I unlock a card from earlier than its actual release (e.g. through special challenges) appear in the Shop? It would be useful to know because it may be difficult to level them up otherwise.
Answer: Challenges are ways to get the card before they are actually released. Some examples are the Bandit Challenge and the more recent Heal Spell Challenge. During those challenges, no one could have won those cards other than through winning the challenges.
After the official release though is when everyone (after a certain arena like you need to be at least in Hog Mountain to get the Heal Spell) can try to get the new card(s).
Comment: Or, the more recent one, the Fisherman Challenge
Answer: Those will appear in the shop only after the official release.
Answer: Simply put, no, but you can acquire the cards early by winning any challenges offering the card.


Failed to run custom build command for `libgpg-error-sys v0.6.0` when cross compiling rust project using cross

Question: Whenever I try to cross compile my rust project on my Machine running arch linux, using cross for the x86_64-unknown-linux-gnu architecture I get this error
$ cross build --target x86_64-unknown-linux-gnu
   Compiling tracing v0.1.37
   Compiling parking_lot_core v0.9.7
   Compiling rand_core v0.5.1
   Compiling libgpg-error-sys v0.6.0
error: failed to run custom build command for `libgpg-error-sys v0.6.0`

Caused by:
  process didn't exit successfully: `/target/debug/build/libgpg-error-sys-49b8c1a22a8cb06e/build-script-build` (exit status: 1)
  --- stdout
  cargo:rerun-if-env-changed=GPG_ERROR_NO_PKG_CONFIG
  cargo:rerun-if-env-changed=PKG_CONFIG_x86_64-unknown-linux-gnu
  cargo:rerun-if-env-changed=PKG_CONFIG_x86_64_unknown_linux_gnu
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG
  cargo:rerun-if-env-changed=PKG_CONFIG
  cargo:rerun-if-env-changed=PKG_CONFIG_PATH_x86_64-unknown-linux-gnu
  cargo:rerun-if-env-changed=PKG_CONFIG_PATH_x86_64_unknown_linux_gnu
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG_PATH
  cargo:rerun-if-env-changed=PKG_CONFIG_PATH
  cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR_x86_64-unknown-linux-gnu
  cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR_x86_64_unknown_linux_gnu
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG_LIBDIR
  cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64-unknown-linux-gnu
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64_unknown_linux_gnu
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG_SYSROOT_DIR
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR

  --- stderr
  Error: PkgConfig(`PKG_CONFIG_ALLOW_SYSTEM_CFLAGS="1" "pkg-config" "--libs" "--cflags" "gpg-error" "gpg-error >= 1.12"` did not exit successfully: exit status: 1
  error: could not find system library 'gpg-error' required by the 'libgpg-error-sys' crate

  --- stderr
  Package gpg-error was not found in the pkg-config search path.
  Perhaps you should add the directory containing `gpg-error.pc'
  to the PKG_CONFIG_PATH environment variable
  No package 'gpg-error' found
  Package gpg-error was not found in the pkg-config search path.
  Perhaps you should add the directory containing `gpg-error.pc'
  to the PKG_CONFIG_PATH environment variable
  No package 'gpg-error' found
  )
warning: build failed, waiting for other jobs to finish...

I have gpgme = "0.11.0" as a dependency in my Cargo.toml file

I reinstalled the libgpg-error package
Tried adding the output of pkg-config --path gpg-error to the PKG_CONFIG_PATH variable as well. The output of pkg-config --path gpg-error is /usr/lib/pkgconfig/gpg-error.pc
Answer: This works for me:

sudo apt-get -y update && sudo apt-get install -y libgpgme-dev && sudo apt-get install -y libgpg-error-dev

Then restart the terminal.
Comment: It worked for me too, but no need to restart terminal
Comment: But I got this problem without any cross compilation. So I guess this just adds what is needed for the gpgme crate.


Tranquility not sending data to Druid

Question: I am evaluating Druid for my use case which ingest csv data through tranquility in real time. Following is the server configuration:-
{
  "dataSources" : {
    "audience" : {
      "spec" : {
        "dataSchema" : {
          "dataSource" : "audience",
          "parser" : {
            "type" : "string",
          "parseSpec":{
    "format" : "csv",
    "timestampSpec" : {
      "column" : "timestamp"
    },
    "columns" : ["timestamp","partner_id","event_id","product_id","device_id","count"],
    "dimensionsSpec" : {
      "dimensions" : ["partner_id","event_id","product_id","device_id"]
    }
  }
},
          "metricsSpec" : [{ "type" : "longSum", "name" : total, "fieldName" : "count" }],
  "granularitySpec" : {
    "segmentGranularity" : "HOUR",
    "queryGranularity" : "HOUR",
    "intervals" : [ "2013-08-31/2013-09-01" ]
  }

  },
        "ioConfig" : {
          "type" : "realtime"
        },
        "tuningConfig" : {
          "type" : "realtime",
          "maxRowsInMemory" : "100000",
          "intermediatePersistPeriod" : "PT10M",
          "windowPeriod" : "PT10M"
        }
      },
      "properties" : {
        "task.partitions" : "1",
        "task.replicants" : "1"
      }
    }
  },
  "properties" : {
    "zookeeper.connect" : "localhost",
    "druid.discovery.curator.path" : "/druid/discovery",
    "druid.selectors.indexing.serviceName" : "druid/overlord",
    "http.port" : "8200",
    "http.threads" : "8"
  }
}

data is generated randomly by a python script as:-
1471336991,1,960,136,3ZLA7,1
1471336991,1,369,367,8MP2B,1
1471336991,2,544,550,C9ZG8,1
1471336991,1,135,394,XFX31,1
1471336991,2,590,552,VXMTL,1
1471336991,1,493,615,0C2HR,1
1471336991,2,435,710,HKYP0,1
1471336991,1,394,483,V2HP9,1
1471336991,2,441,376,J1LYO,1

Following commands submits the data and returns {"result":{"received":1000,"sent":0}}
python createData.py |curl -XPOST -H'Content-Type: text/plain' --data-binary @- http://localhost:8200/v1/post/audience.

Answer: Finally able to solve the problem. Actually I was sending time to Druid in Epoch time format, but it expect ISO-8601 format. In python one can easily get so by :-
datetime.datetime.utcnow().isoformat()

Comment: This is a irrevalent question to your post! But do you happen to know the difference between `windowPeriod` and `segmentGranularity` in the real time ingestion spec above? Like does it create a segment based on the value you provide in the `windowPeriod` or the `segmentGranularity`?
Comment: Yup! Window period is about relevance of the data and segment granularity tells when to rollup the data.
Comment: @MangatRaiModi Do you mind looking at the question here? https://stackoverflow.com/questions/45206900/tranquility-server-would-not-send-data-to-druid I try to send data to a server with window period of one year. Tranquility receives the data but would not send it. Thanks!
Answer: Druid supports multiple time formats which can be specified in the "timestampSpec" property.
The Druid documentation lists the following timestamp formats: "iso, millis, posix, auto or any Joda time format."
For example, to send time in milliseconds:
"timestampSpec" : {
    "column" : "timestamp",
    "format" : "millis"
 }

Answer: A couple of things

Use ISO 8601 Datetime format
Make sure the written timestamp is within +/- 10Mins of the current hour
Comment: See what @rohitkochar posted.  Druid can accept different format.

Tranquility not sending data to Druid


How to detect a personmovement in a RoI

Question: I have a video and want to know when a person enters and stays in a specific area in the video, then sets a time in the video (video time), when he enters, and when he leaves to use this times later for cutting the video.
Im only a little bit experienced in opencv but have currently no experience with tensorflow or keras.
This is for a video analysis.
I have tried some things like BackgroundSubtractorMOG, use another resolution, etc.
https://s18.directupload.net/images/190517/wym8r59b.png
https://s18.directupload.net/images/190517/pi52vgv7.png
def calc_accum_avg(frame, accumulated_weight):

    global background

    if background is None:
        background = frame.copy().astype("float")
        return None

    cv2.accumulateWeighted(frame, background, accumulated_weight)

def segment(frame, threshold=25):

    global background

    diff = cv2.absdiff(background.astype("uint8"),frame)

    _, thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)

    contours, hierarchy = cv2.findContours(thresholded.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    if len(contours) == 0:
        return None

    else:
        move_segment = max(contours, key = cv2.contourArea)

        return (thresholded, move_segment)

def main():
  video = cv2.VideoCapture("/home/felix/Schreibtisch/OpenCVPython/large_video.mp4")
  video.set(3, 1920)
  video.set(4, 1080)
  length = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
  print(length)
  num_frames = 0

  fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()

  while True:
      ret,frame = video.read()
      fgmask = fgbg.apply(frame)
      if frame is None:
          return
      frame_copy = fgmask.copy()
      #frame2_copy =frame.copy()
      roi_visualiser = frame[roi_visualiser_top:roi_visualiser_bottom,roi_visualiser_right:roi_visualiser_left]
      roi_board = frame[roi_board_top:roi_board_bottom,roi_board_right:roi_board_left]
      gray = cv2.cvtColor(roi_visualiser, cv2.COLOR_BGR2GRAY)
      gray = cv2.GaussianBlur(gray, (9,9), 0)
      #gray = cv2.cvtColor(roi_board, cv2.COLOR_BGR2GRAY)
      #gray = cv2.GaussianBlur(gray, (9,9), 0)
      if num_frames < 2:
          calc_accum_avg(gray, accumulated_weight)
          #calc_accum_avg(gray2, accumulated_weight)
          if num_frames <= 1:
              cv2.imshow("Finger Count", frame_copy)

      else:
          hand = segment(gray)
          if hand is not None:
              thresholded, move_segment = hand
              cv2.drawContours(frame_copy, [move_segment + (roi_visualiser_right, roi_visualiser_top)], -1, (255,0,0), 1)
              #cv2.drawContours(frame_copy2, [move_segment + (roi_board_right, roi_board_top)], -1, (255,0,0), 1)
              fingers = count_moves(thresholded, move_segment)
              if fingers > 0:
                  print("ja") #test funktioniert
              else:
                  print("Nein")
              cv2.putText(frame_copy, str(fingers), (70,45), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2) #no need
              cv2.imshow("Thresholded", thresholded) #no need
      cv2.rectangle(frame_copy, (roi_visualiser_left, roi_visualiser_top), (roi_visualiser_right, roi_visualiser_bottom), (255,0,0), 1)
      cv2.rectangle(frame_copy, (roi_board_left, roi_board_top), (roi_board_right, roi_board_bottom), (255,0,0), 1)
      num_frames += 1

      cv2.imshow("Finger Count", frame_copy)

I get no error messages all runs fine, but i dont get the correct result i need.

  [1]: https://i.stack.imgur.com/dQbQi.png
  [2]: https://i.stack.imgur.com/MqOAc.png

Comment: Can you expand on what you have tried and why it did not work?
Answer: Have you tried BackgroundSubtractorMOG2? It can distinguish shadows, you can use that to prevent false positives.
To make the processing more efficient, first create a subimage of the area where the person enters/leaves. Apply the backgroundsubtraction on the subimage. Also, if the frames are noisy, applying a blur before backgroundsubtraction can improve the result.
Check the resulting mask for white objects of significant size. If detected, store the frame number using video.get(CV_CAP_PROP_POS_FRAMES) in an array and stop recording frame numbers until the mask is fully black again.
Comment: Thanks for your answer and yes i have tried it with MOG2 but have the same problem with the shadow i have tried  cv2.Canny(IMG, 300, 600, 3) but now i cant find any Contuors !??
Comment: Can you add an image of `fgmask` with a false positive using MOG2, and also the declaration of MOG2? Even better would be if you could upload a 10 second video with the false detection in the middle.

How to detect a personmovement in a RoI


How to pass arguments from one function to other functions?

Question: I have created three functions. The first function is used in the other two functions but I am passing it a hardcoded filepath. I want to be able to pass this in as a parameter, but I seem to be getting an issue.
Essentially, given a file_path, my function will get the first item in the list and then the second item.
So far my code is as follows :
def sort_files(file_path):
    """Sort files in ascending order"""
    files = os.listdir(file_path)
    return sorted(files, reverse=True)

def current_day():
    """Get the current day file"""
    return sort_files(file_path)[0]

def previous_day():
    """Get the previous day file"""
    return sort_files(file_path)[1]

Comment: Please explain the nature of the "issue" you are getting.
Comment: @Primusa

Could you provide an example
Comment: Because `file_path` isn't defined in those functions; you have to pass it *to* them from the caller(s).
Comment: why not make `file_path` a parameter in your functions
Comment: @ScottHunter

Well when i am passing file_path within my function current_day and previous_day , i get an error saying "unresolved reference 'path'"
Answer: If you want a function to accept an argument, you need to define it as doing so by specifying the parameter name it will be known as in the function (as you did with sort_files).
Answer: How are you executing the call to the current_day and previous_day. You should make them as function that can take a parameter.
Also please post the code that you are using to execute the whole setup.


Difference between TickerProviderStateMixin and SingleTickerProviderStateMixin?

Question: When I work with AnimationController it requires a vsync parameter. I have researched, should I use TickerProviderStateMixin or SingleTickerProviderStateMixin, currently I still do not know what is the difference between them. Thanks if you give me an explanation about it.
References:
https://api.flutter.dev/flutter/widgets/SingleTickerProviderStateMixin-mixin.html
https://api.flutter.dev/flutter/widgets/TickerProviderStateMixin-mixin.html
Answer: When you are using single AnimationController use SingleTickerProviderStateMixin.
If you need more than one AnimationController use TickerProviderStateMixin.
We need TickerProviderStateMixin below snippet because we have two AnimationController
class _TrickerExampleState extends State<TrickerExample>
    with TickerProviderStateMixin {
  late AnimationController controller1;
  late Animation<double> fadeAnimation;

  late AnimationController controller2;
  late Animation<Alignment> positionAnimation;

Answer: Remember the main propose of the Ticker: Calls its callback once per animation frame. That's why the AnimationController needs a Ticker and that's why depending on the number of AnimationControllers you need one Mixin is more efficient like they said. So, if you can create all your animations with one AnimationController then use the SingleTickerProviderStateMixin. If you need more than one AnimationController then use the TickerProviderStateMixin.
Answer: as the documentation says, they will provide Ticker.
The difference is that SingleTickerProviderStateMixin Provides one Ticker and has less MixinApplication than TickerProviderStateMixin

I think we have to know what is Ticker.
here a snippet explanation :
Using Flutter's animation framework, this is achieved through a Ticker + TickerProvider.

Ticker is the refresh rate of our animations. This is what we want to
pause when our clock is hidden.
TickerProvider, usually implemented with
SingleTickerProviderStateMixin, is a binding between Ticker and
external factors.

here the complete article about it : https://dash-overflow.net/articles/why_vsync/


React router displaying Multiple components at the same time

Question: I am trying to have multiple routes, so I can redirect from one to another, but every time I add another route, the main app renders the styles and the components at the same time, I've tried lazyLoad, Switch and to add the "exact" in the Route path

import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'

import HomePage from './components/homePage/homePage';
 import SignInForm from './components/signInForm/signInForm';

function App() {
  return (

  <Router>
  <Switch>
    <Route exact path="/" component={HomePage} />
    <Route exact path="/Sign-In" component={SignInForm} />
  </Switch>
   </Router>

  );
}

export default App;

Comment: I can't reproduce that. https://codesandbox.io/s/thirsty-smoke-zx8qi?file=/src/App.js. What do you mean by *the main app renders the styles and the components at the same time*?
Comment: I want that it loads only one page, and that is the home page, but it loads the sign in form as well and its styles too
Comment: You mean it should only fetch the code for the component of the current route?
Comment: Yeah, but when I add it loads both of them at the same time, I want them separated, when I click for instance a button for Sign in, I want that it redirects me to sign in
Comment: If you want your components to be bundled and loaded independently you need to prepare them for code splitting. See https://reactjs.org/docs/code-splitting.html for details.
Comment: But you should also write your styles so that they do not interfere with each other anyways. So loading your "sign-in" styles should not break your "homepage" styles. If they do you didn't scope them properly.
Comment: Yeah the problem was with Classes, fixed it, thanks to everyone who helped out :) means a lot
Answer: In your case i thin you should use another order of your components:
<Switch>
    <Route path="/Sign-In" component={SignInForm} />
    <Route path="/" component={HomePage} />
</Switch>

Switch checks the routes from up and goes down, in your case both are "exact", so it displays both.
You don't even need exact, if you keep the correct order of paths.
Comment: The two routes can't both be `exact` matches at the same time.
Comment: @trixn I supouse you're right, but i've seen this behavior in the ```Switch``` that takes more than one component and it threats them like ```exact```, my solution was always to keep the ```/``` path always last. That's why I wrote "exact" not ```exact```
Comment: @StrahinjaBabic I think you have a misunderstanding about how your code is bundled and served to the client. Imports happen at compile time. As soon as you import any file it will be bundled into your `js` and `css`. React-Router doesn't split your code into chunks, it only renders it conditionally at run-time.
Comment: switched the order, removed the exact, but it still doesn't work, it still changes the styling of the homepage when I add the Sign In route
Comment: @StrahinjaBabic the styles are a different thing, the important thing is not make them load one above the other.
Comment: I think what OP whats is code splitting and lazy loading but i'm not sure about that ^^


Returning value of private variable

Question: My instructor said that if the class has private variables and when you want to return values of those variables via getters,  if their data types are primitive, you can just directly return their values, but if they're of reference types, a general rule of thumb is that you should almost always return Object.clone(). Then I'm wondering in what case you wouldn't need to return Object.clone()?
Comment: Don't use Object.clone. It's broken
Comment: I don't see any reason to bother casting any class to an object and back (ex: A Driver has many Cars ... why not return List directly?)
Comment: *" Then I'm wondering in what case you wouldn't need to return Object.clone()?"* What did your instructor say when you asked them?
Comment: He says so because you could change the object state by a reference to a private variable. However I think that using clone is not the correct solution. My own general rule is: if you need a getter for a private variable of a mutable reference type, you should check that your class interface is really the best solution for the problem that you are trying to solve.
Comment: Your object (that you return) should control its own mutability.  You should be able to return a reference, and the object itself should be mutable or immutable depending on the object's definition and purpose.  If there are use cases where you can have immutable versions of otherwise mutable objects you should have a means of wrapping them in an immutable facade.  And BTW, your teacher is wrong, or has not kept up with Java best practices in the past 15 years.
Comment: Someone said if you are returning a copy of reference of immutable objecrs, by definition of immutability you can't mutate the state of object but can't you overwrite memory contents by the use of reference?
Answer:
but if they're of reference types, a general rule of thumb is that you should almost always return Object.clone().

Usage of clone is discouraged. Probably you mean by creating a copy(deep) of the object and return.

Then I'm wondering in what case you wouldn't need to return Object.clone()?

Whenever you want to allow the callers of your class to modify the data of your class.
Inshort, in case of mutable objects.
Answer: If the members are immutable reference types such as String, Integer, etc... there is no need to create a copy of the instance variable in the getter method.
When an instance variable is mutable, returning the original value allows the caller of the getter method to mutate your object without calling a setter method. This is usually a bad practice, and can lead to hard to find bugs.
Answer:
...if they're of reference types, a general rule of thumb is that you should almost always return Object.clone()

You may want to make a copy, but not necessarily with Object.clone. This is typically called making a defensive copy.
Consider this class:
import java.util.List;
import java.util.LinkedList;

class Foo {
    private List<String> list;

    private String info;

    public Foo(String info) {
        this.list = new LinkedList<String>();
        this.info = info;
    }

    public List<String> getList() {
        return this.list;
    }

    public String getInfo() {
        return this.info;
    }
}

Neither getList nor getInfo makes a copy of the object it returns to the caller, they return a reference to the object. In the case of getList, that means code using the class can do this:
List<String> theList = foo.getList();
theList.add("Hi there");

...which changes the state of the list inside foo, without using any foo mutator method (getList isn't a mutating method).
In the case of getInfo, since strings are immutable, there's nothing the caller can do with the reference to the string that will change the state of foo.

Then I'm wondering in what case you wouldn't need to return Object.clone()?

If what you're returning is immutable (like String), no need to make a defensive copy.
If you want users of the class to be able to change the state of foo without using a foo method, you don't want to make a defensive copy.

If what you're returning is mutable (like a List) and you don't want the caller to be able to change it, then:

Return an immutable version of it, perhaps via a wrapper (such as from Collections.unmodifiableList).
Return a defensive copy of it.

Since copies can be expensive, you need to choose both Foo's API and how you deal with the objects it contains with an eye toward memory use and performance if there's a good chance that those will be a factor in the use of the class.

Returning value of private variable


Cannot read external hard disk folders created in Ubuntu

Question: I am experiencing a problem. I tried to plug in my external hard disk on Ubuntu. I copied in to it some folders (created on Ubuntu) with files in them.
Then, I plugged it on Windows and I wasn't able to copy or modify any of the copies folders or sub-folders. I could access my files (and modify them), but I couldn't modify or copy any of the folders or sub-folders.
I tried formatting my computer's and the external hard disk, that did not make a difference.
What should I do?
wimvds --> Thanks for your answer, first of all :) Yes! I did. I always use "Unmount" on linux as well as on windows...
Misery --> No errors are promoted during the copy process. What do you mean by saying "attributions"?? :/
Comment: Ubuntu recognizes NTFS partitions without any problem so it should work normally. Does it prompt any error while copying folders from Your HDD to Windows?

Did You try to right-click on the folders and see what attributes they have?
Comment: Did you by any chance just unplug your HDD? If so you should mount it again in Linux and click the Unmount icon (eject button icon) next to the external HDD before unplugging the device.
Comment: This question appears to be abandoned and unanswered, could you perhaps add more detail to your question? If this question no longer applies then you can either delete it or answer it yourself if you've solved the problem.  This is to help with the Ask Ubuntu Clean Up. If you feel this question is *not* abandoned, please flag the question explaining that. :)
Answer: As others have said this is file permissions.
Use Microsoft's "xcacls" (a downloadable tool by Microsoft for Windows sysadmins) because I believe it's a Windows issue. I used to see this on Windows Servers sometimes when the ACL (Access Control List) is borked.
Take ownership of everything (important) and then assign 'full control' access level.
You shouldn't have to do it each time.
Answer: What types of files are you trying to access from the windows machine? Have you tried copying those files using the windows cmd window? Try using chmod -r 777  on the folder in the hard drive. Also, have you tried zipping the folder on Ubuntu, then copying that file over to the external HDD? Also, have you done anything to the external HDD since you bought it? Maybe it has some type of copy protection mechanism.
Answer: Ok, This most likely was your problem. When the USB was created it was made to only be compatible with Ubuntu (ext 2, ext 4, or encrypted). What you need to to to fix this problem is format the USB as 'FAT' compatible with all systems. This should solve you problem.   I had this very dame problem.
Answer: It sounds like the NTFS read-only attribute has been set.  Check in Windows that the files do not have the read-only attribute set.  I've never seen this happen with an NTFS filesystem used under Ubuntu.
If it's ext2 or ext4, what ext driver have you installed to access the ext partition?
Answer: The file you copied might be encrypted or it could be what @Shannon_VanWagner posted...


Allowing VNC only for specific MAC Address?

Question: I just want to allow only for a specific MAC Address(es) to have VNC to my Ubuntu 12.10. This would be pretty cool, because I think if I use password authentication + MAC Filter = safe.
I saw I could filter for the IP´s, but how to do this for MAC´s? Any ideas or suggestions? Thank you
Answer: Actually that doesn't make it safer at all. MAC addresses can be configured ("spoofed") on most OSs for most NIC models. An attacker could sniff traffic and simply spoof your configured MAC address.
Instead make your VNC listen on loopback and SSH into the machine, using the SSH tunnel feature to connect to VNC.
If you insist on using your insecure method, iptables (netfilter) can do that:
iptables -I INPUT -m mac --mac-source 00:XX:YY:ZZ:AA:BB -j ACCEPT

this rule added to a chain with the DROP (or REJECT) default policy would accept from the given MAC only. Can be combined further to check for other parameters as well. Basically I would hand it off to a different chain if I was you, checking first on the upper layers for connections to the relevant port(s) (5900?) and then do the MAC filtering. After all you only want to filter this single service to be available from this MAC only - not any service. If you are only interested in the MAC and the port do:
iptables -I INPUT -p tcp --destination-port 5900 -m mac --mac-source 00:XX:YY:ZZ:AA:BB -j ACCEPT

Note:
-m mac requires the module mac (for netfilter), so this has to be available.

I would only use such methods to delist myself from a blacklist. For example I have configured a tar pit for SSH connection attempts (similar to what sshguard and similar programs do). Just like port knocking it could make sense to use a certain MAC as a signal to delist (i.e. remove from the blacklist) the connecting IP. But as a security mechanism by itself, no way. Too easy to fake.
Comment: @0xC0000022L - Thank you for reading the link. As long as one understands the difference I suppose it is personal choice, but, DROP has been advocated, but, IMO, REJECT is better, so trying to educate.
Comment: You should use REJECT rather then DROP, see http://www.chiark.greenend.org.uk/~peterb/network/drop-vs-reject
Comment: Hi and thank you. For now I have a question: if I use your line 'iptables -I INPUT -m mac --mac-source 00:XX:YY:ZZ:AA:BB -j ACCEPT' - is this then only for VNC or will this block other connections to the system or to the devices in the system? I mean, I have here also a Network HDD, this should be available to everybody.
Comment: @silla: please read my complete answer. The first one will accept *only* from this MAC (assuming default `DROP` policy), but for any service. The second one will accept for connections to TCP port 5900 (default for VNC) from that MAC but not affect other services (i.e. on ports other than 5900).
Comment: sry! I did not fully understand this 'port' stuff, but now I got it. VNC = 5900
Comment: @bodhi.zazen: fair point, edited that in. I think it depends on what you want to achieve. Both are perfectly fine for their respective use cases and `DROP` certainly is the more wide spread. I've been using both, depending on what I wanted to achieve.
Comment: @bodhi.zazen: yep, and it is fully appreciated :)


Android: OnClickListener on an ImageView inside a list item in a custom Listadapter

Question: I have custom Listview with a Cursoradapter. This is how my list looks like:

(source: kepfeltoltes.hu)
When I click on a list item, I want to play the recording and when I click on the info button I want to start a new Activity.
I set an onClickListener on the ImageView (called detailsIcon) and set a tag on it with the ID of the recording. The problem that I cannot retrive the tag later, other strange thing is that all the ImageView seems to have the same ID.
This is the log file, when the system populates the list:
07-15 14:33:28.238: I/System.out(27753): Setting icon (ID: 2131296298) on view (ID: -1) tag to:8
07-15 14:33:28.328: I/System.out(27753): Setting icon (ID: 2131296298) on view (ID: -1) tag to:7
07-15 14:33:28.368: I/System.out(27753): Setting icon (ID: 2131296298) on view (ID: -1) tag to:6
07-15 14:33:28.403: I/System.out(27753): Setting icon (ID: 2131296298) on view (ID: -1) tag to:5
07-15 14:33:28.418: I/System.out(27753): Setting icon (ID: 2131296298) on view (ID: -1) tag to:4
07-15 14:33:28.433: I/System.out(27753): Setting icon (ID: 2131296298) on view (ID: -1) tag to:3
07-15 14:33:28.453: I/System.out(27753): Setting icon (ID: 2131296298) on view (ID: -1) tag to:2
07-15 14:33:40.878: I/System.out(27753): Setting icon (ID: 2131296298) on view (ID: -1) tag to:1
07-15 14:33:41.238: I/System.out(27753): Setting icon (ID: 2131296298) on view (ID: -1) tag to:8

When I clcik on the imageView, it crashes with a nullpointer exception. The id = (Integer) v.getTag() gives back null. How can I solve this problem?
This is the interesting part of my CursorAdapter:
@Override
    public void bindView(View view, Context context, Cursor cursor) {

        TextView title = (TextView) view.findViewById(R.id.title);
        TextView date = (TextView) view.findViewById(R.id.date);
        ImageView btn_play_pause = (ImageView) view
                .findViewById(R.id.btn_play_pause);
        TextView duration = (TextView) view.findViewById(R.id.length);
        ImageView detailsIcon = (ImageView) view
                .findViewById(R.id.icon_details);

        rec = new RecordedObject(cursor);

        view.setTag(R.id.recording_id, rec.getId());

        ////////////////////////////////////////////////////////
        //here is the part, that is not working properly
        detailsIcon.setTag(R.id.recording_id, rec.getId());
        System.out.println("Setting icon (ID: " + detailsIcon.getId()
                + ") on view (ID: " + view.getId() + ") tag to:" + rec.getId());
        ////////////////////////////////////////////////////////

        title.setText(rec.getTitle());
        date.setText(rec.getDateReadable());

        duration.setText(MyDateFormatter.formatDuration(rec.getLength()));

        if (cursor.getPosition() == selectedRecording) {
            view.setBackgroundDrawable(context.getResources().getDrawable(
                    R.drawable.list_item_selected));
            title.setTextColor(0xFFFFFFFF);
            date.setTextColor(0xFFFFFFFF);
            duration.setTextColor(0xFFFFFFFF);
            btn_play_pause.setVisibility(View.VISIBLE);

        } else {
            view.setBackgroundDrawable(context.getResources().getDrawable(
                    R.drawable.list_item_normal));
            title.setTextColor(0xFF000000);
            date.setTextColor(0xFF000000);
            duration.setTextColor(0xFF000000);
            btn_play_pause.setVisibility(View.GONE);

        }

        detailsIcon.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                int id;
                id = (Integer) v.getTag();
                System.out.println("View (ID: " + v.getId() + ") ");
            }
        });
    }

This is my list item xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip"
    android:descendantFocusability="blocksDescendants" >

    <LinearLayout
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="5dip"
        android:padding="3dip" >

        <ImageView
            android:id="@+id/icon_details"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_menu_info_details" />

        <ImageView
            android:id="@+id/btn_play_pause"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:contentDescription="@string/play"
            android:src="@android:drawable/ic_media_play"
            android:visibility="gone" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/thumbnail"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/thumbnail"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/title_of_recording"
            android:textSize="17dip"
            android:textStyle="bold"
            android:typeface="sans" />

        <TextView
            android:id="@+id/length"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="length of recording" />

    </LinearLayout>

    <TextView
        android:id="@+id/length_old"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="5dip"
        android:gravity="right"
        android:textSize="9dip"
        android:textStyle="normal"
        android:visibility="gone" />

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"

        android:text="@string/date_of_recording"
        android:textSize="12dip" />

</RelativeLayout>

Answer: Change your OnClickListener to the following:
    detailsIcon.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            int id;
            id = (Integer) v.getTag(R.id.recording_id);
            System.out.println("View (ID: " + id + ") ");
        }
    });

When you call detailsIcon.setTag(R.id.recording_id, rec.getId()); you are setting the key for the tag to R.id.recording_id. You must use this key to retrieve the tag from the view. If you were trying to set the id of the view you can call detailsIcon.setId();.


How to solve large modular equations?

Question: I am trying to code a modular equation solver, say given an equation,
$x^2=180345$ and the modulo is 8, then we can solve it like this-->

$x^2 = 180345 \bmod 8 = 1 \bmod 8$
Now, x can have only the following set of values mod 8:
{0, 1, 2, 3, 4, 5, 6, 7}
You can verify that only x = 1, 3, 5, 7 satisfy x^2 = 1 mod 8 and the
other values do not.

A code for this will be as simple as-->
<code>for i in range(1,8):
  if( (i**2) % 8 == 1):
    print(i)
</code>
But I am facing problem when it comes to large values.
for example, say this is the case now
$x^{2023}=60272843869801735644577066673$ and modulo is $19806040628566084345385967582$
With the same code that I mentioned it will take a lifetime to solve this equation, but when I use this online modular equation solver it is performing this operation within seconds. Can someone tell me what is the algorithm that they are using?
Comment: Is this an extension of https://math.stackexchange.com/questions/4024008/how-to-solve-for-x-in-modular-arithmetic-when-the-equation-has-exponent?rq=1?
Comment: Check the algorithm section of https://en.wikipedia.org/wiki/Discrete_logarithm, baby step/giant step is quite a popular one to start with.
Comment: @zwim The OP's problem is taking $k$'th roots, not discrete logarithms.
Answer: You cannot solve this congruence in a naive way.
I've been trying to implement such algorithms too,
because they are often quite useful in various algorithmic problems and contests.
Probably they are using the Tonelli-Shanks algorithm in that calculator.
Then... if the modulo is not a prime number, you will need to do further work
probably by using the Chinese remainder theorem
Try to implement the algorithm for a prime modulo, that's a good start.
But you do need to know some elementary number theory to go through this.
Not sure if you do. If you don't then you'd better go through some elementary number theory book first. Maybe some book like this one Elementary Number Theory

How to solve large modular equations?