Select duplicates from a single row with criteria from two tables

Question: I have two tables:
+---------+-----------------+----------+----------+----------+---------+
| TrackId |       URI       | ArtistID |  Title   | AlbumID  | BitRate |
+---------+-----------------+----------+----------+----------+---------+
|  1      | /home/music/... |   234    | atune    |  8958223 |   192   |
|  2      | /music/uri1/... |   427    | goodsong |  222     |   192   |
|  3      | /music/uri2/... |   427    | goodsong |  222     |   128   |
|  4      | /music/uri3/... |   427    | goodsong |  222     |   160   |
|  5      | /home/music/... |   427    | goodsong |  333     |   128   |
|  6      | /home/music/... |   522    | another  |  3458859 |   128   |
+---------+-----------------+----------+----------+----------+---------+

and
+----------+------------+
| AlbumID  | AlbumTitle |
+----------+------------+
|  8958223 |   titleA   |
|  222     |   titleB   |
|  333     |   titleC   |
|  3458859 |   titleD   |
+----------+------------+

Simply put, what I want is this:
+---------+-----------------+----------+----------+----------+------------+---------+
| TrackId |       URI       | ArtistID |  Title   | AlbumId  | AlbumTitle | BitRate |
+---------+-----------------+----------+----------+----------+------------+---------+
|  3      | /music/uri2/... |   427    | goodsong |  222     |   titleB   |   128   |
|  4      | /music/uri3/... |   427    | goodsong |  222     |   titleB   |   160   |
+---------+-----------------+----------+----------+----------+------------+---------+

This is an attempt to remove duplicates that have the:

same title
same artist id
different track id
the non-highest bitrate duplicates
same album name from the album table

while not returning the entry with the highest bitrate duplicate
I've asked a very similar question here: Select duplicates from a single row?
The solution to that was:
SELECT c1.*
  FROM CoreTracks c1
      ,(SELECT Title, ArtistID, MAX(FileSize) AS maxFileSize, MAX(BitRate) maxBitRate
          FROM CoreTracks
          GROUP BY Title, ArtistID) c2
  WHERE c1.Title = c2.Title
    AND c1.ArtistID = c2.ArtistID
    AND (c1.FileSize != c2.maxFileSize AND c1.BitRate != c2.maxBitRate)

...but I cannot seem to wrap my head around dealing with another table this time around.
Comment: And where are you use your second table? Can you explain your problem a bit more detailed.
Comment: But the bit-rates are different!
Comment: MySQL and SQLite are different databases - which one is correct?  Databases share functionality, but it's not 100% (or there wouldn't be a need to distinguish).
Comment: I'm using SQLite3.  I'm looking for a general SQL solution but if a particular solution works only in SQLite for some reason, that would still solve this I suppose.
Comment: @HamletHakobyan a very astute point.  I've corrected my question to demonstrate the need for the second table.
Answer: second table isn't relevant in your use case, since u have the FK reference to AlbumId in the first table
select t.*, a.AlbumTitle
from Track t
inner join (
    select max(BitRate) as BitRate, ArtistId, Title, AlbumId
    from Track
    group by ArtistId, Title, AlbumId ) b
  on t.ArtistId = b.ArtistId and t.Title = b.Title and t.AlbumId = b.AlbumId and t.BitRate < b.BitRate
inner join Album a
      on t.AlbumId = a.AlbumId

Comment: Ah this is a good point.  It's my mistake that I failed to express that I also wanted the album name returned.
Comment: Thank you pjacko for your response!  I gave it a try and it's yet another excellent way of getting this to work.  Much appreciated.
Answer: Give this a try:
SELECT c1.*
FROM CoreTracks c1
LEFT JOIN
     (SELECT Title, ArtistID, AlbumID, MAX(BitRate) maxBitRate
      FROM CoreTracks
      GROUP BY Title, ArtistID, AlbumID) c2
    ON c1.Title = c2.Title
    AND c1.ArtistID = c2.ArtistID
    AND c1.AlbumID = c2.AlbumID
    AND c1.BitRate = c2.maxBitRate
WHERE c2.Title IS NULL

Here is the SQL Fiddle.
--EDIT
To add the Album Title:
SELECT c1.*, a.AlbumTitle
FROM CoreTracks c1
JOIN Albums a on c1.AlbumId = a.AlbumId
LEFT JOIN
     (SELECT c.Title, c.ArtistID, c.AlbumID, MAX(c.BitRate) maxBitRate
      FROM CoreTracks c JOIN Albums A ON c.AlbumId = a.AlbumId
      GROUP BY Title, ArtistID, AlbumID) c2
    ON c1.Title = c2.Title
    AND c1.ArtistID = c2.ArtistID
    AND c1.AlbumID = c2.AlbumID
    AND c1.BitRate = c2.maxBitRate
WHERE c2.Title IS NULL

And the updated fiddle.
Good luck.
Comment: I updated my question as I miserably failed to mention I wanted the album name returned x)  That's why I needed that second table.
Comment: This is excellent.  This helped me break a threshold in comprehension.  I feel like Neo coming out of the Matrix and knowing Kung Fu at long last.  Thank you.


Can't draw shapes in java

Question: I'm pretty sure that this code should draw an oval on the screen next to the word text. However, the word is all the appears, the rest of the screen is black. This seems to happen with any primitive shape. I'd like to think I know java fairly well, but graphical things have been really confusing to me. I'm at my wit's end with this and any help would be appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.util.ArrayList;

public class Game extends JPanel implements Runnable {
    int W = 4;
    int H = 3;
    int windowSize = 300;
    boolean running;
    static boolean drawHitBoxes = true;
    int FPSLimit = 30;

    private Thread thread;
    private BufferedImage buffer;
    private Graphics2D g;

    public Game() {
        super();
        setPreferredSize(new Dimension(W * windowSize, H * windowSize));
        setFocusable(true);
        requestFocus();
    }

    public void addNotify() {
        super.addNotify();
        if (thread == null) {
            thread = new Thread(this);
            thread.start();
        }
    }

    public void run() {
        running = true;

        buffer = new BufferedImage(W * windowSize, H * windowSize,
                BufferedImage.TYPE_INT_RGB);
        g = (Graphics2D) buffer.getGraphics();

        // citList.add(new Citizen(200, 200, "Joe"));

        long startTime;
        long waitTime;

        long frameTime = 1000 / FPSLimit; // /How long one frame should take
        long currentFrameTime;

        while (running) {
            startTime = System.nanoTime(); // record when loop starts

            gameUpdate();
            gameRender();
            gameDraw();

            // Calculate how long the current frame took
            currentFrameTime = (System.nanoTime() - startTime) / 1000000;
            waitTime = frameTime - currentFrameTime;

            try {
                Thread.sleep(waitTime);
            } catch (Exception e) {
            } // Sleep for the remaining time
        }
    }

    private void gameUpdate() {
        // for(Citizen i:citList){i.update();} //Update citizens
    }

    private void gameRender() {
        g.setColor(Color.WHITE);
        g.drawOval(100, 100, W - 100, H - 100);
        g.setColor(Color.WHITE);
        g.drawString("Text.", 100, 100);
        System.out.println("Drawing white box.");

        // for(Citizen i:citList){i.draw(g);} //Draw citizens
    }

    private void gameDraw() {
        Graphics gMain = this.getGraphics();
        gMain.drawImage(buffer, 0, 0, null);
    }
}

Comment: Please see edit to answer. You likely want: `g.drawOval(100, 100, W * windowSize - 200, H * windowSize - 200);`
Comment: My god, I can't believe I did that and couldn't see it. This is horribly embarrassing. Thanks.
Answer: g.drawOval(100, 100, W-100, H-100);

W is 4 and H is 3, and so since W-100 is -96 and H-100 is -97, making your 3rd and 4th parameters negative, which doesn't make sense for the Graphics#drawOval(...) method since how can an oval's width and height be negative. Solution: be sure to use only positive parameters that make sense when calling this method. Probably what you want is:
 // but you'll also want to avoid magic numbers such as 100 & 200 as well
 g.drawOval(100, 100, W * windowSize - 200, H * windowSize - 200);

As an aside, myself, I prefer using passive graphics, drawing in paintComponent and am fearful whenever I see Swing code that has a Graphics or Graphics2D instance field.. Also your code looks to not obey Swing threading rules as it appears to be making Swing calls off of the Swing event thread.
Answer: I think it's better to create the paintComponent method and transfer your gameRender and gameDraw there and in your while loop replace their method calls with repaint(). Here is the code that works.
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.util.ArrayList;

public class Game extends JPanel implements Runnable {
    int W = 4;
    int H = 3;
    int windowSize = 300;
    boolean running;
    static boolean drawHitBoxes = true;
    int FPSLimit = 30;

    private Thread thread;
    private BufferedImage buffer;
    private Graphics2D g;

    public Game() {
        super();
        setPreferredSize(new Dimension(W * windowSize, H * windowSize));
        setFocusable(true);
        requestFocus();
    }

    public void addNotify() {
        super.addNotify();
        if (thread == null) {
            thread = new Thread(this);
            thread.start();
        }
    }

    public void run() {
        running = true;

        buffer = new BufferedImage(W * windowSize, H * windowSize,
                BufferedImage.TYPE_INT_RGB);
        g = (Graphics2D) buffer.getGraphics();

        // citList.add(new Citizen(200, 200, "Joe"));

        long startTime;
        long waitTime;

        long frameTime = 1000 / FPSLimit; // /How long one frame should take
        long currentFrameTime;

        while (running) {
            startTime = System.nanoTime(); // record when loop starts

            gameUpdate();
            //gameRender();
            //gameDraw();
            repaint();

            // Calculate how long the current frame took
            currentFrameTime = (System.nanoTime() - startTime) / 1000000;
            waitTime = frameTime - currentFrameTime;

            try {
                Thread.sleep(waitTime);
            } catch (Exception e) {
            } // Sleep for the remaining time
        }
    }

    private void gameUpdate() {
        // for(Citizen i:citList){i.update();} //Update citizens
    }

    private void gameRender() {
        g.setColor(Color.WHITE);
        //g.drawOval(100, 100, W - 100, H - 100);
        g.drawOval(100, 100, 100, 100);
        g.setColor(Color.WHITE);
        g.drawString("Text.", 100, 100);
        //System.out.println("Drawing white box.");

        // for(Citizen i:citList){i.draw(g);} //Draw citizens
    }

    private void gameDraw(Graphics gMain) {
        //Graphics gMain = this.getGraphics();
        gMain.drawImage(buffer, 0, 0, null);
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        gameRender();
        gameDraw(g);
    }
}

As point out by @Hovercraft in his answer, the W-100 and H-100 in the code `g.drawOval(100, 100, W - 100, H - 100);' will yield negative numbers. I don't know exactly what values do you want to result in there but I just replace them with 100 just to remove the bug.
Comment: I like that better, 1+. Please see [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html) for more on `update()` usage in Swing and AWT.
Comment: Unlike AWT programs, you should almost *never* call `updateUI()` on Swing components, unless you're doing so after changing the Look & Feel.
Comment: @HovercraftFullOfEels why is it? Does this create delays?
Comment: @HovercraftFullOfEels. What's the best way to trigger the protected void paintComponent(Graphics g) on this example?
Comment: I updated my answer and change updateUI() to repaint()

Can't draw shapes in java


ESR rule for mongoDB: What if I want to sort on my range index?

Question: I am planning to include indexes to make my mongodb queries faster, currently working on Springboot.
I have variables userType and creationStamp (date and time in epoch milli while saving the document in collection). Currently my collections have no indexes and all queries have these two common variables, default sorting being done on
creationStamp-
which makes the query very slow as all its values are unique.
I have to introduce a new variable date (which won't have timestamp). My idea is to use a compound index with order {userType, date} as range follows equality but I'm not sure how sorting would be done in this case.
Are the documents sorted by the order they are saved in the collection?
If not, how should I approach this problem if I want the sorted order to be in descending order of date and time of getting saved in the collection?
Can I just fetch the documents on basis of userType and date but sort on basis of creationStamp?
Thank you.
Comment: What is the specific query (or queries) that you will be running? I can't figure out exactly what you plan to use `date` for, particularly if it is just a subset of the `creationStamp` field
Comment: Hi, these queries are to fetch documents from collections using filters and return sorted results based on creationStamp. Subset common to all these filtering queries is userType and range of date. I wanted to add date so that I can index on it as creationStamp would be unique for every record
Comment: Thanks but it's still not clear to me what benefit or value `date` provides. You mention filtering on a range of date, is that not possible with `creationStamp` directly? Said another way, I think you are going to create an indexing problem by adding that field when it wouldn't otherwise exist with the other two fields.
Comment: creationStamp would be unique for each record. Filtering on it would result in looping through every record for that user type while there would be records under each date making it easier to pick up- at least this is my understanding. Anyway, I ran explain in mongodb compass and it took 35ms w/o indexing while it takes up to a minute sometimes to show on UI, so this must be a different problem. Thank you
Answer: I think there are a few misconceptions which are making the question more complex than it needs to be. Let's start with the latest comment:

I ran explain in mongodb compass and it took 35ms w/o indexing while it takes up to a minute sometimes to show on UI, so this must be a different problem.

We need to take care here to make sure that we are comparing apples to apples. One of the responsibilities of explain plans is to report how the database will execute a query. But they don't always actually run that plan as part of the command. If there are no indexes on the collection then there aren't any options for execution apart from doing the collection scan.
Relatedly, even when explain is run at an elevated verbosity to gather execution statistics it is still not representative of the overall work that is performed in order to populate a UI with information from the database. Notably absent in that regard is the time it takes to transmit the information across the network from the database to the client.
I doubt that your system is able to scan and sort 5 million documents in 35 milliseconds. Even if so, that's not a scalable approach long term.

... default sorting being done on creationStamp- which makes the query very slow as all its values are unique.
I wanted to add date so that I can index on it as creationStamp would be unique for every record
creationStamp would be unique for each record. Filtering on it would result in looping through every record for that user type while there would be records under each date making it easier to pick up- at least this is my understanding

You keep focusing on the fact that the creationStamp field effectively contains values that are effectively unique for each document in the collection like it is a bad or inefficient for query execution, but I don't think that's really the case.
Keep in mind that an index is nothing more than an ordered data structure. Moreover unless it is a partial index then it will have an entry for every single document in the collection. The most notable consideration that the cardinality of the indexed field has here is in regards to the size of the index. Fewer distinct values typically result in prefix compression being more effective, but that consideration is not pertinent to your question about performance.
What the database is going to do is walk the index from the root down to leaf nodes, and then sequentially read those leaf nodes until it reaches the end of its range. This is going to happen the same whether you are using a date field that only has granularity of a day or if you are using something much more precise. It is the same amount of work both ways.
Furthermore, you want to be able to use the index to sort your query results. If you don't do this then the database will have to do much more work in order to execute your query. The only way to do this is to have the field that you are sorting on as a key in the index definition.

Recommendation
All of this said, here is what I would suggest. Create an index on { userType: 1, creationStamp: 1} and generate the .explain("executionStats") output for your query. The executionStats section should show that the number of documents returned is the same as the number of index keys examined as well as documents examined. There should also not be a SORT stage present. If so, then you have a perfectly optimized query. If not then you should create a new question with that explain output and we could explore it further.
Comment: Oh and to clarify - the suggestion here is to _not_ have an additional/derived `date` field (just in case that wasn't clear above). Looking forward to hearing the results!


why the same program slower in linux 2.6.32 than 2.6.18?

Question: I wrote a program, which is so simple.
<code>void do_test() {
    const char *s = "http://";
    int i = 0;
    for(; i<100000; ++i) {
        const char *p = s;
        while(*p != '/') {
            ++p;
        }
    }
}
int main() {
    int i = 0;
    for(; i<100; ++i) {
       do_test();
    }
    return 0;
}
</code>
run this code 100 times,will lead the difference.it costs 1.29s in my 64 bit server with kernel linux 2.6.32, but it just costs 1.23s in my 32 bit server with kernel 2.6.18.
Comment: Could it be that your slower machine is just tired and needs some coffee as a pick-me-up?
Comment: Is it reliably slower, that is, it's always about 60 ms slower?
Comment: In the title you are comparing a program on two kernel versions, but in the question you are comparing a program on two different machines with two different kernel versions.
Comment: Intel(R) Xeon(R) CPU           E5620  @ 2.40GHz. the cpu is the same.
Comment: Why not compile as 32-bit and compare?
Answer: Since the hardware is different, the difference in performance might have (and very probably has) nothing to do with the kernel.
Moreover, I would think of compiler optimizations, CPU architecture, etc. well before blaming the kernel...
Comment: Always blame the kernel... never blame yourself! ;-)
Comment: @FiddlingBits: Why blame yourself if you can blame a compiler bug, language defect, poor library implementation or high air pressure?
Comment: so would you give me some suggetions to find the reason?
Answer: Even if two computers have the same specs the hardware may not be strictly identical, nanoscopic differences during the manufacturing of the processors could lead to this small difference (~1%)
Comment: The timings are ~5% different. Thermal environment could have a larger impact. Since the processor base frequency and microarchitecture are the same, manufacturing variation would only affect turboboosting. Even different cores within the same chip could have detectable differences.


How should I wire 2 switches that control 1 light and 1 receptacle?

Question: Last winter I pulled power into an attic. I put in a 2 gang box with 2 switches. One switch controls a light in the attic and works fine. The second controls an outlet and I realized months later that power is always on, the switch has no affect.
I had used some wiring books and made up the wiring diagram myself, so I'm guessing I have something wired incorrectly? I have black, white and ground in the power coming in and power to light and black, red, white and ground in the power to the switched outlet. If I need to pull the outlet to diagram how it's wiring I can do that. Here is what I have in the box for the switches:
EDIT: I'd like the whole outlet to work on the switch, nothing continuous.
Edit to add a photo of why I wired the receptacle the way I did. Changing it to the solution check-marked below worked.
Comment: Also you don't splice (connecting of 2 or more wires)outside of the box all slipices should be done with 8inches of wire so your connections can have about 6" of wire left over when done with slipices.
Answer: You forgot to break the tab off on the outlet.
You want the red line to control one half the duplex?   And the Black to feed the other continuously?   There's a little copper tab between the hot screws that you remove to do this.
Answer: If you had intended for the outlet to be switched then the outlet should have been wired to the red switched wire going to the "hot" side of the outlet. The "neutral" side of the outlet would have been connected to the white wire. In this case the black wire in the outlet box should have been simply wire nutted to cover its end and pushed to the back of the box whist not being connected to anything.
The black wire could come into play if the outlet was a duplex one (two outlets). The usage would be that one of the two would be switched and the other powered all the time. To wire this up you would remove the breakaway tab on the "hot" side of the outlet. Leave the breakaway tab in place on the "neutral" side of the outlet. The black wire would connect to the always on outlet in its "hot" side. The red wire would connect to the switched outlet on its "hot" side. Finally, like before, the white wire would  connect to the common "neutral" side of the outlet.
Comment: Thank you! Switching the wires in the receptacle box worked. I had wired it based on a diagram in Stanley Complete Wiring, page 189 which I added on to the question above.
Comment: That's what I said.


Uninstall NVidia drivers?

Question: I've upgraded from 10.04 to 10.10 (in order to be able to upgrade to 11.04).
It seems like the current graphics drivers are incompatible with the latest kernel I have.
I don't know if I have installed drivers only from apt or if I have downloaded. I think it's only apt thou.
How do I uninstall all Nvidia drivers and revert to the default drivers? I've used at least 2 different multi monitor setup utilities, but it was last year so I don't remember much.
What config files do I need to change so that the default drivers works?
Answer: Try renaming the xorg.conf file and reboot:
sudo mv /etc/X11/xorg.conf /etc/X11/xorg.conf.nvidia

To remove the drivers:
sudo apt-get purge nvidia-settings nvidia-current

Uninstall NVidia drivers?


Fourier Series - Periodicity

Question: I don't know if I'm doing something wrong in this exercise.
$f(t)=\pi-t$, if $0<t<\pi$
$f(t)=0$, if $\pi<t<2\pi$
I have to find the Fourier Series of $f(t)$

I define the Fourier Series like this:
T: period
$$f(t)=\frac{a_0}{2}+\sum_{n=1}^{\infty}[a_n.\cos{\frac{2\pi nt}{T}}+b_n.\sin{\frac{2\pi nt}{T}}]$$
where ($\alpha$ is a real number)
$$a_0=\frac{2}{T}.\int_{\alpha}^{\alpha+T}f(t)dt$$
$$a_n=\frac{2}{T}.\int_{\alpha}^{\alpha+T}f(t).\cos{\frac{2\pi nt}{T}}dt$$
$$b_n=\frac{2}{T}.\int_{\alpha}^{\alpha+T}f(t).\sin{\frac{2\pi nt}{T}}dt$$
Here's the problem: I think that $T=4\pi$, because I extend the function $f(t)$ from $-2\pi$ to $2\pi$, so I have this:
$$a_0=\frac{1}{2\pi}.\int_{-2\pi}^{2\pi}f(t)dt=\frac{1}{\pi}.\int_{0}^{2\pi}f(t)dt$$
$$a_n=\frac{1}{2\pi}.\int_{-2\pi}^{2\pi}f(t).\cos{\frac{nt}{2}}dt=\frac{1}{\pi}.\int_{0}^{2\pi}f(t).\cos{\frac{nt}{2}}dt$$
$$b_n=\frac{1}{2\pi}.\int_{-2\pi}^{2\pi}f(t).\sin{\frac{nt}{2}}dt=\frac{1}{\pi}.\int_{0}^{2\pi}f(t).\sin{\frac{nt}{2}}dt$$
But other people took $T=2\pi$ and they have:
$$a_0=\frac{2}{2\pi}.\int_{0}^{2\pi}f(t)dt=\frac{1}{\pi}.\int_{0}^{2\pi}f(t)dt$$
$$a_n=\frac{2}{2\pi}.\int_{0}^{2\pi}f(t).\cos{nt} dt=\frac{1}{\pi}.\int_{0}^{2\pi}f(t).\cos{nt} \mathrm{d}t$$
$$a_n=\frac{2}{2\pi}.\int_{0}^{2\pi}f(t).\sin{nt} dt=\frac{1}{\pi}.\int_{0}^{2\pi}f(t).\sin{nt} \mathrm{d}t$$
Look that he took the integral between 0 and $2\pi$ and I took it from $-2\pi$ to $2\pi$
Did I do something wrong? Why this he took the period from 0 to $2\pi$? $f(t)$ is not a periodic function?
Thanks!
Answer: It does not matter whether we choose to extend $f$ so that the period is $2 \pi$ or $4 \pi$. Your problem is a simplification you made when determining the coefficients.
$$a_n = \frac{2}{4 \pi} \int_{-2 \pi}^{2\pi} f(t) \cos{\frac{n t}{2}} \ dt \neq \frac{1}{\pi} \int_{0}^{2\pi} f(t) \cos{\frac{n t}{2}} \ dt,$$ because when you extend your function $f(t)$ to the interval $[-2 \pi, 2 \pi]$ it is NOT an even function. So, you must compute the integral over the whole interval and not make this incorrect simplification.
What you will find is that when $n$ is odd, you will get $a_n = b_n = 0$ and that when $n$ is even you will get the same answer as you would get by thinking of the function as only having a period of $2 \pi$
Comment: The function is not even, but the integrals over $[-2\pi,0]$ and over $[0,2\pi]$ are the same. This justifies the simplification. In particular, your inequality above is wrong for the function in the OP's example.
Comment: @fonini That's what I thought at first too, but then I checked and that's not right. When $n$ is odd you get that the the integral over $[-2\pi,0]$ is the negative of the integral over $[0, 2\pi]$.
Comment: Ops :\ that's true.
Comment: @fonini Ya its because when $n$ is odd the sine and cosine period are adjusted such that they take on the opposite sign in $[-2 \pi, -\pi]$ as they do in $[0, \pi]$.
Comment: @KevinDriscoll so you say that, if the function is even or odd, I can do what I did (the integral from $-2\pi$ to $2\pi$ but, if it's NOT even or odd, I have to write the integral from 0 to T. Are you saying that? Thanks !!!
Comment: @KevinDriscoll here I have a function that is odd and it's not like you said. Look:

$f(x)=0$ if $0<x<T$ and

$f(x)=x$ if T<x<2T

I suppossed to take Period=4T, like you said, but I have to take Period=2T. Why?
Comment: @Juan I don't think I understand your question, but regardless that function is NOT odd anyway. Again, it doesn't matter if you take the period to be $2T$ or $4T$.
Answer: i get these: $a_0 = \frac{1}{2\pi} \int_0^\pi (\pi - t)\, dt = \frac{\pi}{4}$
and $a_n = \frac{1}{\pi}\int_0^\pi (\pi - t)\cos nt \, dt = \frac{2}{\pi n^2}$ if $n$ is odd and $0$ otherwise. same way i get $b_n = \frac{1}{\pi}\int_0^\pi (\pi - t)\sin nt \, dt= \dfrac{1}{n}.$
so the fourier series looks like $$f \simeq\dfrac{\pi}{4} + \sin t + \dfrac{2}{\pi}\cos t + \cdots $$
Answer: $f$ is only defined in an interval, so that $f$ can be made periodic by extending it to the entire real line (or just to $[-2\pi,2\pi]$ if you prefer). In the end, the period $T$ of $f$ will be $2\pi$ because that's the length of the original interval ($[0,2\pi]$) in which $f$ was defined.
Your calculations are correct, because $4\pi$ is also a period of $f$, altough it is not the fundamental period (the smallest positive number that can be called "a period" of $f$). So both of the following are correct?
$$f(t)=\frac{a_0}{2}+\sum_{n=1}^{\infty}[a_n.\cos{\frac{2\pi nt}{T}}+b_n.\sin{\frac{2\pi nt}{T}}]$$
$$f(t)=\frac{\tilde a_0}{2}+\sum_{n=1}^{\infty}[\tilde a_n.\cos{\frac{2\pi nt}{\tilde T}}+\tilde b_n.\sin{\frac{2\pi nt}{\tilde T}}]$$
Where $a_n$ and $\tilde a_n$ (etc) are the coefficients from both formulas you posted (one considering $T=2\pi$, and the other $\tilde T=4\pi$).
Yes, they are the same. What's happening is that $\tilde a_n=\tilde b_n=0$ whenever $n$ is odd. You can check that this makes the formulas equal.
EDIT: the calculations are not entirely correct, because, as mentioned in Kevin Discroll's answer, you cannot make the simplifications for reducing the integral over $[-2\pi,2\pi]$ to twice the integral over $[0,2\pi]$ (you could make this simplification if the integrand was just $f(t)$, but you can't for the integrand $f(t)\cos nt/2$; see the comments in his answer). My answer above is only true if you define: $$\tilde a_n = \frac1{2\pi}\int_{-2\pi}^{2\pi}f(t)\cos (nt/2) dt$$ and likewise for $\tilde b_n$.
Comment: Thanks!!! I always used that the integer goes from -T/2 to T/2, but here it's from 0 to T. How can I know if I have to use $2\pi$ or $4\pi$? The exercise with $T=2\pi$ was much more easy. Thanks!
Comment: You can just define always $T$ to be the length of the interval on which $f$ is defined. In you example, $f$ is defined on an interval of the form $[0,T]$, instead of $[-T/2,T/2]$, which is not bad or wrong at all, it's just another convention. If you draw the graph of $f$ from in the interval $[-2\pi,2\pi]$, you'll see that the graph repeats itself (the $[-2\pi,0]$ and $[0,2\pi]$ pieces look exactly the same). This repetition means that there was no need to consider $T=4\pi$; you could have just considered $T=2\pi$.

Fourier Series - Periodicity


What is best practice for flagging or removing a tag on a question?

Question: I was just reviewing a question with three tags. The latter two tag appear to be new and vague.  I have been cautiously editing tags, usually to add a tag where needed. I am not sure about deleting one.  Is it appropriate to do so?  (I don't even know if I have the permission to do so; I'll ask this on meta as well.)
Answer: It is perfectly fine to remove a tag that is not much helpful, or that should not be used. While you are editing the question, check there isn't anything else that needs to be corrected: spelling, grammar, and everything else that can make the question clearer without changing its meaning.
You cannot edit every post, until your reputation is not at least 2,000. Your edits will be queued, and approved.


Securing brick, rock or pavers on artificial turf

Question: I want to build a backyard putting green. The company I am going to buy the turf from (Garden-mark) says to lay the artificial grass over prepped ground as if laying pavers and secure the turf with spikes.
I would like to add rocks or paver edges (for the golf ball and addition hold down for the turf) and obstacles (like a tunnel), something like this:

How would I secure the rock or pavers to each other?  To the turf?
Answer: This is somewhat discretionary, but either mortar of the correct type or landscape adhesive should do to bond the stones. I'd think gravity would be adequate to hold it in position on the turf, or you'd install a concrete footing, bond the stone to that, and install turf around it.
Depending on how larger your stones or edgers are you may not need anything.
Answer: We might ask "How are pavers normally secured" and the answer for most parts of this planet is "gravitationally" (there are probably some exceptions in absurdly high wind areas, but "not using pavers" is the most likely approach in those limited areas.)
The turf needs to be secured with spikes because it's not a heavy thing, like a rock or slab of cement (aka paver.) Actual heavy things, particulary low, flat, wide ones, tend to stay where put unless acted on by large outside forces that are uncommon in the extreme (and gluing your rocks down may not help if an F5 tornado comes through, anyway.)


Change state of member variable in React not working

Question: I have a class Box2 which I have made an instance of in Box1
Box1 just renders the instance which is has of Box2 however using setState for that instance that I have it doesnt change
import React from 'react';
import ReactDOM from 'react-dom';

class Box2 extends React.Component{
    constructor(props){
        super(props);
        this.state={text:"No"};
    }
    render(){
        return(

            {this.state.text}

        );
    }
}

export default class Box1 extends React.Component{
    Elements=[];
    constructor(){
        super();
        this.Elements[0]=new Box2();
        this.Elements[0].setState({text:"YES"});
    }
    render(){
        return(

        {this.Elements.map((e)=>e.render())};

        );
    }
}

Answer: You can not change state of your child components. Instead you should use props:
class Box2 extends React.Component{
  render(){
    return(

        {this.props.text}

    );
  }
}

export default class Box1 extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isBox2Yes: true,
    };

    this.onBoxClick = this.onBoxClick.bind(this);
  }

  onBoxClick() {
    this.setState({ isBox2Yes: !this.state.isBox2Yes });
  }

  render(){
    return(

        <Box2
          text={this.state.isBox2Yes ? 'YES' : 'NO'}
          onClick={this.onBoxClick}
        />

    );
  }
}

Comment: I would like to have my class be composed of several elements of other classes and update given an event trigger and render differently based on that
Basically,  onClick it would change the text from "NO" to "YES"
How would I go about doing that?


How to find the path through a dotted (station) path, like a metro map for example

Question: This is the map of Metro stations, each vertical line is a line with different stations, and horizontal lines represent transferring station where you can change your line and get to another one.

I was trying to make a program that given a starting station and an ending station would return the number of stations required for the trip. I started by creating a dictionary containing the there lines and their stations numbered in order, but it ended with a lot of if statements and I couldn't figure out how to make it move from a line to another using the line-switching stations. I thought of using nodes, and Dijkstra's algorithm, but I am not sure if it would work.
I don't know what I should look for, or which algorithm I should try. Is Dijkstra's algorithm suitable or is it more concerned about the distance between the nodes?
Comment: Any derivative of Breadth First Search will work
Answer: You can set every distance between nodes to 1 and then Dijkstra's algorithm will apply here.


Qt moveToThread works only the first time

Question: I'm creating an application performing an infinity task, so I decided to manage it with a QThread. On specific condition, this thread should spawns a temporary therad in order to perform some computation. The problem is that this works only the first time, while the second time I get this error:
QObject::moveToThread: Current thread (0xd29078) is not the object's thread (0x6e000df0).
Cannot move to target thread (0x6e002c68)

In the main I initialized the class and moved it in a QThread.
AccelerometerBuffer accBuffer;
QThread *accelerometerThread = new QThread;
accelerometerThread->setObjectName("AccelerometerThread");
accelerometerThread->setParent(&accBuffer);
accBuffer.moveToThread(accelerometerThread);
QObject::connect(accelerometerThread,SIGNAL(started()),&accBuffer,SLOT(readAccelerationData()));
QObject::connect(accelerometerThread,SIGNAL(finished()),accelerometerThread,SLOT(deleteLater()));
accelerometerThread->start();

In readAccelerationData, after condition, I should call another SLOT (saveData()) in the AccelerometerBuffer class and so the temporary thread should be spawned by the accelerometerThread.
if(condition){
    QThread* thread = new QThread;
    QThread::currentThread()->moveToThread(thread);
    connect(thread,SIGNAL(started()),QThread::currentThread()->parent(),SLOT(saveData()));
    connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater()));
    thread->start();
}

The first time that the condition occurs, everything works fine, saveData is correctly executed.
The following times, instead, I get the error and I don't understand the reason.
Answer: You can only moveToThread from the owning thread. As soon as your move to another thread, the same call will no longer be able to do anything.
From https://doc.qt.io/qt-5/qobject.html#moveToThread

Warning: This function is not thread-safe; the current thread must be same as the current thread affinity. In other words, this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread.
Comment: So, the second time the accelerometerThread "lives" in the context of the temporary thread and cannot perform another `moveToThread`, right?
Comment: Not exactly sure what you mean @Cristiano
Comment: After moving the accelerometerThread to the temporary thread and as you said, current thread must be same as the current thread affinity, but I changed it and so I get the error. This is my main doubt


Using Vue.js with vue-socket-io

Question: I am trying to use vue-socket-io with Vue.
I can emit messages from client to server without a problem. But, from server to Vue app, I can't receive anything.
What am I doing wrong?
main.js:
import Vue from "vue";
import App from "./App.vue";
import router from "./router";

// socket io
import * as io from "socket.io-client";
import VueSocketIO from "vue-socket.io";

Vue.use(
  new VueSocketIO({
    debug: true,
    connection: io('http://localhost:3000'), // options object is Optional
  })
);

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  vuetify,
  render: (h) => h(App),
}).$mount("#app");

App.vue:
<template>
  <v-app>

Test

  </v-app>
</template>

Node server:
...
const server = http.createServer(app);
const io = require("socket.io")(server);
server.listen(port);
server.on("listening", () => {
  const addr = server.address();
  console.log(`Mágica acontecendo em  ${addr.address} na porta ${addr.port}`);
});

io.on("connection", async function (socket) {
    console.log("conectado:" + socket.id);
    socket.broadcast.emit("user-connected", socket.id);
});

Answer: Using socket.io with Vue.js and Node.js full example:
In your backend (Node.js):
//setting up sockets
const app = express()
const server = http.createServer(app)
const io = require('socket.io')(server)
io.on('connection', (socket) => {
  socket.on('sendUpdateUsers', function(data) {
    io.emit('usersUpdate', data)
  });
})

Sending a socket update from the component:
import io from 'socket.io-client';

data() {
 return {
  socket: io(),
  users: []
 }
},
methods: {
 this.socket.emit('sendUpdateUsers', {users: this.users})
}

Listening to socket in the component:
import io from 'socket.io-client';

data() {
 return {
  socket: io(),
  users: []
 }
},
created() {
  this.socket.on('usersUpdate', (data) => {
   this.users = data.users
  })
}

Answer: I had this issue earlier and fixed it with listener.subscribe:
mounted() {
    this.sockets.listener.subscribe("user-connected", (data) => {
        debugger;
        console.log(data);
        this.$socket.emit("users");
    });
    this.$socket.emit("users");
    this.sockets.listener.subscribe("users", (data) => {
        console.log("users", data);
    });
},

Not sure if it'll work for you but it's worth a try.

Using Vue.js with vue-socket-io


How to pass data continously to next activity after cliking button one time

Question: I am developing android application, I need to pass data continuously to next activity after i click button one time For Ex: i am fetching latitude and longitude from url and sent to next page by using button
//This is my url
private static String url = "http://example.com/android/gps/latlong.php";

//i am getting latitude and longitude from url and store into one string

final String latitudee = c.getString("latitude");
final String longitudee = c.getString("longitude");

//Now i need to pass these two values to next page when i click button

button2.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View arg0) {
             Intent intent = new Intent(context, Nextpage.class);
             intent.putExtra("lat", latitudee);
             intent.putExtra("long",longitudee);
    }
});

//Next page i am getting those values from mainactivity page

latitudee = getIntent().getExtras().getString("lat");
longitudee = getIntent().getExtras().getString("long");

My Requirement:-
Latitude and longitude is coming continuously from url, so i need to pass latitude,longitude to next page continuously after i click one time.
if i click one time and enter into second page, first time data will passing to next page while clicking but i need to get continuous values from main   activity
could you please help me how to do it?
Comment: Use a background service.
Comment: Are you using latitude and longitude in mainactivity?
Comment: @BidhanA could you please give me any sample
Comment: @Nag No i am getting lat,long from url in mainactivity and i need to send lat,long to next page continuously  after i enter into second page by using button
Comment: Two activities do not exist simultaneously (this is how android works), when you call startActivity(..) the calling activity will be paused and stopped while the other runs. This is the reason people are saying you need to handle the data in a background service.
Comment: @stealthcopter  if i use bacground service, i can pass data continuously to next activity?
Comment: Yes. In this instance you'd want a background service that is getting the lat/lng and sending the information on via a broadcast intent. The broadcast intent is a way of passing data to anything that is registered to listen for it.
Comment: @stealthcopte could you please give some sample according to my requirement?
Answer: So to do this you need to create a background service that continually checks for the lat and long. Then, each time these values are updated, you would use a broadcast receiver to notify your current activity of the updated values.
Information on how to create a background service can be found here https://developer.android.com/training/run-background-service/create-service.html.
Comment: could you please give some sample according to my requirement?
Answer: Correct your code ...  as u havent started activity using intent ... use this code ....
button2.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View arg0) {
             Intent intent = new Intent(context, Nextpage.class);
             intent.putExtra("lat", latitudee);
             intent.putExtra("long",longitudee);
                startActivity(intent);
    }
});

Answer: In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);

Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}

Comment: This will not continually give the updated lat and long. This will only pass it the first time.


How to make a div responsive and use a fixed size?

Question: I have a div within a  tag, this has a fixed width, height and margin.

This is div

I want to decrease the width when this div not fit's the browser anymore, when the browser width is less than 1252+50+50px, and i want the height to decrease but still keep the same ratio(1252x805).
How can this be done?
Comment: Did anyone mention `max-width: 1252px` and `width: 100%` ?
Answer: When you want to apply  a specific style when the screen size width between 320px and 480px for example ,You can use  ( @media queries) to detect the screen size.:
@media only screen
  and (min-device-width: 320px)
  and (max-device-width: 480px)
   {
/* your style here */
}

Answer: You can add the following CSS :
 #360container {
  width: 100%;
  padding-bottom: 64.2%; /* 805 is 64.2% of 1252 */
}

Answer: Try this code and let me know whether it satisfies you or not.
<!DOCTYPE html>

W3Schools Demo

Resize this responsive page!

London

London is the capital city of England.

It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.

Paris

Paris is the capital and most populous city of France.

Tokyo

Tokyo is the capital of Japan, the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.

Answer: Here is something that may work, pure CSS

Take a look at the fiddle
https://jsfiddle.net/je3g4evs/1/
Answer: Try this:
.aDiv {
  width: 100%;
  max-width: 480px;
  height: 100px;
}

https://jsfiddle.net/mrz240sa/7/
Answer: if you want your website to be responsive use percentage widths instead of pixels....
for eg.

W3Schools Demo

Resize this responsive page!

London

London is the capital city of England.

It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.


Create a pandas dataframe from a qrc resource file

Question: I would like to save a CSV file into a qrc file and than read it putting its contents in a pandas dataframe, but I have some problems.
I created a qrc file called res.qrc:
<!DOCTYPE RCC><RCC version="1.0">
  <qresource>
    <file>dataset.csv</file>
  </qresource>
</RCC>

I compiled it obtaining the res_rc.py file.
To read it I created a python script called resource.py:
import pandas as pd
import res_rc
from PySide.QtCore import *

file = QFile(":/dataset.csv")
df = pd.read_csv(file.fileName())
print(df)

But I obtain the error: IOError: File :/dataset.csv does not exist
All the files (resource.py, res.qrs, res_rc.py, dataset.csv) are in the same folder.
If I do res_rc.qt_resource_data I can see the contents.
How can I create the pandas dataframe?
Answer: The qresource is a virtual path that only Qt knows how to obtain it and can change internally without warnings, in these cases what must be done is to read all the data and convert it into a stream with io.BytesIO
import io
import pandas as pd
from PySide import QtCore
import res_rc

file = QtCore.QFile(":/dataset.csv")
if file.open(QtCore.QIODevice.ReadOnly):
    f = io.BytesIO(file.readAll().data())
    df = pd.read_csv(f)
    print(df)

Comment: thanks that solves my problem! Sorry I didn't really understand why we have to pass by BytesIO, could you please explain it?


Replacing contents of html page using another html page

Question: I am trying to avoid header, sidebar info repeating of my html page template.
So, I was thinking to user innerHTML to replace the contents on the fly. However, I do not want to put entire target html on the same page under innerHTML as it will be nightmare to debug or maintain later.
So, is there a way to specify the another page link in the innerHtml and have contents separate?
just as an example

I'm looking if i can specify the innerHTML value as some .html file name and move the
hey vik
 there.
Comment: This is where starting to use server-sided code will come in handy. You should try anything that isn't PHP.
Comment: This is what a template library is for https://garann.github.io/template-chooser/
Comment: Check out Mustache.js : https://github.com/janl/mustache.js/
Comment: not simple enough to do this without any other library etc?
Comment: You could store all of the "other" html values as Javascript, or you can hit up server side code for an answer.  But as with most things roll-your-own on the server-side you have to just be a little careful about security.
Answer: ok guys i finally used jquery to do this. What I did was instead of loaded content part, i actually moved the static part into a .html file and then loaded it via jquery as
$(function() {
$("#includedContent").load("navbar.html");
 };
the place where i need to rander it i added as below

Answer: You can use document.documentElement to select the root element of the document and the store it in a variable:
let content = document.documentElement;

And then use innerHTML to change the page content:
content.innerHTML = "
text
";


Intermittent flickering lights across multiple circuits and multiple brands of bulbs

Question: I'm having an issue in a house I bought last fall where I'll be sitting in a room and the lights will flash on and off so fast it feels seizure inducing.  I don't think it's every bulb every time this happens, but I'm not sure.  For MOST of the bulbs in the house, this happens just the once every so often.  I've tried changing bulb brands in some fixtures (all LED) but with no luck.  It still happens but in varying degrees.  This is in multiple rooms, on multiple circuits, on both sides of the panel.
I had an electrician look at it and he basically said to ask the power company to come out and check the neutral connection.  They did that, still no luck.
I installed a hard start kit installed on my AC compressor and that seems to have helped some.  There's also 6 fridges/freezers in this house (some small beverage ones) so tracking devices kicking on and off is incredibly tricky.
The one room I can get consistent flicker is in our master bathroom.  We have a Toto washlet with heated seat and some "vintage style" LED bulbs around the vanities.  If the Toto washlet kicks on (I imagine it's the heater causing this), these vintage style bulbs will flicker like crazy.  This room is consistent, everywhere else is super intermittent.  I'm thinking the bathroom is its own separate issue, but wanted to include this just in case.
Is there anything I can do to try and track down the source of this?  Anything I can measure to show my utility company an issue on their side?  My electrician basically said I'm out of luck until the transformer gets replaced but the occasional flicker is extremely jarring.
Comment: I would add more accent and task lighting such that you reduce the amount you depend on middle of the ceiling lighting. Options include spots, strips, and fairy lights. This lighting should be LED, driven by explicit DC adapters, which won't flicker like LED bulbs do.
Answer: Try turning one thing off at a time. When you find the problem the flickering will quit. However you may have multiple sources so you should bring the ones you turned off back on one at a time. If you can narrow it down to one with this process you can work on finding the problem. Check breakers and see if one is hot and or the wire is not tight. I doubt this is it but you never know until you check. You can get a recording voltmeter but I doubt it will show the transients. It will give you a voltage trend and let you determine what time of day the problem is at its worse. It is possible the transformer supplying you is to small and or the feeder to your home is undersized. What size breaker panel do you have? If you have neighbors on the same transformer check with them and see if they also have the same problem. If several of you do complain to the power company.
Comment: That's a lot of fluctuation.  Does the voltage drop  to 110 for just an instant or does it stay there for a while?  Is it a gradual drop, or instantaneous drop? You may be on a power company circuit that has other customers using heavy duty equipment requiring large start up currents. Or a neighbor with an oddball electrical usage pattern, like an arc welder.  LEDs are notorisiouly sensitive to voltage variations and react INSTANTLY.   Gil's advice is good: Turn everything off but the lights and see if you still have the flicker, then turn circuits back on, one by one.
Comment: Curious question, does the problem go away very early in the morning or when it cools down outside? Is the grid loaded in your area, California is one that is having problems. There are test instruments called power quality meters, made by several manufacturers. Quite pricey but they can be rented if you so desire.
Comment: 200 Amp panel.  I have a commercial grade UPS that charts incoming voltage min/max and frequency.  Always get 60Hz, voltage fluctuates between 110-120.
Answer: Another option in addition to the turning off one light or appliance at a time is to ask your power company to test your electric meter. This happened to me – the same issues you're having – and after multiple inspections of the breaker + a breaker replacement, it turned out to be the electric meter. The power company replaced the meter at no charge and the flickering stopped.


org.openqa.selenium.os.UnixProcess destroy message with Selenium 3.0, gecko 0.15, FF52

Question: Simple script:
<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class sanity {

public static void main (String[] args) throws InterruptedException
{
   System.setProperty("webdriver.gecko.driver", "C:\\Selenium Purely\\geckodriver\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
driver.get("http://facebook.com");
driver.quit();//closes the browser
} }
</code>
On execution completion, it throws below error in console.
1489404845805   geckodriver INFO    Listening on 127.0.0.1:34461
1489404846478   mozprofile::profile INFO    Using profile path C:\Users\jshaikh\AppData\Local\Temp\rust_mozprofile.ZsJREdq3xMm4
1489404846494   geckodriver::marionette INFO    Starting browser C:\Program Files (x86)\Mozilla Firefox\firefox.exe with args []
1489404846525   geckodriver::marionette INFO    Connecting to Marionette on localhost:60729
1489404848161   Marionette  INFO    Listening on port 60729
Mar 13, 2017 5:04:12 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
1489404862119   Marionette  INFO    New connections will no longer be accepted
[Child 4856] ###!!! ABORT: Aborting on channel error.: file c:/builds/moz2_slave/m-rel-w32-00000000000000000000/build/src/ipc/glue/MessageChannel.cpp, line 2143
Mar 13, 2017 5:04:23 PM org.openqa.selenium.os.UnixProcess destroy
SEVERE: Unable to kill process with PID 11728
What could be the issue?
Answer: Try to use the latest version of selenium-java (version 3.3.1 at the time of this writing).


How to let Eclipse JDT auto-generate methods at the end of the class?

Question: Is there a way to let Eclipse JDT (Indigo and newer) auto-generate methods at the end of the class, rather than as the next member, when you type the name of an unimplemented method?
Ideally, methods would still be auto-generated before getters and setters.
Answer: I think what you want is to pull up the generate dialogs via alt-shift-s rather than just starting to type.  They have Insertion Point drop-downs that let you pick where the generated code goes.  Choose Last member.
Alternatively, you could always generate your code and then sort your members via Source->Sort Members but if you're incrementally adding to old code your team-mates might not like you checking in big changes like that into your repository.
Comment: I'm aware of the *Insertion Point* dropdowns, but am very fond of using the keyboard (and avoiding the mouse) whenever I can, so I was looking for an alternative to the menu- and view-based source alteration mechanisms.


dotnet is not recognized as the name of a cmdlet

Question: We have downloaded and run DotNetCore.1.0.1-SDK.1.0.0.Preview2-003133-x64.exe. After having closed and reopened our command prompt, running dotnet gives the following output.

The term 'dotnet' is not recognized as the name of a cmdlet, function, script file, or operable program.

We have tried the following:

Uninstall all versions of Visual Studio.
Uninstall all versions of .NET Core.
Repair C++ Redistributable 2015 x86 & x64
Restart the computer.
Then reinstall the .NET Core SDK.

This is the contents of C:/Program Files/dotnet
host
  fxr
sdk
  1.0.0-preview2-003133
shared
  Microsoft.NETCore.App
swidtag
  Microsoft .NET Core 1.0.1 - SDK 1.0.0 Preview 2-003133 (x64).swidtag

Our PATH includes C:\Program Files\dotnet\
Comment: Did you solve this.  I am going through it now but on "1.0.1-preview3-004056" in VS2015.
Comment: @K7Buoy I did solve it, but I'm afraid I did not document the solution.
Comment: I had to roll back in my project.json to 1.0.0-preview2-003131.  Something messed my system up, I have been messing about with Gulp and Bash over the last couple of days and my PATH had been removed as well.  All sorts going on for some reason.
Comment: @K7Buoy I have since found a answer that works for us.
Answer: Also ensure that "C:\Program Files\dotnet" is part of the "path" system environment variable.
After uninstalling previous SDK versions, it had disappeared from mine.
Comment: Restart IDE if restarting shell within it doesn't work.
Comment: The same happened for me. This is certainly a bug in the dotnet installer.
Comment: I had this happen after uninstalling visual studio 2022 (I use Rider). The actual SDK was still there but it was removed from the path.
Answer: This error also occurs if .Net Core is not installed on your machine. To verify it, please run the command dotnet --help from Windows PowerShell or VS Code terminal. If .Net Core is installed then you will see the output, else the same error. If you see the same error then:

Please download and install it from here.
Then close the CLI or Code editor you are using.
Re-open it again, run the following command:
dotnet new webApp -o aspnetcoreapp

It will hopefully let you get rid of the problem.
Answer: After again coming across this problem, we found the answer here.
Open Programs and Features, choose Microsoft Visual C++ Redistributable (x86), click Uninstall and then choose Repair. After repairing it (and the x64 version if you have it), reinstall or repair the installation of the .NET Core SDK 1.0.1.
Answer: I had a same problem. It can be fixed by following this solution:

Open command window (win+R) then:
cd Desktop
mkdir CSharp
cd CSharp

Open new file on desktop, then after that
dotnet new console -o firstapp
cd firstapp
code

vs code automatically opened.

Then you open the terminal:
dotnet restore
dotnet run

Finally done.
You can watch this video.
Answer: In my case the issue had to do with the x64 vs. x86 discrepancy.
My path had x86 in it. I manually changed it to "Program Files" rather than "Program Files (x86) and it started working again.
Answer: Go to Apps and Features,
Search for Microsoft Visual C++ Redistributable 2015
Click the modify button and then click repair, do this for both versions of Microsoft Visual C++ Redistributable 2015. It should then prompt you to restart device.
This worked for me!!
Answer: Go to the Control Panel->Microsoft Visual C++ Redistributable(x86)-> Repair. Following this completion, Microsoft .NET core SDK-> Repair. It will work.
Answer: In my case, I was updating VS 2019 when it occurred. Once the update is finished, the error is gone.
Answer: Open powershell terminal as admin
Run these commands in sequence to troubleshoot as shown in the picture.

dotnet --list-sdks

winget search dotnet

winget install --id Microsoft.DotNet.SDK.7 -e

cd C:\"Program Files"\dotnet

.\dotnet --list-sdks

Restart the powershell terminal

dotnet --list-sdks

Make sure Environment path is updated


How to get rid of fleas in an apartment with carpeted floors?

Question: Long story short...we came home after 5 days away with our 1.5 year old and noticed that the wherever the cat slept or lounged there was cat hair and little particles that looked like black pepper.
A quick internet search pointed to fleas. My wife bought a flea collar for the kitty (~$50 for a time release collar good for 8 months...that hurt the wallet) and a flea comb.
She proceeded to comb 40-50 fleas off of kitty. (Awhile ago I noticed spots on kitty's neck that were scabbed over. I should have guessed that it was probably from scratching.)
I also saw a flea on the carpet and then it sprang away.
My question is, what is the cheapest, safest and most efficient way to get rid of these suckers. Is there a permanent solution? I have a 1.5 year old so I'm concerned with using chemicals.
Answer: When I lived in an apartment, we had a problem with fleas once (due to a neglectful pet owner in the building).  Getting rid of the problem was no small feat, and took a lot of work over a few days.
I started by laundering all bedding, clothing, and basically anything fabric that was washable.  Next I rented a steam cleaner, to clean the carpets. You can call in the pros for this if you don't want to do it yourself.  The final step was to spray the entire carpet; paying special attention to the edges and corners, with Adams™ Flea & Tick Home Spray. Other brands exist, this was just the one I chose which worked for me.
When using any chemical spray, make sure you have adequate ventilation. Try to avoid skin contact with chemical sprays as well. My wife had a bad reaction to the spray, where her feet swelled up quite a bit.
If you're in an apartment building; where the source of the infestation could be coming from other tenants, you'll also have to treat the other units.  If you don't remove the infestation from the entire building, you'll likely see the fleas return to your apartment.  Any outdoor pets in the building should also be treated, not only to combat the flea infestation but also for the health of the animal.
Comment: It *may* not be dangerous to use around your child, though I would not apply it in their direct vicinity.  I had no reaction to the chemical, and my wife only had a problem until the carpet was dry.  If you're going to use chemicals, maybe send the wife and child to visit grandma and grandpa for the afternoon. It might also be a good idea to check with your pediatrician before using chemicals in your home.
Comment: That home spray doesn't sound good around my one and half year old.
Comment: Unfortunately fleas are hardy and most "hacks" or "non-invasive" methods are much less successful. At some point you have to consider is the infestation and chance introduction of infection carried by the critters better or worse than the chemicals used to get rid of them.
Answer: Due to the fact that you have an infant I would seek professional assistance. You don't have the choices of chemicals that trained and licensed pest professionals do. I can't testify to their effectiveness but I have heard that you can trap fleas with a desk lamp. You place the lamp on the floor with the arm extended and pointed about 6 inches off the floor. Place a pie pan on the floor under the lamp so the lamp shines on it. Pour an inch of water in the pan. Add a small amount of vegetable oil to the water. The theory is that the fleas are attracted to the light, hop in the pan and are trapped in the liquid. Another tip I have done is to take the extra piece of flea collar and put it in the vacuum cleaner bag. We have a HEPA filter so the chemicals are contained in the bag. The idea is that any fleas vacuumed up are killed in the bag preventing their release when the bag is changed.
Answer: Understanding the flea life cycle is important (e.g., http://www.petmd.com/dog/parasites/evr_multi_understanding_the_flea_life_cycle) because different treatments work on the different flea stages.  Different approaches work for different stages.  For example, "Cocoons have a sticky outer coating that allows them to hide deep in the carpeting and not be easily removed by light vacuuming or sweeping. The cocoon also serves to protect the developing adults from chemicals." That means you must repeat the various treatments, so you catch the little buggers when they move through their life cycle.
Answer: To solve a flea problem, you will need to tackle it from all sides. You will need to address the fleas on your pet, as well as kill the adult fleas, eggs, and larvae from your entire apartment. Some of these suggestions also already appear in other answers.
The first step is to treat your pet. Bathe them with flea and tick killing shampoo. Then comb them thoroughly to remove as many fleas and eggs as possible. Apply flea medicine to them or put on a flea collar. This will help prevent your pet from being eaten alive. You may need to try different types of medications if the one you are using does not work. The fleas will then generally leave them alone.
Fleas will also target humans, so be sure to clean all linens, clothing and bedding if possible. Hot water works best to kill off the eggs and larvae which may be there. You should also vacuum every carpet, and be sure to clean every crevice thoroughly. The furniture should also be vacuumed. Be sure to pull up the cushions and vacuum. It is also a good idea to pull out the furniture and clean behind and underneath. Once you are done vacuuming, put the bag into a plastic garbage bag and immediately dispose of it. You can also spray flea killer directly into the bag so they don't escape. After everything has been cleaned and vacuumed, then move on to steam cleaning. Make sure to use hot water when cleaning. The hot water is more likely to kill the eggs.
Those steps will get rid of around 90% of the fleas. The remaining ones will be much harder to deal with. Their lifecycles are extremely fast. It only takes about 3 days for a flea to reach maturity and start breeding. When I dealt with them in my old apartment, the only thing that was able to completely get rid of them was a flea trap. A flea trap uses a small night light light bulb, and has a piece of sticky paper underneath it. The fleas will jump towards the light, and then fall through a plastic grate onto the paper and get stuck there. Put the trap in an area where you have noticed flea activity, and you will see that the paper will be completely covered with hundreds of fleas within a few days. Replace the paper when necessary, and your flea problem will eventually be solved. When you get your trap, make sure to get some extra refills. They get used up pretty quickly. Also keep track of how many fleas are being captured. At first, there should be quite a few every day. That number should decline over the span of a few days. If it doesn't then there is still a serious problem, and you should repeat the steps above to reduce their population. Eventually there shouldn't be any more fleas in the trap. Once you think they are all gone, put in a fresh refill and leave it on for at least a week to see if you get any more. There will be a few stragglers around for quite some time, and if they are not all exterminated, then they will be able to repopulate. You can also try having multiple traps around, or at least try moving it around to see if you find more.
Answer: We had this same issue in our last apartment. We gave both cats a bath with the blue dawn dish soap. This kills fleas almost instantly. Be generous with the suds too. While we were bashing the cats, we had a flea powder on the carpets. After the bath, before letting the girls out of the bathroom, we vacuumed everywhere. Once you do this, you'll be good until your pretty is exposed again. For aftercare, yo can get some Avon Skin So Soft oil. Mix it equal parts with water making it completely safe for your pet's fur and skin, and won't leave them too oily. My grandma has been selling Avon for over 40 years, so I literally grew up using it on every pretty I've ever owned. If you want to see how bad the flea infestation is before you treat, just set out a few small plates that are derp enough to hold a little water, not deep at all. Then add a drop of the blue dawn dish soap. The fleas will jump in the water, and the soap will kill them. No need to mix the soap in. Just a drop in, and you're set. The first time I did this, we had a TON of fleas, and I'm just a few days time too. As soon as I put down the first plate, a flea jumped in and died while I was watching. So so nasty.
Comment: I certainly hope you were "bathing" your cats, and not "bashing" them. o.O
Answer: I recommend the following for your flea problem. Vacuum the afflicted room(s). Toss the vacuum bag once your done with it. Next, take a carpet steamer to the recently vacuumed areas to kill off the remaining eggs and adult fleas.  For further protection from fleas, you may purchase some carpet powder.
Comment: You have already been warned about posting answers that are little more than spam. I've removed the link from this answer as it's not necessary.
Answer: The solution I used: There are treatments which specifically target insect eggs. Two treatments of this, a few days apart according to the instructions to make sure any eggs laid after the first treatment also die, cleared most of the apartment. The cat got the flea-shampoo treatment combined with thorough combing with a nit comb; any fleas that this extracted were dropped into water with dish detergent. (The detergent cuts surface tension so they sink.) Finally, she got a flea collar, so any remaining fleas that latched onto her would be killed off -- basically I let her do the mop-up pass.  May or may not have been overkill but it worked.
For what it's worth, not one of those fleas ever bit me, as far as I could tell.
Answer: I can't confirm it's effectiveness, but I've heard of people using baking soda to get rid of fleas in carpets. It does have a nice side-effect in that's it's also a deodorant.  Maybe steam clean first, then put down baking soda (along the lines of @Tester101's answer, but minus the potentially harmful chemicals)?
Answer: As part of your "acute" treatment (along the lines that the other answerers have suggested), make sure you thoroughly wash your clothes and bedding in very hot water.
In addition to the "acute" and "follow-up" treatment that the other answerers have suggested, you can sprinkle Borax on all of the carpeted surfaces.  (Borax is a cheaper version of the non-toxic flea powders.)  Make sure that the areas where the cat sleeps or lounges are covered especially well.  Re-apply the Borax after each time you vacuum.  This will tend to prevent recurrences, at the expense of making the air very dry.
Comment: Borax is definitely **not** non-toxic when applied the way you describe.  Borax is not *acutely* toxic which means that contact with small amounts of it for a small amount of time is probably fine.  You should not apply it and leave it there 24/7.  When people recommend borax, they typically prescribe applying it, letting it sit for a few hours and then vacuuming it up.
Answer: Fleas eggs hatch upon vibration. When you walk on the carpet the vibration causes eggs to hatch. It's a 3 day cycle I believe.  You have to vacuum consistently over several days. All the above mentioned will work but again the 3 day cycle is necessary. Good luck.
Answer: Forget the cheapest route. When it comes to fleas you need a professional exterminator.  There are some good ones that won't cost you $500  to come out twice.  Some charge only one time and gaureentee their work for two months.  I'm speaking from experience they will have to go out and fumigate 2 or 3 times.   You know it will work when they ask you and your pet to stay out for five hours because of the smell.  Don't hire the person that says their formula doesn't smell.  Again from experience it will not work.
Answer: One more important thing. Make sure to remove your pet while you treat your home and treat your pet with a flea treatment that are drops not a collar.  A collar can cause your pet to get sick. Imagine wearing garlic around your neck .  These drops are safe and can be applied behind their head.   Must be purchased by the vet. Over the counter cheaper brands will do nothing. However , Abvantage brand works well and you can order online. I cannot stress enough do not  go for the knock off brands.  Much luck sent your way and my way too.
Comment: Could you [edit](http://diy.stackexchange.com/posts/108319/edit) this into your existing answer?


Main box amp requirement for 2.4 amp refrigerator

Question: My LG refrigerator has a 2.4 amp rating. What size breaker do I need For this? The only other on this line is a GFCI with three plugs.
Comment: Where on the planet are you? Where in your house are the other receptacles on the circuit located? What loads do they serve?
Comment: In the USA, this would automatically be "any 15A or 20A circuit". But LG is very much an international brand, so we need to know where you are.
Comment: 1,5mm^2 with C10A breaker is the minimum allowed by CEI.
Answer: Assuming USA/Canada: 15A if it's 14Ga copper wire, 15 or 20A if it's 12Ga copper wire. I'm personally not a fan of sharing the refrigerator or freezer circuits with any other load due to the possibility that the other load will trip the circuit and spoil your food.
If the other outlets are in the kitchen, that's required to be 20A if it's one of the two required countertop outlet circuits.
Comment: If it's serving countertop outlets period, even
Comment: Breakers are sized to protect the wiring, not to protect specific appliances.  so @Ecnerwal is correct.
Answer: In the US a typical convenience receptacle will be protected by a breaker that is legally sized to protect that fridge. The only conflict would be if you have other devices plugged into that circuit that the instructions that come with that appliance specify using a dedicated circuit.
Comment: Thank you. The only use of the GFCI circuits is occasional rice cooker. I am located in the USA.
Comment: @RayKreiner the expected way of saying "thank you" is to click the "up vote" arrow for any and every answer you find helpful. It's also expected that you click the check mark next to the answer that you found _most_ helpful in resolving your issue.


deck railings: alternatives to 4x4 posts?

Question: I'm working on a deck with a lot of level changes. Using 4x4 posts for the railing is undesirable because it'll look rather clunky.
I am wondering if there are any examples someone can point me to where a different, thinner post size is used. I can't seem to find any (possibly because it isn't possible to do it without it being too flimsy). Would a possible alternative be to use multiple, thinner posts? I doubt it as the real problem is people pushing on the railing... Hopefully this question is specific enough to warrant an answer.
Thanks.
Comment: If you're willing to mix materials you could use a steel post for the railing that is much thinner than 4x4.
Answer: Typical wood deck railings are 4x4 posts, 2x4 rails, 2x2 balusters and a 2x6 railing cap on top.  Wood railing is chunky but it needs to be to prevent people falling through it in the event of a accident.  It is not just leaning that is the concern but 1 or 2 200+ lb people failing into the weakest spot (middle of the rail) that it needs to handle.  But when it is done right, stained a nice color, sealed and has quality work, it does look very nice.  You can upgrade the look by having post caps or switching out the wood balusters for metal ones for not much more.
If you want thinner posts you need to switch materials, like metal, but that will probably double your costs.  With metal posts, come metal rails which then require metal balusters.  All this metal requires a metal worker to fabricate offsite and then bring to site for assembly and install.
Comment: There are some metal railings at the big box stores that are not awful. Look for 1-1/2" posts and a sturdy mounting system. (There are ones that are absolutely awful, too, so choose carefully.)
Answer: I've used 2x10 s for vertical supports
They have lots of contact/ surface area to attach to stringers or band joists. I think 4 bys have become the standard by default.
2by don't have to be notches and seem effective


Fixing the date axis of a time series in vba

Question: I have a code that gets data from excel and makes a graph. It takes some inputs (since more than one graph is done), creates a new Chart Sheet and insert the data.
Problem 1 My code gets the UsedRange from the specified sheet and uses that to fill the graph. The data starts at A1 and goes until the end. One of the Graphs however, have data in its first row that should not go into the graph. Foe example:
This is for one of the normal graphs:
           Item 1         Item 2
 day 1      100            100
 day 2      110            180
 day 3       90            110
 day 4       70            130

and so on. This is the exception:
           Item 1         Item 2
 day 1        1              1
 day 2      110            180
 day 3       90            110
 day 4       70            130

QUESTION 1 In this second case, I want to remove the first row of data (not the identifier row) from the graph. Since I am using UsedRage, how can that be done?
Problem 2 For all the graphs, the data series start at some point in the past and comes until today. Problem is that when the date series is graphed, it starts counting from the first day (stepping through the periods, eg. 6 months) until it reaches the most recent date.
In this case, it does not include today's date, which is what I am trying to achieve.
To exemplify:
In this case, my data goes until the 7th of December, but the last date that appears is the 31st of October.
QUESTION 2 Can this be fixed?
Obs: I already tried using the recorder to generate a code for this, but even in the embedded excel options I cannot find any way to do it.
The code so far:
Function Grapher(ChartSheetName As String, SourceWorksheet As String, ChartTitle As String, secAxisTitle As String)

Dim lColumn As Long, lRow As Long
Dim LastColumn As Long, LastRow As Long
Dim RetChart As Chart
Dim w As Workbook
Dim RetRange As Range
Dim chrt As Chart
Dim p As Integer
Dim x As Long, y As Long
Dim numMonth As Long
Dim d1 As Date, d2 As Date

Set w = ThisWorkbook

'find limit
LastColumn = w.Sheets(SourceWorksheet).Cells(1,   w.Sheets(SourceWorksheet).Columns.Count).End(xlToLeft).column
LastRow = w.Sheets(SourceWorksheet).Cells(w.Sheets(SourceWorksheet).Rows.Count, "A").End(xlUp).Row

If SourceWorksheet <> "DD" Then 'this is the exception case
    Set RetRange = w.Sheets(SourceWorksheet).UsedRange 'HOW CAN i CHANGE THE RANGE TO ACCOUNT FOR THE PROBLEM 1?
Else
    Set RetRange = w.Sheets(SourceWorksheet).UsedRange
End If

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
For Each chrt In w.Charts
    If chrt.Name = ChartSheetName Then
        Set RetChart = chrt
        RetChart.Activate
        p = 1
    End If
Next chrt
If p <> 1 Then
    Set RetChart = Charts.Add
End If
'count the number of months in the time series, do the ratio
d1 = w.Sheets(SourceWorksheet).Range("A2").Value
d2 = w.Sheets(SourceWorksheet).Range("A" & LastRow).Value
numMonth = TestDates(d1, d2)
x = Round((numMonth / 15), 1)
'ratio to account for period size
If x < 3 Then
    y = 1
ElseIf x >= 3 And x < 7 Then
    y = 4
ElseIf x > 7 Then
    y = 6
End If
'create chart
        With RetChart
            .Select
            .ChartType = xlLine
            .HasTitle = True
            .ChartTitle.Text = ChartTitle
            .SetSourceData Source:=RetRange
            .Axes(xlCategory, xlPrimary).HasTitle = True
            .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Date"
            .Axes(xlValue, xlPrimary).HasTitle = True
            .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = secAxisTitle
            .Name = ChartSheetName
            .SetElement (msoElementLegendBottom)
            .Axes(xlCategory).TickLabelPosition = xlLow
            .Axes(xlCategory).MajorUnit = y
            .Axes(xlCategory).MajorUnitScale = xlMonths
        End With
End Function
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Function TestDates(pDate1 As Date, pDate2 As Date) As Long
TestDates = DateDiff("m", pDate1, pDate2)
End Function

Any Help would be deeply appreciated.
Comment: The first row (where "Item1" and "item2" is a header row?
Comment: @A.S.H Exactly. The row I want to exclude is the

    day 1        1              1
Answer: Problem 1:
If the start cell should be A2 you could try this:
Set RetRange = w.Sheets(SourceWorksheet).Range("A2:C" & LastRow)
Problem 2:
I see on your graph that the interval of the data shown on X axis is 4 months. As i know there is no way to force excel to make an irregular interval and force show additional label for last value.
You could try adding a label to the last data point:
label-last-point
EDIT: Added screen to my comment
Comment: @ A.S.H. It will reverse the graph but as i recall the last value will not have a label.
Comment: Thanks for the answer. Problem 1: That is what I am currently doing: I set the beginning of the cell to that and then restate the series name directly in the graphing part.
Problem 2: What I am currently trying to do, is find a way for excel to count the dates backwards, therefore I would have the last date (stepping 4 or 6 months back) until the matching date in the beginning, then the first beginning dates do not appear, which is acceptable. Problem is I cannot find a way to do it.
Comment: The other thing you could try is to change the series format from dates to text. Excel will treat it differently and you should get more options on customizing the axis labels.
Comment: @DGMS89 Try This: `.Axes(xlCategory, xlPrimary).ReversePlotOrder = True`
Comment: @A.S.H I tried it before, but checking any time series backwards would be counter intuitive. The only way I imagine it could work is if there was a way to mirror the plot part of the graph in the output. But that goes against the purpose of the line of code you suggested. If I could count the dates backwards but past them normally, it would be solved.
Comment: Sorry then, I totally misuderstood part 2.
Answer: After lots of tinkering with the code and help from other posts and people, I could finally solve problem 1.
Problem 1 Can be solved by setting the range to total and than resetting the data when the graph is created. The code for it is (to be added within the "with"):
If SourceWorksheet = "DD" Then
                For lColumn = 2 To LastColumn

                    .FullSeriesCollection(lColumn - 1).Name = "=DD!$" & Col_Letter(lColumn) & "$1"
                    .FullSeriesCollection(lColumn - 1).Values = "=DD!$" & Col_Letter(lColumn) & "$3:$" & Col_Letter(lColumn) & "$" & LastRow

                Next lColumn

            End If

        End With

Problem 2 I have been scavenging the internet, but apparently there is not way to step backwards and then mirror the graph, so that remains unsolved.


Needed help ralated to Web Server

Question: I have installed OS Windows7 Home Basic at my development machine. After developing the ASP.NET web application, I needed to deploy. I started installing IIS on my machine, but found that in Win7 Home Basic, there is no iis manager. After searching on net, I found Cassine Web Server(CWS). I installed the CWS and it working fine as a web server.
I have a question. Is CWS is better than IIS? Is CWS is secured as IIS? Is CWS can be used as a web server at target machines?
If anyone used CWS, please tell me about your experience.
Comment: Check the answers to this question: http://stackoverflow.com/questions/281667/asp-net-development-server-or-localhost-iis
Answer: CWS is just a development web server. It has no purpose to be used as a production web server.
Comment: but as per the CWS site, it can be used at client machine also. I think it may be less secure than IIS.  http://ultidev.com/products/UWS-Cassini-Pro/Default.aspx
Comment: It's absolutely not the same products, in your question it's Microsoft's Cassini aka Visual Studio WebDev in ultidev website, it's not ultidev Cassini.
And based on the ultidev comparison table, ultidev Cassini has a lack of security.

Needed help ralated to Web Server


Do I need a separate home inspection if I've got a good contractor doing a gut rehab?

Question: We're looking at buying a single family home that's... rather out of date. It's basically in gut-rehab shape. We're planning on replacing electrical, plumbing, heating, and even some foundation work. We have a contractor we like and trust. Is there any point in paying a separate home inspector?
Comment: Not a building inspector. A home inspector, of the kind one normally gets as a contingency when purchasing a house. The contractor would _of course_ get relevant permits and inspections.
Comment: Check your local jurisdiction. It's probably unlawful to do work on your house without a permit and approved Inspections
Comment: Home inspectors have NO authority.
Answer: You still might want the inspection.  Even though you don't care about the electrical, plumbing, heating, wall and floor finish, you are counting on the underlying structure to be sound.  You might want to know about, for example, evidence of water damage / possible mold, rot in the sill or beams, sagging floors, possible asbestos, evidence of termites or other pests - many things you might not have thought of.
You may be able to ask the inspector to place less emphasis on the systems you know you plan to replace.
Comment: Oh, there are _definitely_ sagging floors and asbestos tile. It's to that level already :)
Answer: I have purchased homes without an inspection report, your lender may require one, but if doing everything for your personal residence his contract with the scope of work may even make the lender happy.


Show that if $G$ is a noncomplete graph of order $n$, then $t(G)≤\frac {n-α(G)}{α(G)}$

Question: Show that if $G$ is a non-complete graph of order $n$, then $t(G)≤\frac {n-α(G)}{α(G)}$
with $\kappa(G)$ is connectivity of $G$, $\alpha (G)$ is the independent vertices of $G$, and $t(G)$ is the toughness of $G$
I know that for every non-complete graph $G$
$$\frac{\kappa (G)}{\alpha(G)} \leq t(G) \leq \frac{\kappa(G)}{2}$$
I'm not sure I can see the relationship between $n$ and $\kappa (G)$ and $\alpha (G)$ that give me that result.
Comment: Can you define $\kappa, \alpha$ and $t$?
Answer: By removing all vertices except an independant set of size $\alpha(G)$, it is possible to split $G$ into $\alpha(G)$ components.
Since $G$ is $t(G)$-tough, we must have removed at least $t(G)\alpha(G)$ vertices.
We conclude $$t(G)\alpha(G)\le n-\alpha(G)$$
Comment: Where did I use that $G$ is noncomplete?
Comment: did you use the first part of the inequality?


SQL to Linq conversion with cross join

Question: Can someone please help in converting the following sql to linq in c#?
select s.SYSTEM_NAME,
       r.RESET_CODE,
       COUNT(v.reset_code)
  from (select distinct system_name
          from tbl) s
cross join (select distinct reset_code
              from tbl) r
left join tbl v on v.SYSTEM_NAME = s.SYSTEM_NAME
               and v.RESET_CODE=r.RESET_CODE
 group by s.SYSTEM_NAME,r.RESET_CODE

Answer: Cross joins are generally represented as multiple from clauses in a query expression, or a call to SelectMany in extension method syntax.
So the first part of your query might be:
var query = from systemName in db.Table.Select(x => x.SystemName).Distinct()
            from resetCode in db.Table.Select(x => x.ResetCode).Distinct()
            ...

Left outer joins are usually represented with a "join ... into ..." query, possibly like this:
var query = from systemName in db.Table.Select(x => x.SystemName).Distinct()
            from resetCode in db.Table.Select(x => x.ResetCode).Distinct()
            join tmp in db.Table on
                new { ResetCode = resetCode, SystemName = systemName }
                equals new { tmp.ResetCode, tmp.SystemName }
                into tmpGroup
            select new { ResetCode = resetCode,
                         SystemName = systemName,
                         Count = tmpGroup.Count() };

I'm not sure about the Count part, to be honest... I'm not 100% sure what the COUNT(v.ResetCode) does in your original SQL.
Comment: Thank you very much. It solved my problem. I added the column name in the count() to have 0 for missing resetcodes. the linq query shows me the results correctly. But will niot having group by have an impact?? just curious to know what role it actually plays..
Comment: @Sasi: You're performing a "group by" operation with the "join ... into" operation, effectively. It uses the GroupJoin LINQ query operator.

SQL to Linq conversion with cross join


Php script to replace specific string in filenames from database

Question: I need a simple php script which needs to find files on server after reading Number column from database, copy files to another directory and then replace specific strings in saved files. For example we have files
20160107-151620_03216488727-all.mp3
20160418-105509_03225545395-all.mp3
We need to replace (03216488727, 03225545395) with the strings from database. Here is my database info:
Number                      Policy Number          Month
03216488727       123456788              2016-06
03225545395       123433339              2016-06
so after the replacement files will be
20160107-151620_123456788-all.mp3
20160418-105509_123433339-all.mp3
Please help.
Comment: Actually I am not a php programmer, I am a system administrator and do basic shell scripting. That's why I need help.
Answer: Have a look on the str_replace() function.
Comment: Actually I am not a php programmer, I am a system administrator and do basic shell scripting. That's why I need help.


Xamarin forms, working with a OnPropertyChanged with a INT value

Question: I have one button on my MasterDetailPage changing the value on an INT (named App.value1) depending on what you click looking like this:
void click1 (object s, EventArgs a)
{
    if (App.value1 == 0) {

        App.value1 = App.value1 + 1;

    } else {
        App.value1 = 0;
    }
}

And I want this click function to immediately change the value on my StartPage (another ContentPage). So I have created a viewmodel looking like this, where I try to work with the current value:
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged (string propertyName)
{
    var changed = PropertyChanged;
    if (changed != null) {

        PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
    }
}

public int currentValue {

        get {
            return App.value1;
        }

        set {

            if (App.value1 == 0) {
                App.value1 = 0;

            } else {

                App.value1 = 1;
            }

        }

    }

And this is the StartPage where I want the value of the INT to update immediately depending on what you clicked on at the MasterDetailView.
public StartPage ()
{
        var ourView = new StartPageViewModel ();

        ourCurrentValue = ourView.currentValue;
}

protected async override void OnAppearing()
{
    LoadData();
}

private async Task<List<Pin>> LoadData() //I work with pins here (not showing that code though as it is irrelavant.
{
    if (ourCurrentValue == 0) {
        System.Diagnostics.Debug.WriteLine ("Value is 0");
    }

    else {
        System.Diagnostics.Debug.WriteLine ("Value is 1");
    }
}

Right now I only see "Value is 0" in my log. Nothing updates when I click on my button on the MasterDetailPage.
UPDATED CODE:
public class StartPageViewModel : INotifyPropertyChanged
{
    private ICommand clickCommand;
    private int currentValue;

    public  event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged (string propertyName)
    {
        var changed = PropertyChanged;
        if (changed != null)
        {
            PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
        }
    }

    public StartPageViewModel()
    {
        ClickCommand = new Command(() => CurrentValue = CurrentValue + 1);
    }

    public ICommand ClickCommand
    {
        get { return clickCommand; }
        set
        {
            clickCommand = value;
            OnPropertyChanged("ClickCommand");
        }
    }
    public int CurrentValue
    {
        get { return currentValue; }
        set
        {
            currentValue = value;
            OnPropertyChanged("CurrentValue");
        }
    }

}

And StartPage:
public StartPage ()
    {
        App.PropertyChanged += (sender, args) => OnPropertyChanged("currentValue"); // ERROR: `An object reference is requiered to access non-static member 'Xamarin.Forms.BindableObject.PropertyChanged`
    }

Comment: The purpose of INotifyPropertyChanged is to fire the PropertyChanged event when the value of the property changes, in the setter.  Your setter is empty.  You are also using INPC on one property (currentValue) but modifying a different property App.value1.  If you want to update when value1 changes, then update value1's setter to implement INPC.  And if you are not using databinding, then you will need to manually set a PropertyChanged handler if you want it to do anything.  Finally, why is currentValue a string property if you are parsing it's value as an int?
Comment: Ok so, make a int directly instead of a string and then turn it to a int. Move the current code in my viewmodel on my getter to my setter instead? And to answer your question I am not using databinding here just changing the value of the int and making code visible depending on the current value
Comment: Updated the code with two changes now. Moved code to the setter and made the "currentValue" on my viewmodel an int directly. What is missing now? How can I manually set the propertychanged handler?
Comment: @Yannick, as @Jason wrote, when you are updating `App.value1` in your click button handler, `StartPage` doesn't even have a way to be notified that, the value changed, because it is binded to `StartPageViewModel`
Comment: Ok. It cannot reach it via the current viewmodel then? How would I need to adjust it?
Comment: Is `StartPage` a child of the `MasterDetailPage`? Maybe, they can just share the same ViewModel then?
Comment: The Masterdetailview is the Master and the StartPage is the detail. So yes I think so
Comment: They both Initialize their "components" at the same time
Comment: Also, `OnAppearing` is called once before the `StartPage` becomes visible. So, if you are not doing something in your application that would cause `OnAppearing` method to be called again then it won't be called (for example navigate to another page and then come back)
Comment: Yes exactly, that is why I need something like a propertychangedfunction right?
Comment: Yes, when you are binding to your `currentValue` property in View, then raising `PropertyChanged` event would cause View update to the new value of property
Comment: Precisely. I know what the "structure" is but not sure how to make it work with the code. With the current code, am I far off? And can you see what would need to adjust?
Comment: I would say yes, because your click button handler updates `App.value1`, but `StartPageViewModel` doesn't know anything about that.

If you would have shared ViewModel between `MasterDetailPage` and `StartPage` then you could update value from click button handler and `StartPage` would know about that because it is binded to the same property which is being updated.
Comment: Ok, do u know what kind of code I need to add or how I would need to adjust my current one?
Comment: Another possibility you have is to create event which will be responsible for notifying subscribers that `App.value1` changed and then you have to subscribe to that notification in your `StartPageViewModel` and update your `currentValue`
Comment: Via a messagingcenter function? I have heard of that but never actually used it. I would appreciate if you showed me how it could look like
Answer: You can proceed with something like that:
Make following changes to your App class and value1 property inside that class:
public static event PropertyChangedEventHandler PropertyChanged;

private static void OnPropertyChanged (string propertyName)
{
    var changed = PropertyChanged;
    if (changed != null)
    {
        PropertyChanged (null, new PropertyChangedEventArgs    (propertyName));
    }
}

private static int _value1;
public static int value1
{
    get { return _value1; }
    set
    {
        _value1 = value;
        OnPropertyChanged("value1");
    }
}

Then add this line to your StartPageViewModel constructor:
App.PropertyChanged += (sender, args) => OnPropertyChanged("currentValue");

In that code you are just leveraging PropertyChanged for your own purposes (you can even create your own event for that).
I mean StartPageViewModel subscribes to PropertyChanged event in Appclass, so it will be notified when value1 change. And when it actually occurs, then it is invoking his own PropertyChanged to notify View about currentValue change.
However, I would say better solution is to share View Model between MasterDetailPage and StartPage, because using global state makes your solution hard to understand :
public class SharedViewModel : INotifyPropertyChanged
{
    private ICommand clickCommand;
    private int currentValue;

    /* INotifyPropertyChanged implementation */

    public SharedViewModel()
    {
        ClickCommand = new Command(() => CurrentValue = CurrentValue + 1);
    }

    public ICommand ClickCommand
    {
        get { return clickCommand; }
        set
        {
           clickCommand = value;
           OnPropertyChanged("ClickCommand");
        }
    }
    public int CurrentValue
    {
        get { return currentValue; }
        set
        {
           currentValue = value;
           OnPropertyChanged("CurrentValue");
        }
    }
}

And you need to use the same instance of SharedViewModel in MasterDetailPage as well as StartPage
Comment: Gives me errors when I change from a protected virtual void to a private static void in my viewmodel. I also get these two errors on  `OnPropertyChanged("value1");` and `App.PropertyChanged += (sender, args) => OnPropertyChanged("currentValue");` it says: `An object reference is requiered to access non-static member 'Xamarin.Forms.BindableObject.PropertyChanged'`
Comment: Your `App` class is View Model?
Comment: I am so lost right now haha. Should I add this code in my projectname CS file? `public class App : Application` inside there?
Comment: First piece of code, you should add to file where `App` class reside, the second part is just one line to `StartPageViewModel` constructor
Comment: Yes, in that file where is your `value1` defined
Comment: I am going for the second option. Check my updated code in the post (scroll down). I get this error: `An object reference is requiered to access non-static member Xamarin.Forms.BindableObject.PropertyChanged`
Comment: I get so much errors from this. When I use the first option I get this error: `Keyword "this" is not valid in a static property, static method or static field initializer`
Comment: I have not got it quite right yet. But I have a good base to start off. I will most likely make a new post within a few hours with progress. Thanks
Comment: If you go for a second option, then you don't need this whole **static** stuff in `App` class. Anyway, the error is actually quite right, I didn't noticed that there is a `this` keyword in event raise. I modified code, so it should works fine now.