What is the right way to connect 7 conductors in an electrical box?

Question: What is the "right" way to join 7 different wires in a single electrical box?
Here's the situation. I opened up a four-gang light switch. There were four switches controlling five lights.
As expected, the four switches were interrupting the hot (black) wires.
The neutral (white) wires also went through this box.
The previous electrician had connected all the neutrals together--five lines going off to the lamps and the house neutral source--all told, 6 conductors. The solid copper wires were stripped about 1 inch, twisted together, and shoved in a wire nut that was probably intended to be used with about 3 conductors.
I had never seen 6 conductors twisted together like that.
I was replacing one of the switches with an RF switch so that I could control a patio light remotely from the car. The RF switch required neutral itself so that it could operate even when the circuit was open. So I had to add another pigtail from this neutral mess, and now there are seven neutrals all just twisted together in one big heap and shoved in a wire nut that was probably intended to be used with about 3 conductors.
Is there a "proper" way to do this or is this pretty much the state of the art?
Comment: It depends a lot on your regional code, i guess.
Comment: Be careful with the Ohmmeter, Joel :-) The neutral wires should of course NOT be shorted out against ground (they should read infinite, not 0), and the neutrals all need to be connected if you want current to flow and your lights to work.
Answer: Add pigtails between wire nuts. You might need 3 or 4 chained together for your situation, depending on the size of wire nut you use.
Comment: Exactly right. good comment.  + vote
Answer: You can get push-in connectors that can take up to 8 wires (assuming you have 14- or 12-gauge wire):

(Though there is some question about whether they're up to code. :)
Comment: @Shirlock - You should add this comment as an answer to [this](http://diy.stackexchange.com/questions/5141/are-push-in-connectors-up-to-code) question.
Comment: I really like these new connectors. My local inspector says if they carry a UL/CSA listing for a mechanical connector, they are fine. I guess it is a matter of semantics as these new type of connectors are not specifically mentioned in the NEC, but rather a general requirement for the UL/CSA standard  listing.
Comment: I used push-in connectors on my recent kitchen remodel to great benefit.  They make things a bit bulkier, so it's harder to fit everything into the electrical box, but it's worth it in time saved.  Twisting several wires together with a wire-nut is doable, but rather difficult for someone who isn't a professional electrician.
Comment: I'm lazy tester.  LOL.  but I still like those connectors.
Comment: If you want some flexibility (reopen the connection without ruining the wire ends) and even more ease of use, you can try these [http://www.wago.us/products/terminal-blocks-and-connectors/installation-connectors/compact-splicing-connectors-for-all-conductor-types-222-series/overview/ 222 series] but you will need two of the 5-pole type. (And don't miss to watch the video)
Answer: Since the neutrals do not need to be bonded together in this situation, you could put three together in one red or blue wirenut with a pig tail coming out for your RF switch, and then put the remaining white neutrals in a separate wirenut.
Comment: wait... what? Since there's only one actual neutral connection coming into the box, that one has to somehow connect to all five lamps, doesn't it?
Comment: Ok  I reread your question. Is there a single hot feed for all the light circuits?  If so, then the bridge between the two bundles is necessary.  Sorry, my bad!
Comment: Yeah, I should have taken a picture while I was there to explain it better. There's a single romex run to the panel which feeds everything.
Comment: every white is a neutral in this question. Maybe there are separate runs to the panel there. I certainly would not assume there is only one neutral. Easy way to check is put an OHM meter from each white to bare ground, they should read 0 ohms, that will confirm. Still shouldn't make any difference. Nome of the whites are hot,  cause they all were connected together before. If you want to be absolutely sure, put a bridge conductor between the two new bundles, but again, if any one in the bundle goes 0 ohms to ground, the entire bundle is neutral.
Comment: BTW, nice to see you here Joel.  thanks for starting this site.


Separation of variables and complex numbers

Question: I began with the Laplace's equation in the context of spherical harmonics.
From wikipedia, one reads.

So far I have followed, but in the sequel is stated that
$m \in \Bbb{R}$ since $\Phi$ is periodic. Then assume $Y(\theta,\varphi)$ is regular at the poles of the sphere ($\theta = 0,\pi$) this implies that $\lambda  = l (l+1)$ for some integer $l \geq |m|$.
Why is this so?
I tried to work with
$$\lim_{\theta \to 0}\lambda \sin^2 \theta + \frac{\sin \theta}{\Theta} \frac{d}{d\theta}\bigg(\sin\theta \frac{d\Theta}{d\theta}\bigg)  = m^2 $$
But could only arrive at
$$\lim_{\theta \to 0}\lambda \sin^2 \theta \bigg(\lambda  + \frac{\Theta''}{\Theta} \bigg)+ \sin \theta \cos \theta\frac{\Theta'}{\Theta}   = m^2 $$
What is the way to go?
Answer: Let's have a look at the radial equation that resulted from the separation of variables.  That equation is
$$\frac{d}{dr}\left(r^2\frac{dR(r)}{dr}\right)-\lambda R(r)=0 \tag 1$$
Now, using the Frobenius Method we write a series solution for $R(r)$ of the form
$$R(r)=\sum_{n=0}^{\infty}a_nr^{n+\alpha} \tag 2$$
Using $(2)$ in $(1)$ reveals that $\lambda =\alpha(\alpha+1)$ and $a_n=0$ for all $n\ne 0$.
Therefore, the differential equation for $\Theta$ becomes
$$\frac{d}{d x} \left[ (1 - x^2) \frac{d}{d x} \bar\Theta(x) \right] + \left[ \alpha (\alpha + 1) - \frac{m^2}{1 - x^2} \right] \bar\Theta(x) = 0 \tag 3$$
where $x=\cos \theta$ and $\Theta(\theta)=\bar\Theta(\cos \theta)$.  It can be shown that solution to $(3)$ is given by
$$\bar\Theta(x) = \frac{1}{\Gamma(1-m)} \left[\frac{1+x}{1-x}\right]^{m/2} \,_2F_1 (-\alpha, \alpha+1; 1-m; \frac{1-x}{2}) \tag 4$$
where $\Gamma$ is the Gamma Function and $_2F_1$ is the Hypergeometric Function.
The expression is $(4)$ can be shown to have a singularity at $x=-1$ unless $\alpha$ is an integer, say $\ell$ and $m$ is restricted by $-\ell \le m\le \ell$.  In that case, solutions to $(4)$ are polynomials called the Associated Legendre Polynomials.
Comment: As a side comment it should read $-m \leq \ell \leq m$ in the last sentences.
Comment: @Leucippus Thank you!  And nice catch!  +1  It is that restriction that is the source of the OP's question, I believe.  The ODE has solutions for non-integer $\ell$, but those have undesirable singularities.  Another important point to note that neither of us raised is that the Spherical Harmonics form a complete orthogonal set.  That is vital to the general expansion.  Hope that you're doing well.  I am still at home in recovery - hopefully just 1 more week on the wound vac device!
Comment: As always a good presentation and set of comments. There is, indeed, a restriction on $\ell$.
Comment: How can $(4)$ be shown?
Comment: @ConradoCosta Substitute the solution into $(4)$ and see that you get the ODE for $_2F_1$.
Comment: @Dr.MV, Thank you for your kindness. I am studying legendre polynomials, and I can see that they solve for $\lambda = l(l+1)$ with $l \in Bbb{Z}$. I am not pursuing Frobenius method yet. Since the Differential operator that defines Legendre polynomials is  self-adjoint. I guess it remains to show that the solutions of that form (the legendre polynomials) are a complete orthonormal set. This will show that for no other $\alpha$ the above problem admits solution. I might be a while on this matter.
Comment: I believe so, still It will take me some time to understand all the way until the conclusion that if $\alpha \in \Bbb{Z}$ then we obtain a solution (as you mentioned there is a singularity at $x = -1$) could you explain why this singularity  is an issue?
Comment: The singularity is only an issue if the points $\theta =0$ and $\theta =\pi$ are in the domain of the problem.  If those points are in the domain, and if we seek non-singular solutions, then we retain only solutions for which $\alpha$ is an integer
Answer: \begin{align}
\lambda \, \sin^{2}\theta + \frac{\sin\theta}{F} \frac{d}{d\theta}\left(\sin\theta \, \frac{dF}{d\theta}\right) = m^{2}
\end{align}
leads to
\begin{align}
\frac{1}{\sin\theta} \, \frac{d}{d\theta}\left(\sin\theta \, \frac{dF}{d\theta}\right) + \left[ \lambda - \frac{m^{2}}{\sin^{2}\theta} \right] \, F = 0
\end{align}
or
\begin{align}
F'' + \frac{\cos\theta}{\sin\theta} \, F' + \left[ \lambda - \frac{m^{2}}{\sin^{2}\theta} \right] \, F = 0.
\end{align}
Since $\lambda$ is an arbitrary separation constant let $\lambda = l(l+1)$. This leads to the form of the associated Legendre differential equation and has solution
\begin{align}
F(\theta) = A \, P_{l}^{m}(\cos\theta) + B \, Q_{l}^{m}(\cos\theta).
\end{align}
Since $\theta \to 0$ is a required component of the problem then $B=0$ to keep the solution bounded.
Comment: @Leucippus If $\ell$ is not an integer with $|m|\le \ell$, then the solutions to the ODE have a singularity at $\theta = \pi$.  Thus, in order for solutions to be non-singular, we must have $\ell$ an integer and we also must restrict $m$.  Interesting stuff.
Comment: but why the boundary conditions imply that $\lambda = l (l+1)$?
Comment: @ConradoCosta 1) The form of the Associated Legendre Polynomials requires it to be that way; 2) The boundary conditions require a solution to be bounded as $\theta \to 0$ and $F(\theta+2\pi) = F(\theta)$, ie being continuous from one full rotation to the next.
Comment: Could you explain 1) in greater detail? that is indeed my question.
Comment: @ConradoCosta It is defied by the $m^{th}$ derivative of $P_{l}(x)$ multiplied by a factor as seen in the Associated Legendre Wiki page https://en.wikipedia.org/wiki/Associated_Legendre_polynomials.
Comment: Sorry I wasn't clear, the question is why $\lambda = l (l+1)$, in your answer you choose $\lambda = l(l+1)$ but this is a necessary form of $\lambda$? apparently yes, but this is what I fail to see.
Comment: @ConradoCosta It was clear in what was being asked. In general $\lambda$ is an arbitrary constant which is subject to change. There are two reasons why it changes to $\lambda = n(n+1)$ for $n$ being an integer. The reasons are: 1) the boundary conditions are $\theta \to 0$ and $F(\theta + 2 \pi) = F(\theta)$ and 2) the form of the differential equation has been defined as "known" with particular parameters. In this case it is the Associated Legendre polynomial. It kind of falls under "known forms" because they have been defined for many years and in today's view are considered as "accepted".
Comment: I believe your answer is correct and complete, I just am unable to learn from it since I don't see clearly why $\lambda = l (l+1)$. I am reading about Legendre polynomials and Sturm-Liouville problems. Maybe after this excursion I will be able to reach the answer.
Comment: @ConradoCosta It does take some understanding and acceptence. Books by T. S. Chihara, "Orthogonal Polynomials", and E. D. Rainville, "Special functions", start by these constants of differential equations being known.


Package Creation Error

Question: I was experimenting with building packages, and I got into a bit of a trouble. After setting everything up, I ran
dch -i

And edited the changelog to look like this:
packagekit-qt (0.9.5-2ubuntu2) wily; urgency=medium

  * A new package

 -- Ranveer Aggarwal <firstname.lastname@example.com>  Wed, 27 May 2015 21:26:46 +0530

packagekit-qt (0.8.8-2ubuntu1) saucy; urgency=low

  * Merge from Debian unstable (LP: #1217699). Remaining changes:
    + Add alternative recommendation of python3-aptdaemon.pkcompat

 -- Sebastian Heinlein <firstname.lastname@example.com>  Wed, 28 Aug 2013 07:14:56 +0200

packagekit-qt (0.8.8-2) unstable; urgency=low

  * Upload to unstable

 -- Matthias Klumpp <firstname.lastname@example.com>  Sun, 23 Jun 2013 22:42:21 +0200

packagekit-qt (0.8.8-1) experimental; urgency=low

  * New upstream release: 0.8.8
  * Do not depend on system-interface virtual package
  * Adjust packaging to SONAME bump

 -- Matthias Klumpp <email@example.com>  Tue, 04 Jun 2013 14:50:38 +0200

packagekit-qt (0.8.7-2) experimental; urgency=low

  * New upstream release: 0.8.7

 -- Matthias Klumpp <email@example.com>  Tue, 19 Mar 2013 20:34:27 +0100

packagekit-qt (0.8.6-1) unstable; urgency=low

  * Initial release (Closes: #468132)

 -- Matthias Klumpp <firstname.lastname@example.com>  Sun, 02 Dec 2012 22:17:35 +0100

And then, I ran
debuild

but, I was greeted by the following error:
This package has a Debian revision number but there does not seem to be
an appropriate original tar file or .orig directory in the parent directory;
(expected one of packagekit-qt_0.9.5.orig.tar.gz, packagekit-qt_0.9.5.orig.tar.bz2,
packagekit-qt_0.9.5.orig.tar.lzma,  packagekit-qt_0.9.5.orig.tar.xz or new.orig)
continue anyway? (y/n) y
 dpkg-buildpackage -rfakeroot -D -us -uc
dpkg-buildpackage: source package packagekit-qt
dpkg-buildpackage: source version 0.9.5-2ubuntu2
dpkg-buildpackage: source distribution wily
dpkg-buildpackage: source changed by Ranveer Aggarwal <firstname.lastname@example.com>
 dpkg-source --before-build new
dpkg-buildpackage: host architecture amd64
 fakeroot debian/rules clean
dh clean --parallel
   dh_testdir -O--parallel
   dh_auto_clean -O--parallel
   dh_clean -O--parallel
 dpkg-source -b new
dpkg-source: error: can't build with source format '3.0 (quilt)': no upstream tarball found at ../packagekit-qt_0.9.5.orig.tar.{bz2,gz,lzma,xz}
dpkg-buildpackage: error: dpkg-source -b new gave error exit status 255
debuild: fatal error at line 1376:
dpkg-buildpackage -rfakeroot -D -us -uc failed

Doing an ls in my main directory returns this:
debian  packagekit-qt_0.9.5.orig.tar.xz

Where could I be going wrong?
Comment: The tarball should be in the grandparent directory of `debian`, IIRC. The path should look like this: `foo->packagekit-qt->debian`, `foo->packagekit-qt_0.9.5.orig.tar.xz`. Do everything relative to `packagekit-qt`.
Comment: You're right. That was the only mistake :/ This was kinda my first time packaging, so I seem to have to made a silly mistake. I'll do more research before posting a doubt here next time.
Comment: That's okay. At least your folders don't have version numbers in the name. If that was all, I'll post it as answer.
Comment: Yep! Please post it as an answer. Just putting the same version number as the folder name works. Basically, `debian` should have been in the source folder
Comment: It will work, but dch -i will rename the directory as well when changing the version. Made my first few tries very annoying since your $PWD is no longer a valid path. Took me ages to figure out I didn't need the number there.
Answer: The tarball should be in the grandparent directory of debian. The layout should look like this:

foo->packagekit-qt->debian
foo->packagekit-qt_0.9.5.orig.tar.xz.

Do everything relative to packagekit-qt.

Package Creation Error


How to load child node on expand kendo treeview

Question: I want to create a treeview with nodes from folders and files on my PC. User can drag and drop nodes.
My design view (cshtml) :
@(
    Html.Kendo().TreeView()
        .Name("treeview")
        .Events(ev=>ev.Expand("onExpand"))
        .BindTo((IEnumerable<TreeViewItemModel>)ViewBag.ParentNode)
)

My Controller :
public class HomeController : Controller
{
    public ActionResult TreeView()
    {
        ViewBag.ParentNode = GetDefaultNode();
        return View();
    }
    private IEnumerable<TreeViewItemModel> GetDefaultNode()
    {
        List<TreeViewItemModel> defaultNode = new List<TreeViewItemModel>();
        string[] drivers = Directory.GetLogicalDrives();
        for (int i = 0; i < drivers.Length; i++)
        {
                TreeViewItemModel node = new TreeViewItemModel();
                node.Text = drivers[i];
                node.Url = drivers[i];
                defaultNode.Add(node);
                GetChildNode(node);
        }

        return defaultNode;
    }
    private void GetChildNode(TreeViewItemModel item)
    {
        if (Directory.Exists(item.Text))
        {
            try
            {
                string[] dirNodes = Directory.GetDirectories(item.Text);
                if (dirNodes.Length > 0)
                {
                    for (int i = 0; i < dirNodes.Length; i++)
                    {
                        TreeViewItemModel child = new TreeViewItemModel();
                        DirectoryInfo dirInfo = new DirectoryInfo(dirNodes[i]);
                        child.Text = dirInfo.Name;
                        child.Url = dirInfo.FullName;
                        child.HasChildren = true;
                        item.Items.Add(child);
                        child.Items.Add(new TreeViewItemModel());
                    }
                }
                string[] fileNodes = Directory.GetFiles(item.Text);
                if (fileNodes.Length > 0)
                {
                    for (int f = 0; f < fileNodes.Length; f++)
                    {
                        TreeViewItemModel child = new TreeViewItemModel();
                        FileInfo fileInfo = new FileInfo(fileNodes[f]);
                        child.Text = fileInfo.Name;
                        child.Url = fileInfo.FullName;
                        child.HasChildren = true;
                        item.Items.Add(child);
                    }
                }

            }
            catch { }

        }
    }
}

It show root node and child of root node.
I want child nodes load on user expand root node. So I declare events onExpand in treeview, but I don't know how to pass a current expand node to controller, and get a list of nodes on view, after that insert it to current expand nodes.
I had searched a lot on this page and google, but can't find the way to solve my problems.
ps:sorry because I'm not good in English, hope you can understand my mean.
Update:
I change to use Binding to remote date but i still have not solved my problems.
My cshtml:
    @(Html.Kendo().TreeView()
.Name("treeview")
.DataTextField("Text")
.DataUrlField("Url")
.DataSource(dataSource => dataSource
    .Read(read => read
        .Action("GetRoot", "Home")
    )
)
)

My controller:
        public JsonResult GetRoot()
    {
        return Json(GetDefaultNode(), JsonRequestBehavior.AllowGet);
    }
    private IEnumerable<TreeViewItemModel> GetDefaultNode()
    {
        List<TreeViewItemModel> defaultNode = new List<TreeViewItemModel>();
        string[] drivers = Directory.GetLogicalDrives();
        for (int i = 0; i < drivers.Length; i++)
        {
                TreeViewItemModel node = new TreeViewItemModel();
                node.Text = drivers[i];
                node.Url = drivers[i];
                defaultNode.Add(node);
                GetChildNode(node);
        }

        return defaultNode;
    }
    private void GetChildNode(TreeViewItemModel item)
    {
        if (Directory.Exists(item.Text))
        {
            try
            {
                string[] dirNodes = Directory.GetDirectories(item.Text);
                if (dirNodes.Length > 0)
                {
                    for (int i = 0; i < dirNodes.Length; i++)
                    {
                        TreeViewItemModel child = new TreeViewItemModel();
                        DirectoryInfo dirInfo = new DirectoryInfo(dirNodes[i]);
                        child.Text = dirInfo.Name;
                        child.Url = dirInfo.FullName;
                        item.Items.Add(child);
                    }
                }
                string[] fileNodes = Directory.GetFiles(item.Text);
                if (fileNodes.Length > 0)
                {
                    for (int f = 0; f < fileNodes.Length; f++)
                    {
                        TreeViewItemModel child = new TreeViewItemModel();
                        FileInfo fileInfo = new FileInfo(fileNodes[f]);
                        child.Text = fileInfo.Name;
                        child.Url = fileInfo.FullName;
                        item.Items.Add(child);
                    }
                }

            }
            catch { }

        }
    }

And this is result:

As you see, it only show root nodes without child nodes.When i debug, root nodes contain childs
Comment: You can use remote data binding, take a look on example at docs in mvc http://demos.telerik.com/aspnet-mvc/treeview/remote-data-binding
Answer: Problems solved. When using remote databinding, nodes only load on the same level.When onExpand fire, it will call method GetNodes again.
 public JsonResult GetNodes(string id)
    {
        List<Node> node = new List<Node>();
        List<string> drivers=new List<string>();
        if (string.IsNullOrEmpty(id))
        {
            drivers.AddRange(Directory.GetLogicalDrives());
        }
        else
        {
            if(Directory.Exists(id))
                drivers.AddRange(Directory.GetDirectories(id));
        }

            try
            {
                for (int i = 0; i < drivers.Count; i++)
                {
                    Node item = new Node();
                    DirectoryInfo dirInfo = new DirectoryInfo(drivers[i]);
                    item.id = dirInfo.FullName;
                    item.Name = dirInfo.Name;
                    item.hasChildren = HasNodes(drivers[i]);
                    node.Add(item);
                }
            }
            catch { }

        return Json(node, JsonRequestBehavior.AllowGet);
    }


Problems with raster prediction from linear model in r

Question: I'm having problems with predicting a raster using a linear model.
Firstly i create my model from the data found in my polygons.
  # create model
  poly <- st_read("polygon.shp")
  df <- na.omit(poly)
  df <- df[df$gdp > 0 & df$ntl2 > 0 & df$pop2 > 0,]

  x <- log(df$ntl2)
  y <- log(df$gdp*df$pop2)
  c <- df$iso
  d <- data.frame(x,y,c)

  m <- lm(y~x+c,data=d)

Then i want to use raster::predict to estimate an output raster
  # raster data
  iso <- raster("iso.tif")
  viirs <- raster("viirs.tif")

  x <- log(viirs)
  c <- iso

  ## predict with models
  s <- stack(x,c)
  predicted <- raster::predict(x,model=m)

however i get following response:
Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) :
  object is not a matrix

I don't know what the problem is and how to fix it. My current throughts are that its something to do with the factors/country codes:
My model includes country codes, as I would like to include some country fixed effects. Maybe there is a problems with including these. However even when excluding the country codes from the model and the entire dataframe, i still get the same error message.
Futhermore, my model is based on regional values from the whole world and the prediction datasets only include the extent of Turkey. Maybe this is the problem?
And here is the data:
https://drive.google.com/open?id=16cy7CJFrxQCTLhx-hXDNHJz8ej3vTEED
Comment: Try to test the structures of your train/test data with str(data) to see if they have the same format.
Comment: The training data is a dataframe with x and y values, and the test data is a raster of x values. Apart from that i cannot see any differences, although i dont know what i should be looking for.
Comment: You should look for types of data: Are both train and test matrices? Are the x-values numerical in both train and test?
Comment: please provide a simple, reproducible example that comes with its own data. See e.g. ?raster::predict about how to make one. The error seems to be that `x` is not what you want to use in `predict`.
Answer: Perhaps it works if you do like this:
iso <- raster("iso.tif")
viirs <- raster("viirs.tif")
s <- stack(log(viirs), iso)
names(s) <- c("x", "c")

predicted <- raster::predict(s, model=m)

It won't work if the values in df$iso and iso.tif don't match (is one a factor, and the other numeric?).


How to extract heavily corroded anode rod?

Question: I obviously waited too long to replace the anode rod in my water heater, because after finally (with much cussing) getting the rod unthreaded, I found that it was so heavily corroded that it won't fit through the opening in the tank.
I can pull it up about an inch, and see the rod is there, hanging by a cable down its center. But the corrosion has expanded it to a larger diameter than the threaded opening, so I can't pull it any further out.
Is there any way to extract the rod at this point, or am I now just waiting for the tank to fail and buying a new heater?
Or would it be better to cut the old rod loose and let it rust in the bottom of the tank, and install a new rod?
Additional information in response to comments:

I don't have a record of when exactly I installed the heater, but it is marked with a manufacturing date of 2006. I haven't changed the anode since it was installed.

My water is fairly hard and I don't have a softener (Thinking this might affect how long the anode lasts)
Comment: you definitely got the most from this tank. 14 years is the golden years in tank life. Good maintenance keeps it heating.
Answer: If its corroded and enlarged all the way to the bottom you may have to cut it loose. In the tank it will continue being dissolved by the minerals until there's nothing left. And while that's happening the new rod will be in place.
You can try wrenching it out and probably break off chunk's of anode. This also shouldn't be an issue unless you plan on flushing the tank in which case there may be debris blocking the port. But these pieces will eventually dissolve. too.
Comment: I'm worried if I force it out I'll damage the threads and not be able to get a good contact and pressure seal for the new anode. Am I overthinking this?
Comment: It's good  to consider all outcomes. I don't think the Anode rod will damage the steel threads, but if you'd rather use finesse try breaking the larger sections with pliers. It may be thin enough for removal further down.
Comment: If not cut the rod above the bulbous section and let it sink so you can get the new one in place.
Comment: @JimStewart -- for a 2006 tank, that'd be 14 years, which isn't doing too terribly badly, especially if the tank only has a 6 year warranty on it
Comment: @ojait does the enlarged anode mean that the OP is removing the anode prematurely?
Comment: @JimStewart, I don't have a record of when exactly I installed the heater, but it is marked with a manufacturing date of 2006. I haven't changed the anode since it was installed. I'll edit my question to include this information.
Comment: Did you have any trouble getting the anode rod loose? Is this tank in a location where a full rupture would flood the structure or is it in a better placement such as a garage?
Comment: @JimStewart, I managed to strip the head of the rod trying to get it loose, but then I was able to get a pipe wrench on it and that got it out reasonably easily. It's in the basement, which is used for storage, so not the best place to let 50 gal of hot water loose,
Comment: "strip" meaning turning the hexagonal cap round, not damaging the threads.
Comment: It is 50 gal if you are home and aware of the failure of the tank. If no one is home, then . . .


Get name of specific Exception

Question: Is this the best method for getting the name of a specific Exception in C#:
ex.GetType().ToString()

It is in a generic exception handler:
catch (Exception ex)

Answer: ex.GetType().Name or ex.GetType().FullName for the fully qualified name.
Answer: Try ex.GetType().Name
try
{
    object test = null;
    test.ToString();
}
catch (Exception ex)
{
    Console.WriteLine(ex.GetType().Name);
}

Gives this..
NullReferenceException

Get name of specific Exception


SQLite to WPF in MVVM pattern

Question: I am starting a project from scratch in WPF using SQLite.I want to use the latest technologies and best practices and want to use MVVM pattern.
what is the best way to start with?
Using Linq to SQL
Any other ORM
or using datatable to List collection and observable collection?
and also how can I update/delete data from SQLite if I use Observable collection?
Any one can help me?
Answer: Since you mentioned best practice, why don't you write unit tests first. It will also help you think abstract.
In addition I would use entity framework rather than linq-to-sql.
Comment: Thank you david.After your reply I searched some of the articles, i found that L2S is better for smaller database/App than EF.Any pointers if you have hands on L2S and EF?Any idea how can I use sqllite to linq2 SQl-or EF?
Comment: As far as I've read L2S is no longer activly developed although some fixes may come out for it in framework updates. The main focus for development is on EF and I highly recomend using it as that would be the latest technology microsoft has for ORM.
Comment: @Dotnet Use google. There are so many tutorials and blogs about what you are asking. And according to my experience, if you relatively have a small project, you may not need MVVM nor database.

SQLite to WPF in MVVM pattern


IS it Possible in mysql to pass Multiple whereBetween clause for same fields?

Question: Here this would be my query:
SELECT *
FROM `table`
WHERE `x` BETWEEN 20 AND 80
  AND `x` BETWEEN 120 AND 140

?
Comment: The same single value cannot match these 2 conditions at the same time. Maybe you need in OR instead of AND between your BETWEENs?
Answer: Your code is already correct. You should try enclosing the two Between statements inside a parenthesis. Like this
SELECT * FROM `table` WHERE (`x` BETWEEN 20 AND 80) AND (`x` BETWEEN 120 AND 140);

Or for OR
SELECT * FROM `table` WHERE (`x` BETWEEN 20 AND 80) OR (`x` BETWEEN 120 AND 140);

To make the code understandable by the compiler and by the person who will read the code.
Comment: Thanx! Will try to make it work with KnexRaw
Comment: Okay @Aviralkumar goodluck~ I hope you'll make it work. Have a nice Day!


C++ Get Total File Line Number

Question: Is there a function I can use to get total file line number in C++, or does it have to be manually done by for loop?
#include <iostream>
#include <ifstream>

ifstream aFile ("text.txt");
if (aFile.good()) {
//how do i get total file line number?

}

text.txt
line1
line2
line3

Answer: I'd do like this :
   ifstream aFile ("text.txt");
   std::size_t lines_count =0;
   std::string line;
   while (std::getline(aFile , line))
        ++lines_count;

Or simply,
  #include<algorithm>
  #include<iterator>
  //...
  lines_count=std::count(std::istreambuf_iterator<char>(aFile),
             std::istreambuf_iterator<char>(), '\n');

Comment: +1 for the [`std::count`](http://en.cppreference.com/w/cpp/algorithm/count) variant.
Comment: in "while (std::getline(aFile , line))" what is line?
Comment: What's the advantage of the std::count variant?
Answer: There is no such function. Counting can be done by reading whole lines
std::ifstream f("text.txt");
std::string line;
long i;
for (i = 0; std::getline(f, line); ++i)
    ;

A note about scope, variable i must be outside for, if you want to access it after the loop.

You may also read character-wise and check for linefeeds
std::ifstream f("text.txt");
char c;
long i = 0;
while (f.get(c))
    if (c == '\n')
        ++i;

Comment: i got 0 for the second function
Comment: @NewFile You're right, `operator>>()` skips white space, of course. Thank you, fixed.
Answer: I fear you need to write it by yourself like this:
int number_of_lines = 0;
 std::string line;
 while (std::getline(myfile, line))
        ++number_of_lines;

 std::cout << "Number of lines in text file: " << number_of_lines;

Answer: Have a counter, initialized to zero. Read the lines, one by one, while increasing the counter (the actual contents of the line is not interesting and can be discarded). When done, and there was no error, the counter is the number of lines.
Or you can read all of the file into memory, and count the newlines in the big blob of text "data".
Answer: Solutions in https://stackoverflow.com/a/19140230/9564035 are good but not provide same output.
If you want to count lines only ended with '\n' use
#include<algorithm>
#include<iterator>
//...
    ifstream aFile ("text.txt");
    lines_count=std::count(std::istreambuf_iterator<char>(File),
    std::istreambuf_iterator<char>(), '\n');

If you want to count also line that not ended by '\n' (last line) you should use getLine solution
ifstream aFile ("text.txt");
std::size_t lines_count =0;
std::string line;
while (std::getline(aFile , line))
   ++lines_count;

Note that if you previously read from file you should set pointer to beginning of file for file.seekg(std::ios_base::beg);
Answer: Fast way then above solutions like P0W one
save 3-4 seconds per 100mb
std::ifstream myfile("example.txt");

// new lines will be skipped unless we stop it from happening:
myfile.unsetf(std::ios_base::skipws);

// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
    std::istream_iterator<char>(myfile),
    std::istream_iterator<char>(),
    '\n');

std::cout << "Lines: " << line_count << "\n";
return 0;

Comment: Using istreambuf_iterator instead of istream_iterator makes it 5 times faster in my experiments.
Answer: Just copy this & run.
#include <stdio.h>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    fstream file;
    string filename = "sample input.txt";
    file.open(filename.c_str()); //read file as string
    int lineNum = 0;
    string s;
    if (file.is_open())
    {
        while (file.good())
        {
            getline(file, s);
            lineNum++;
            cout << "The length of line number " << lineNum << " is: " << s.length() << endl;
        }
        cout << "Total Line : " << lineNum << endl;
        file.close();
    }

    return 0;
}

Comment: Explicitly asking for upvotes is against SO policy and your post has been edited to remove that part. However, you're unlikely to get any upvotes on an answer that recommends using `#include `.
Comment: I didn't know that SO policy. Thanks for your valuable feedback.

C++ Get Total File Line Number


Set subplot colors plotly R

Question: I have this code for subplots, i want to set de colors by a custom palette, but seems not to take any color.
data.frame(x = sample(letters[1:3],30,replace = TRUE)) %>%
  mutate(y = rnorm(30),
         z = runif(30,10,20)) %>%
  group_by(x) %>%
  do(p=plot_ly(.,x = ~y, y=~z, type = "scatter", mode = "lines", line = list(color = "blue","red","green")))) %>%
  subplot(nrows = 1,
                  shareX = FALSE,
                  shareY = TRUE,
                  margin = 0.0001)

Answer: One option to achieve your desired result would be to map the grouping variable on the color "aesthetic" and to set the custom palette via the colors argument where personally I prefer to make use of a named vector to assign colors to categories:
library(plotly)

set.seed(123)

data.frame(x = sample(letters[1:3], 30, replace = TRUE)) %>%
  mutate(
    y = rnorm(30),
    z = runif(30, 10, 20)
  ) %>%
  group_by(x) %>%
  do(p = plot_ly(., x = ~y, y = ~z, color = ~x, type = "scatter", mode = "lines", colors = c(a = "blue", b = "red", c = "green"))) %>%
  subplot(
    nrows = 1,
    shareX = FALSE,
    shareY = TRUE,
    margin = 0.0001
  )

Set subplot colors plotly R


www to non-www with removing extensions htaccess

Question: i've removed .php extensions first on my website. then i've forwarded www to non-www version. but there is a problem with that.
my .htaccess file looks like this:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^188\.166\.104\.194
RewriteRule (.*) http://example.com/$1 [R=301,L]

www forwards to non-www with that .htaccess. that is cool. but the problem is with the other files.
i'm now using: http://example.com/contact instead of: http://example.com/contact.php
but when you try to open http://www.example.com/contact that .htaccess forwards me to http://example.com/contact.php/
how do i fix that?
have a nice day!
Answer: Change the order of rules and some refactoring:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.example\.com|188\.166\.104\.194)$ [NC]
RewriteRule (.*) http://example.com/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

RewriteRule ^([^/]+)/$ $1.php [L]

RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php [L]

Make sure to test is after clearing your browser cache.


When running locally, does Juju use the host machine's APT cache?

Question: When juju  fetches packages for a unit, does it make use of the host system's APT cache? I'm asking this because in my case, bandwidth is limited and I am doing some charm development.
It is not really an option to have Juju continuously fetching packages every time I want to test a charm. Is there some way of having Juju cache the packages it fetches so that it doesn't have to download them all each time?
Answer: If you're using juju locally then it automatically caches debs using squid-deb-proxy.
Juju has an option to allow you to use other apt proxies on your network, see:

https://juju.ubuntu.com/docs/howto-proxies.html

You basically define it in your ~/.juju/environments.yaml for the specific environment, like so:
apt-http-proxy: http://10.0.3.1:8000

Comment: Great, thanks! After the first couple of deploys, I noticed decreased network usage so I assumed something was up :)


Undoing `chown` command?

Question: I was installing a few softwares which prompted that :
Download is performed unsandboxed as root as file couldn't be accessed by user '_apt'. - pkgAcquire::Run (13: Permission denied)
So I did:
sudo chown -Rv _apt:root /home/kpate352/
sudo chmod -Rv 700 /home/kpate352/
But now everything is messed up. I couldn't view my files and it prompts "Permission denied". I also tried doing:
sudo chown -R kpate352:kpate352 /home/kpate352
But it returns nothing.
How to undo the following commands:
sudo chown -Rv _apt:root /home/kpate352/
sudo chmod -Rv 700 /home/kpate352/
Comment: "*But it returns nothing*" is the normal behavior for success. That command's  output should only be error messages, if any.
Answer: Unfortunately you can't undo the changes made by chown or chmod. That's linux! Commands will actually do what you tell them to do. Better do a backup yourself next time.
However you can restore the default permissions for your home folder which will probably fix most of your issues.
First reset the owner of your home folder:
sudo chown -Rv kpate352:kpate352 /home/kpate352/

Then reset permissions for all files:
find /home/kpate352/ -type f -print0 | xargs -0 sudo chmod -Rv 644

Finally reset permissions for all folders:
find /home/kpate352/ -type d -print0 | xargs -0 sudo chmod -Rv 755

This should stabilise your situation.

Undoing `chown` command?


Can't send UTF-8 data through PHP

Question: I have a file called index.php which contains a form, which redirects the page to itself, and awaits some UTF-8 encoded data. My problem is, that the data that is sent through the form is exchanged to question marks by the browser.
Here's the code:
<?php header('Content-Type: text/html; charset=utf-8'); ?>
<!DOCTYPE html>

      <meta charset="utf-8" />

<?php
   if($_POST["action"] == "insert"){
        echo "
";
        print_r($_POST);
        echo "
";

        echo "Some simple UTF-8 text: țșțțáéáéáőúőúőúőúőúőúő";
   }
 ?>

    <form accept-charset="UTF-8" class="form-horizontal" role="form" name="myForm" action="index.php" method="post">
        <input type="hidden" name="action" value="insert">
        <input type="text" name="article_date" class="form-control" size="15" id="article_date" value="">
        <input type="text" name="test_field" value="áááéáéáéáéáéá">
        <input type="text" name="title" class="form-control" id="article_title" placeholder="Some placeholder" value="">
    </form>

If I run this file, and just send the form, as it is, I get this output:

Array
  (
      [action] => insert
      [article_date] =>
      [test_field] => ���������������������������������������
      [title] =>
  ) Some simple UTF-8 text: țșțțáéáéáőúőúőúőúőúőúő

So, what I gather from this, is that basically UTF-8 encoding in the browser is working, as the plain UTF-8 echo is displayed correctly, but when I try to send UTF-8 data through POST, it is not decoded correctly. What could a possible solution to this problem be?
Comment: Did you try to use htmlspecialchars($_POST['value']);
Comment: tried it now, no success:|
Comment: When you gave UTF-8 char statically in the editor it decodes it. I faced the same problem in sublime.
Comment: 1) Can you double check in the browser's inspector tools that the **Content-Type HTTP header** is actually sent correctly and not possibly overridden by your web server? 2) Do you have anything in your php.ini relating to `mbstring.http_input` or such set?
Comment: we are right now experimenting based on another answer from another question, with your point 2.). content type in the inspector tools seems to be UTF-8, so I don't think the problem comes from there:|
Answer:
Check your php.ini files has default_charset = "utf-8";
(Done) have on your PHP header: header('Content-Type: text/html; charset=utf-8');
(Almost done) in your HTML page:   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
And forehand, check the default encoding of the text editor you are using to write the code and if not, set it to UTF-8.
Check httpd.conf (assuming you are using Apache) and check AddDefaultCharset utf-8 is set.
If using it, add in .htaccess IndexOptions +Charset=UTF-8
Answer: try this..
I am using Notepad++ for this...
First time create new file and paste this code only..
<?php header('Content-Type: text/html; charset=utf-8'); ?>
<!DOCTYPE html>

      <meta charset="utf-8" />

After Save you file and close it. And check on Browser...
IMPORTANT: Don't Forgot to Close your file and Reopen..
Now once again open your file and paste this code...
<?php
   if($_POST["action"] == "insert"){
        echo "
";
        print_r($_POST);
        echo "
";

        echo "Some simple UTF-8 text: țșțțáéáéáőúőúőúőúőúőúő";
   }
 ?>

    <form accept-charset="UTF-8" class="form-horizontal" role="form" name="myForm" action="index.php" method="post">
        <input type="hidden" name="action" value="insert">
        <input type="text" name="article_date" class="form-control" size="15" id="article_date" value="">
        <input type="text" name="test_field" value="áááéáéáéáéáéá">
        <input type="text" name="title" class="form-control" id="article_title" placeholder="Some placeholder" value="">
    </form>

Then save your file and check it..
Basically First time our browser doesn't understand utf-8...after once upload the browser working fine...
Answer: The data entering your database is not uploading in UTF8 format.
Make sure :

use DEFAULT CHARSET=utf8 when creating new tables
use SET NAMES utf8 before you query/insert into the database

Or you should set charset during database connection $mysqli->set_charset("utf8");

Can't send UTF-8 data through PHP


If we give blank space in jQuery datatable CellEdit , the required validation doesn't work

Question: I have used jQuery datatable CellEdit ( https://github.com/ejbeaty/CellEdit ) for table inline editor. This is a free lib. It's working awesome. This lib already provides required field validation.
For required validations, need to mention the column index inside of the columns array. Please see this code.
"allowNulls": {
    "columns": [],
    "errorClass": 'error'
}

For example, The table has 5 columns. if we need required field validation for the first 3 columns means, then need to use columns:[0,1,2].
The above mentioned code was inside of the table.MakeCellsEditable function. For more info please read the documentation ( https://github.com/ejbeaty/CellEdit/blob/master/README.md ).
This validation working well if we click confirm button without fill any values in the text box.

But, if I just leave it blank space means, the validations don't work. So, I can able to save the value in my DB with blank values.
So, I need to validate with blank space also.
Comment: *able to save the value in my DB with blank values* When it is important, don't forget to back it up with server side validation. Never rely on client side validation only, as it is easy to bypass.
Comment: @Ageax Yeah sure. For my scenario, I don't need to submit the form. Before submitting the form, I need to validate my input. If we use server side, we couldn't able to achieve the above mentioned validation. I mean, need to set a border for that particular textbox. So, I choose this way. :)
Comment: Using client side validation to improve the UX is fine. However, if you're saving values to a database, that means you are submitting the form to the server. So you should *also* implement server side validation as a backup. Never rely on client side validation only :-) https://stackoverflow.com/questions/10460711/to-what-extend-should-i-rely-on-client-side-validation
Comment: Make sense. Thanks. I will do it server side validation also. :)
Answer: I have analyzed their core JS file. In that file, they are getting cell value like var newValue = inputField.val();
This code is present on inside of the updateEditableCell function. So, instead of this code, We need to use below code,
var OrgValue = inputField.val();
var newValue = OrgValue.trim();

Now, we can able to validate if the textbox has blank space.
Thanks,


how to grep two paragraph from file?

Question: i have file "test_file.txt". My output must contains all"IP  ADDRESS" and "MONTHS OF 2017" from file test_file.txt.
Server$
Server$cat test_file.txt
IP ADDRESS:
1. 172.17.17.17
2. 172.17.17.18
3. 172.17.17.19

NEKI TEXT 2
1 one
2 two
3 three
4 four
5 five

MONTHS OF 2017:
01.  January   2017
02.  February  2017
03.  March     2017
04.  April     2017
05.  May       2017
06.  June      2017
07.  July      2017
08.  August    2017
09.  September 2017
10.  October   2017
11.  November  2017
12.  December  2017
Server$

I found, egrep command but output does not contains all 12 Months from file.
Server$egrep -A3 "ADDRESS|MONTHS" test_file.txt
IP ADDRESS:
1 172.17.17.17
2 172.17.17.18
3 220.127.116.11
--
MONTHS OF 2017
01. January 2017
02. February2017
03. March 2017
Server$

How can I perform command which can have 3 IP address and 12 Months in output?
Comment: super. it works, thank you damadam ;)
Answer: I'd use awk in paragraph mode (by unsetting the record separator):
$ awk -vRS= '/^(IP ADDRESS|MONTHS)/' test_file.txt
IP ADDRESS:
1. 172.17.17.17
2. 172.17.17.18
3. 172.17.17.19
MONTHS OF 2017:
01.  January   2017
02.  February  2017
03.  March     2017
04.  April     2017
05.  May       2017
06.  June      2017
07.  July      2017
08.  August    2017
09.  September 2017
10.  October   2017
11.  November  2017
12.  December  2017

Perl has the same functionality:
 perl -00 -ne 'print if /^IP ADDRESS/ or /^MONTHS/' test_file.txt

Comment: Exactly what I need. :) very useful thank you
Comment: This should be the accepted answer...
Answer: Just do a double egrep :
egrep -A3 "ADDRESS" test_file.txt && egrep -A12 "MONTHS" test_file.txt

Explanation :
egrep -An  would match the word (and his line) and take n lines under that word thanks to -A option
test_file.txt is the file that we want to extract these lines
"ADDRESS" and "MONTHS" are searched word, inside "" statement
&& just execute each command one by one (but if the 1rst didn't work, the 2nd won't be done !)
Answer: It's very simple. You can use the below command.
grep -E "172|01" file.sh

The output is as below:
1. 172.17.17.17
2. 172.17.17.18
3. 172.17.17.19
MONTHS OF 2017:
01.  January   2017
02.  February  2017
03.  March     2017
04.  April     2017
05.  May       2017
06.  June      2017
07.  July      2017
08.  August    2017
09.  September 2017
10.  October   2017
11.  November  2017
12.  December  2017

Explanation:
if you grep only for 172 then the output would be
$ grep "172" file.sh
1. 172.17.17.17
2. 172.17.17.18
3. 172.17.17.19

if you grep only for 01, then
$ grep "01" file.sh
MONTHS OF 2017:
01.  January   2017
02.  February  2017
03.  March     2017
04.  April     2017
05.  May       2017
06.  June      2017
07.  July      2017
08.  August    2017
09.  September 2017
10.  October   2017
11.  November  2017
12.  December  2017

So you need both of these at once. To search for multiple patterns, we need to use the pipleline metacharacter (|) and since this is part of extended regex we need the -E option.
To learn more options for the grep command, you may find this article written by me helpful.
Comment: It won't work if the OP had months of 2016 or 2018 for example, your `grep` would print them also :/
Comment: @damadam Your own answer won't work either if there are more that 3 servers... (I'll give you the benefit of the doubt for the 12 months).

how to grep two paragraph from file?


3 way switches / multiple buildings / no neutral or ground in conduit

Question: I am installing two 3 way switches to control lights in my shed.   I have 3/4" conduit in the ground between the two locations.
I DO NOT want to run ground or neutral through the conduit.   Because of space and neutral/ground is available at both locations.
My main panel/meeter is on the side of the shed with a 200amp breaker.
There is sperate conduit to the house that has the wires to feed the main panel in the house basement.
Also on this panel at the shed, I have 4 unused breaker slots and ground and neutral bars.
Both the shed and houser panels have their own grounding rods in the ground based on code.
I am wring lights and outlets in the shed this week.
I want the lights on a 3 way switches.
My plan was to put a breaker in the house panel.   Ground the switch back to the house panel.   Hot to common on that switch.    Then run my two travelers out through the 3/4" conduit to the shed.
Then at the shed...travelers terminate at the 3 way.   This 3 way here common connects to my light.   The the neutral of my lights then terminates back to the panel here at the shed neutral bar.   The grounds of the lights and the 3 way switch at the shed terminate at the shed panel grounding bar.
Both sides are grounded.    The lights have a path to neutral and ground.   But no neutral or ground is in the conduit.
Now as far as the four open breaker slots in the shed panel.    2 will be for outlets in the shed and two will be for a hot tub in the future.
Any questions ?
Is this a bad idea ?
Comment: Schedule 40.    It was put in by an electrician and a electrical inspection was done at that time.
Comment: You want to violate NEC 300.3, to save the cost of 1 wire.  You wouldn't bootleg neutral off ground, but you feel OK bootlegging neutral from a different *panel*... which is just as bad really.
Comment: Is this the conduit that feeds power to the shed or some other conduit for the light-switch.
Comment: They are separate pieces.  There are three pieces of conduit in total. One is the main feed from the shed panel to the panel in the basement. One is for low voltage such as cable or phone lines. And the third is a smaller 3/4 in conduit for running 3-way switches
Comment: What type of conduit is in the ground?
Comment: Not bootleg anything.      All grounds and neutral are being used
Answer: Neutral is not Ground
They connect (bonded) in one location, usually the main panel. But they are not "the same". In particular, there are a number of instances where "ground can be connected to any place you have ground", but that is never the case for neutral. That is actually mostly for "retrofit ground" - i.e., you didn't have ground before and want to add it to an existing circuit, but there may be other instances where it is permitted. But you can't do that for neutral. Never.
Conduit as Ground
Rigid metal conduit (maybe some other metal types, I get confused) doubles as your ground (but never neutral). Unfortunately, based on comments you have PVC conduit, so you need a ground wire.
All Current Must Go Together
This is the key. On an unswitched circuit, that means hot & neutral together. On an old switch loop, that means hot & switched hot together. On a 3-way circuit, that means travelers and neutral or travelers and switched hot together. This is the key issue - you can't rationalize your way around it. No matter how you wire it (except smart switches) you will need 3 wires in the conduit (and possibly a 4th for ground).
The issue is not having a path for power to get back "home" - any neutral would do that. It is to have the current carrying conductors matched to avoid eddy currents. In addition, this would be guaranteed to trip any GFCI. You generally don't need GFCI on lighting, but that is simply because the life-safety issues are not nearly as common (cost-benefit), not to allow for crazy wiring schemes like this one.
Actual Real Danger!
There is actually one place where this could result in a serious problem - i.e., it isn't just code being nitpicky. If your 3-way lights are on and using neutral via the shed subpanel, and you turn off the feed to the subpanel to work on it, you will have power flowing through the neutral in the subpanel. In other words, you'd be working on a live panel without knowing it, which is an incredibly dangerous situation.
Comment: The shed panel is the main panel with the meter.    The main 200 amp breaker at the shed disconnects the house panel and the four breakers at the shed.
Comment: I may have it backwards for your particular configuration. But the end result is as I understand what you are describing would have hot from one panel (or subpanel) and neutral from the other panel (or subpanel). You can't do that, because in addition to being a clear code violation, it can result in someone getting burned. Literally.
Answer: AIUI code requires earth and neutral at all new switch boxes, you're not allowed to use the neutral from a different circuit.
So yes it's a bad idea and there's no way to make it work.
Comment: once it leaves the breaker box it's divided.  code says neutral must run parallel to the hot it serves in the same raceway
Comment: Neutral all goes back to a common neutral bar.   It's not divided up by circuit


How can I set the layout and the filters for an object exploration through the URL?

Question: Is there a way to open an object exploration of a certain object type and simultaneously set the layout of the exploration and add filters? I was looking at this page in the docs that explains how to define the filter values but I am not sure how to set a layout at the same time.
Answer: You can add a layout RID after the filters, to the end of your URL like this:
<code>https://<stack>.palantircloud.com/workspace/hubble/external/search/v2/{your filters}?layoutRid={layout_RID}
</code>


Gimp: I can't find any of the controls or toolbars that I used to be able to see

Question: I used to use Gimp and really liked it but it's been awhile. Now when I want to use it again, the only thing I can see is the tiny little box with the image. I can't find any of the controls or toolbars that I used to be able to see. Can I get that back? I can't use the program the way it is.
Answer: Open GIMP and the from the GIMP menu select Windows -> uncheck Hide Docks. This is also a useful feature if you're precisely cropping a large image and you temporarily need extra real estate in the image pane in order to show the whole image with a larger Zoom level.
Also see: I accidentally closed my GIMP toolbox. Can I get it back?. In the lower right-hand corner of the Toolbox window there is a blue button surrounded by a yellow arrow that says if you move the mouse cursor over it: "Reset to default values Shift Reset all tool options".


How to get Logitech M305 wheel tilting to work as forward/backward?

Question: I have the mouse specified in the Title. At the moment when I tilt the wheel left/right it works as horizontal scrolling (which I do not use at all). I would like it to work as backward/forward buttons (for example in Firefox).
For Windows there are drivers which allow these events' mapping to be changed. I haven't found any drivers for Linux. Is it possible to change it somehow?
Answer: I have one, and afaik, the best way to make use of the tilt buttons (and various other buttons on many Logitech Mice) is to use btnx, which is in the repos.
I set my M305 tilts to control+page down/up, which handles tab shifting in many applications, but you could set it to whatever keystroke in FF goes back and forward.
There is also a closed source program, HIDPoint which claims to mimic Setpoint, but I haven't really tried it.
Comment: Thanks a lot! This is a great way around. Works perfectly :)


Matrix analysis , inequalities , diagonal entries

Question: Suppose we have an invertible positive definite matrix and we know its diagonal elements when seen as a vector are in increasing order , what can be said about  diagonal vector of its inverse ? , if it's in increasing order or decreasing order etc
Answer: No:
for example
$\begin{pmatrix}
3 & 1 & 1 \\
1 & 4 & 3 \\
1 & 3 & 5
\end{pmatrix}$
has an inverse where the diagonal elements are not in order
$\begin{pmatrix}
\;\;\frac{11}{30} & -\frac1{15} & -\frac{1}{30}\\
-\frac1{15} & \;\;\frac{14}{30} & -\frac4{15}  \\
-\frac{1}{30} & -\frac4{15} & \;\;\frac{11}{30}
\end{pmatrix}$


Two relationships between two same models/tables

Question: Problem
Hello, I'm having some trouble trying to make work two relationships between the two models (Laravel 5.5): Order and User.
1-----m | A User (as a customer) can make many Orders
1-----m | A User (as an employee) can take many Orders
So, in my orders table I have user_id and employee_id as foreign keys.
Now, some orders doesn't have an initial employee_id because orders need to be accepted, then I set up that value.
Using tinker, I've located this Order object (id:30), it has a user_id and a employee_id but when I dd() it, this returns:
=> App\Models\Order {#882
     order_id: 30,
     user_id: 7,  // <-- foreign key
     employee_id: 6,  // <-- foreign key
     restaurant_id: 4,  // <-- foreign key (for other table)
     // ...
     total: "120.00",
     created_at: "2018-01-31 00:15:41",
     updated_at: "2018-01-31 00:15:41",
     deleted_at: null,
     restaurant: App\Models\Restaurant {#900 // <- MY RESTAURANT RELATION (M-1)
       restaurant_id: 4,
       name: "Stark, Padberg and Buckridge",
       // ...
       // ...
       created_at: "2018-01-12 18:18:17",
       updated_at: "2018-01-12 18:18:17",
       deleted_at: null,
     },
     customer: App\Models\User {#914 // <- MY CUSTOMER RELATION (M-1)
       user_id: 7,
       restaurant_id: 4,
       // ...
       created_at: "2018-01-30 17:52:33",
       updated_at: "2018-01-30 23:32:00",
       deleted_at: null,
     },
     deliverer: null,  // <-- THIS SHOULD CONTAIN THE EMPLOYEE DATA
//                            THAT BELONGS TO THE DELIVERER RELATION
     }

What am I doing wrong?
-----
Information of my logic.
Models
Order
In my Order model I've defined the relationships (among other ones) as follows (all my primary keys follow this convention: model_id):
/**
 * Return the user who created the order.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function customer()
{
    return $this->belongsTo(
        'App\Models\User',
        'user_id',
        'user_id'
    );

}

/**
 * Return the employee (user) who deliver the order.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function deliverer()
{
    return $this->belongsTo(
        'App\Models\User',
        'employee_id',
        'user_id'
    );
}

User
/**
 * A customer can make many orders
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function ordersMade()
{
    return $this->hasMany('App\Models\Order',
        'user_id',
        'user_id'
    );
}

/**
 * An employee attends many orders.
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function ordersDelivered()
{
    return $this->hasMany('App\Models\Order',
        'employee_id',
        'user_id'
    );
}

Tables
This is the schema of my orders table:

This is the schema of my users table:

Update
Yes, I have users with ids 6 and 7:

In Tinker i've done:
>>> $o = App\Models\Order::find(30);
>>> $o->customer;
>>> $o->restaurant;
>>> $o->deliverer;
>>> $o;

Comment: Do you have a user with id 6 ?
Comment: @MahdiYounesi oh my god. I've forgot that I have the softDeletes activated, so the record will perdure but "logically" the object is deleted. I feel so stupid, i've been reviewing my code almost a couple of hours.
Comment: @HCK glad your problem is solved
Comment: Can you show what you're running in Tinker to get that output?
Comment: @MahdiYounesi I've updated my question to add the requested information.
Comment: @Jonathon I've updated my question to add the requested information.
Answer:
Well, there wasn't any problem with my code. I have the softDeletes set to true on my models, so I was trying to get a property of a "deleted" element.
As simple as that. Thanks to @MahdiYounesi, who made me check that.
although the problem was almost a stupid one, is a good remainder to note that when you need to also return softDeleted records when querying from an entity, you could just -as the docs says- add withTrashed() in each query that needs this kind of results, or directly in the model when defining the relationship like this:
/**
 * Return the user who created the order.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function customer()
{
    return $this->belongsTo(
        'App\Models\User',
        'user_id'
    )->withTrashed();

}

/**
 * Return the employee (user) who deliver the order.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function deliverer()
{
    return $this->belongsTo(
        'App\Models\User',
        'employee_id',
        'user_id'
    )->withTrashed();
}

This will collect the "deleted" data, usefull for historical information for example.


How do I make my gas oven produce less carbon monoxide?

Question: I had someone perform a combustion safety test on my oven today and he discovered that it's producing an elevated level of carbon monoxide compared to average: 80 PPM. He said the best ovens he's seen produce about 10 PPM. He said that I could get somebody out here to "adjust" it to improve the combustion but wasn't too sure what this would entail.
What does this entail? Is there like a user-serviceable knob on the oven to adjust the air mixture or something that I can do myself? If not, or if it's not safe for me to do this myself, who do I need to hire and what do I need to ask them to do? Or is the oven itself simply totally defective and in need of replacement? It's not a fancy high-end unit but it's fairly new...
Comment: I don't know anything about adjusting ovens, but: are you sure this is worth pursuing? If 10 PPM is "the best," what is typical? What was the level in the rest of the kitchen (which is really the value that matters)? I agree with @SomeGuy, this seems like a casual test procedure. I would get a CO detector and keep an eye on it. If you get one with a digital readout it will tell you the PPM in the air. I'm surprised the CO specialist did not seem to have anything helpful to say about the result.
Comment: Most CO detectors don't alarm until CO is high enough to make a healthy young adult sick - the UL standard requires they not go off until 80ppm - which is plenty to make senior citizens and young children VERY sick. Get a "low level" CO detector.
Comment: I looked into that, but a low-level CO detector was expensive. Instead, I saved the money and replaced the gas range with an induction range, which produces no CO.
Answer: Great questions can always be asked with only a few words.
But my answers never seem short.
The short answer is that the stove can not breathe. Give it more air. Problem Fixed.

What is happening, the chemistry answer:
Carbon Monoxide is made when too much natural gas is burning in too little oxygen.
Good ->  Natural Gas + Lots of Oxygen + Spark = Carbon DIOXIDE + Water + 100% Heat
Bad ->   Natural Gas + Not enough Oxygen + Spark = Carbon MONOXIDE + Water + 50% Heat

You now know how CO (carbon monoxide) is made, and that making it wastes energy.
It also stops blood from working. That is a different lesson.

An oven burner while it is working. Gas Valve, Gas line orifice,and Venturi Tube. Flame Manifold.

Short rant about poor quality testing:
Breathing air with 10 ppm of CO is better than breathing air with 80 ppm.
However
I hate that you were told this by someone you were hoping could improve your safety, it is a case of a little knowledge is dangerous.
I think it is great that you had a test conducted.
People that put any effort into testing are almost always better off than those who do not. Just because they are people who at least think about such things.
It annoys me that the guy that did the testing was so unknowledgeable. I am sure he intended to be helpful. Sadly he left more questions than answers.

Much longer rant about bad test procedures:
If I tell you my car gets 0 miles per gallon, you might think that is bad.
If I add that I got this measurement after I was trying to climb Mt Everest in my car, It then makes sense. Well, 0 miles a gallon makes sense. Conducting a test like that, it makes no sense.
You have to know what you are testing, and you have to be testing the same thing.
I tell you 80 ppm of CO is high, and I have seen 10 ppm, who knows what that means?
Was the oven running for 5 minutes or 30, was it preheated to 400 degrees, or 100, was he 1 foot away or 3, was he using an in date calibrated meter, was the air in the room moving or still, was the room 68 degrees or 78 ?
I am not asking you these questions, but they are valid questions, and I am wondering if he took all this information into account when he gave you the number of 80 ppm.
If he takes me to his 10 ppm oven, I can get his meter to read 200, or 0, without 'adjusting' the oven.
Comment: I was standing there with him. The oven was set to 350 and he was reading it right at the vent under the control panel. His meter read 100 ppm initially and then after 10 minutes it stabilized to about 80 ppm.
Comment: I agree, this procedure for testing sounds very non-specific. Another possible variant: the size of the vent on different ovens may allow more or less ambient air to mix with the exhaust, which would change the PPM reading.
Answer: There is no air mixture adjustment. If it's making CO then the airflow is simply blocked.
Check all the vents, perhaps insulation moved, or there is something there. Also possible for rodents to live in an oven, and they'll move insulation to make a nest.
There are vents on the bottom, and one on top behind the burners in the back (under the control panel).
What color is the fire in the oven? It should be blue. Too much red/orange is not good.
Answer: I work for a Natural gas co. for 20 years we suggest you have a hood vent and run it when ever you are cooking with your oven this will take care of the problem, The oven can be adjusted to help most of the time but, it's going to put out CO that's why we suggest hood vents we will red tag oven unsafe if levels get around 70 ppm please invest in a hood vent that vents to outside
Comment: And make sure your hood actually uses the outside vent.  We had one once that leaked most of the air back into the kitchen because the installer didn't bother to seal the joints.
Answer: Yes you can adjust the air mixture. It's called an air shutter. Gas furnaces, gas ovens, oil furnaces have air shutters you can adjust the amount of air to the burning process. Most manufacturers find anything under 100 PPM acceptable. I shoot for under 50. If you add too much air, the efficiency of the appliance drops. Always use your hood vent and if you can open a window as well even better. Especially on Thanksgiving or when your oven is on for a long period of time. Like he said a hood that vents to the outside is what you want. I think you can call your local gas company and they will come out and inspect your appliance for FREE.


Required XML attribute "adSize" was missing when i have xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" set

Question: I am trying to include ads in my test app, when I run the app in an emulator or a device I get a banner add saying Required XML attribute "adSize" was missing .
I have set xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" in com.google.android.gms.ads.AdView tag.
Not sure how to resolve this issue.
More details :  Android Studio AI-141.1989493
Code snippet :
AdView mAdView = (AdView) findViewById(R.id.adView);
mAdView.setAdSize(AdSize.BANNER);
mAdView.setAdUnitId("ca-app-pub-xxxxx/xxxxxx");
AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .addTestDevice("E58D5904AA50D88E2FD63A1D1EF97B34")
            .build();
mAdView.loadAd(adRequest);

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<activity android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@android:style/Theme.Translucent" />

Activity_main.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/LinearLayout01">
<TableRow android:id="@+id/LinearLayout0">

<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-xxxxx/xxxxxx"
    ads:loadAdOnCreate="true"
    ads:testDevices="TEST_EMULATOR, E58D5904AA50D88E2FD63A1D1EF97B34">
</com.google.android.gms.ads.AdView>

Answer: Change:
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
To:
xmlns:ads="http://schemas.android.com/apk/res-auto"
Answer:

<TableRow
    android:id="@+id/LinearLayout0"
    xmlns:ads="http://schemas.android.com/apk/res-auto">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-xxxxx/xxxxxx"
        ads:loadAdOnCreate="true"
        ads:testDevices="TEST_EMULATOR, E58D5904AA50D88E2FD63A1D1EF97B34">
    </com.google.android.gms.ads.AdView>

</TableRow>

try this include a property on your root as done here.
Answer: The code below worked for me, and I think it will be all round :
<com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            ads:adSize="BANNER"
            ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>

Required XML attribute “adSize” was missing when i have xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads" set


Laravel 5 how to set hosted website on development mode

Question: How do I set my hosted Laravel site such that an attempt to visit any page of the website should display a message like: "Sorry, Website is under development, Will be available soon". it may be a dumb question but am new to this.
thanks for any help.
Answer: you need to modify

yourLaravelDirectory/public/.htaccess

and add this rule to it
<code>RewriteEngine on

RewriteRule ^(.*)$ http://www.newdomain.com [R=permanent,L]
</code>
so now onwords all your traffic will redirect to this new domain..
make sure you have one html page that says "Sorry, Website is under development, Will be available soon" hosted at www.newdomain.com


SQL How can I optimize splitting a string and inserting the words into a new table?

Question: Is there anyway to do this in less time? I am taking the summary column from my case table and splitting the data word by word into my words table using the following loop:
Example case table
CaseID | CaseNumber | Summary
1        111111       This is a summary
2        111112       This is Summary 2

DECLARE
@n int = 1
;
WHILE @n <= 1000
BEGIN
INSERT INTO words (caseID, caseNumber, pn, word)
SELECT caseID, caseNumber, pn, word FROM dbo.Split6(' ', (select summary
from
cases where caseID = @n)) where caseID = @n group by caseID,caseNumber, pn,
word
option (maxrecursion 0)
SET @n = @n+1;
END
GO

It works, but it is slow. Took 3 hours to break down 1000 cases. I have 100,000 cases. Is there a way I can do this more efficiently? Here is the split function I'm using:
Split6 function:
CREATE FUNCTION [dbo].[Split6] (
@sep CHAR(1)
,@s nVARCHAR(4000)
)
RETURNS TABLE
AS
RETURN (
WITH Pieces(caseID,caseNumber, pn, start, stop) AS (
            SELECT cs.caseID
            ,cs.caseNumber
                ,1
                ,1
                ,CHARINDEX(@sep, @s)
            FROM cases cs

            UNION ALL

            SELECT caseID
                ,caseNumber
                ,pn + 1
                ,stop + 1
                ,CHARINDEX(@sep, @s, stop + 1)
            FROM Pieces
            WHERE stop > 0
            )
    SELECT caseID
        ,caseNumber
        ,pn
        ,SUBSTRING(@s, start, CASE
                WHEN stop > 0
                    THEN stop - start
                ELSE 512
                END) AS word
    FROM Pieces
    )  GO

Comment: you'd do better with a programming language rather than sql for this..or if your version of sql server supports [`STRING_SPLIT`](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql), use it.
Answer: You should avoid loops whenever possible.
The following uses a Parse/Split function in concert with a Cross Apply (use Outer Apply to show null values).
As far as performance goes... useing a test sample of 100,000 records with a average of 5 words each, the execution time is 2.2 seconds.
Example
Declare @YourTable Table ([CaseID] varchar(50),[CaseNumber] varchar(50),[Summary] varchar(50))
Insert Into @YourTable Values
 (1,111111,'This is a summary')
,(2,111112,'This is Summary 2')

Select A.CaseID
      ,A.CaseNumber
      ,B.*
 From @YourTable A
 Cross Apply [dbo].[udf-Str-Parse](A.Summary,' ') B

Returns
CaseID  CaseNumber  RetSeq  RetVal
1       111111      1       This
1       111111      2       is
1       111111      3       a
1       111111      4       summary
2       111112      1       This
2       111112      2       is
2       111112      3       Summary
2       111112      4       2

The UDF if Interested
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
    Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')

EDIT - Another Parse/Split Function

The following TVF is slightly faster then the XML version, but limited to 8K.  For example, on 5,000 sample records, with an average of 36 "words", it was 20ms faster than the XML version.
CREATE FUNCTION [dbo].[udf-Str-Parse-8K] (@String varchar(max),@Delimiter varchar(25))
Returns Table
As
Return (
    with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
           cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 a,cte1 b,cte1 c,cte1 d) A ),
           cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter)) = @Delimiter),
           cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter,@String,s.N),0)-S.N,8000) From cte3 S)

    Select RetSeq = Row_Number() over (Order By A.N)
          ,RetVal = LTrim(RTrim(Substring(@String, A.N, A.L)))
    From   cte4 A
);
--Orginal Source http://www.sqlservercentral.com/articles/Tally+Table/72993/
--Select * from [dbo].[udf-Str-Parse-8K]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-8K]('John||Cappelletti||was||here','||')

Comment: @Bendgame Happy it helped


What is the process of building/installing a service?

Question: I am creating a simple service in VS2008 C#
How do I install it on my computer so that it runs when I start my machine?
Answer: Visual Studio supports Windows Services as a type of application. I believe the template for this only exists in the Professional Edition. However, you can build a service by creating a ServiceProcess Installer and using InstallUtil.
You can find more information here.
When you create a New Project, select the type of project Windows Service. Depending on the version of Visual Studio, you may have to browse to the Windows templates section to find it.
Comment: i know that. how do i install it?
Answer: You can use the Visual Studio Command prompt.

Open the visual studio command prompt (where this is depends on a number of things, see this page for info. When you find it, it's useful to add it as an external tool in your tools menu in visual studio).
Navigate to the folder containing the exe for your service
Run installutil <yourexe> where  is the name of the executable file.
If you specified the service to run as a specific user, it will now prompt you to enter that user's credentials.

Depending on settings, you may need to go into services (start > run> services.msc) and set it to start automatically on boot.
You can then uninstall using installutil /u <yourexe> if you ever need to, using pretty much the same process.
Comment: why would i have a DLL? i dont have DLL
Comment: @JOE SKEET sorry, that was meant to say exe. My bad, will fix it.
Comment: from which dir should i run installutil?
Comment: Well, if you build your service in release mode, it'll be the bin/release dir inside your project directory. Otherwise bin/debug. Basically it's the directory that contains your service's exe.


How is the pythagorean scale using fifths constructed?

Question: I was trying to construct the pythagorean scale using fifths. You know by multiplying the tonic with 3:2 ratios and then that with 4:3 ratios and so on. Now in this way the ratios keep on getting bigger. But isn't the pythagorean scale all about simple rational numbers? At least for the fourths and fifths. Well if I proceed this way the fourth isn't turning out to be 4:3 as it should be. But rather something quite unfathomably huge and obnoxious. What's happening here. Can somebody please help me out with a step by step construction of the scale?
Edit: alright so basically suppose I start from a C and I go up a fifth to a G. So the G is in a 3:2 ratio from the C. Now if I go up another fifth from the G I'll go upto a D. Now the ratio of this D to G is 3/2 * 3/2 = 9/4. Since this 9:4 > 2:1, the D exceeds the higher C and is beyond the current octave at hand. So if we step it down an octave by multiplying it by 1/2, it comes to a 9/8 which is our major second. Now multiplying this 9/8 with 3/2 gives me 27/16 which is the major sixth. Likewise if I continue by the time I reach a fourth it's quite a big ratio. But pythagoras also said, a perfect fourth is supposed to be a 4:3 with the tonic. So what's going wrong here?
Comment: You should ask this type of question on https://music.stackexchange.com/ . The pythagorean scales is not constructed by moving up a fifth twelve times, but only six times, and the other notes are produced by moving a down a fifth from the starting note multiple times. If you move down a fifth, you get a perfect fourth (modulo the octave). See https://en.wikipedia.org/wiki/Pythagorean_tuning, in the table, starting from D, you find the G by going down a fifth, and this gives a perfect fourth.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: It could be an issue with octaves. Can you be more specific about how you're getting the "huge and obnoxious" ratios?
Answer: If you go up twelve Pythagorean fifths, starting from C, and down seven octaves, you don't end up at the C from which you started, but at a $\text{B}^\sharp$ higher than that C by a Pythagorean comma. If instead, you go up eleven Pythagorean fifths and down five octaves, you don't end up at the F a fourth above the C, but at the $\text{E}^\sharp$ an augmented third above it.  Unlike in the scales based on equal temperament, in those based on Pythagorean tuning, $\text{B}^\sharp$ does not have the same pitch as C, $\text{E}^\sharp$ does not have the same pitch as F, and an augmented third is a strictly larger interval than a perfect fourth.  The notes of the Pythagorean scale that you get by travelling eleven steps upward and nine steps downward from C around the spiral of fifths are given in the following table, along with the ratio of their frequencies to that of the C from which you started.
\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|}
\text{C}&\text{B}^\sharp&\text{D}^\flat&\text{C}^\sharp&\text{D}&\text{E}^\flat&\text{D}^\sharp &\text{F}^\flat&\text{E}&\text{F}&\text{E}^\sharp\\
\hline
1&\frac{3^{12}}{2^{19}}&\frac{2^8}{3^5}&\frac{3^7}{2^{11}}&\frac{3^2}{2^3}&\frac{2^5}{3^3}&\frac{3^9}{2^{14}}&\frac{2^{13}}{3^8}&\frac{3^4}{2^6}&\frac{2^2}{3}&\frac{3^{11}}{2^{17}}
\end{array}
\begin{array}{c|c|c|c|c|c|c|c|c|c|c|c|}
&\text{G}^\flat&\text{F}^\sharp&\text{G}&\text{A}^\flat&\text{G}^\sharp&\text{A}&\text{B}^\flat&\text{A}^\sharp&\text{C}^\flat&\text{B}\\
\hline
&\frac{2^{10}}{3^6}&\frac{3^6}{2^9}&\frac{3}{2}&\frac{2^7}{3^4}&\frac{3^8}{2^{12}}&\frac{3^3}{2^4}&\frac{2^4}{3^2}&\frac{3^{10}}{2^{15}}&\frac{2^{12}}{3^7}&\frac{3^5}{2^7}
\end{array}
Note that the pairs $\  \text{E}/\text{F}^\flat$, $\  \text{B}/\text{C}^\flat$, $\  \text{F}^\sharp/\text{G}^\flat$, $\  \text{C}^\sharp/\text{D}^\flat$,$\  \text{G}^\sharp/\text{A}^\flat$, $\text{D}^\sharp/\text{A}^\flat$,$\  \text{A}^\sharp/\text{B}^\flat$,$\  \text{E}^\sharp/\text{F}$,$\  \text{B}^\sharp/\text{C}$ do not have the same pitch like they do in equal temperament scales.  In practice, a twelve note Pythagorean scale would typically comprise either the notes A, B, C, D, E, F, G, $\text{C}^\sharp$, $\text{F}^\sharp$, $\text{G}^\sharp$, $\text{B}^\flat$ and $\text{E}^\flat$, or A, B, C, D, E, F, G, $\text{C}^\sharp$, $\text{F}^\sharp$, $\text{A}^\flat$, $\text{B}^\flat$ and $\text{E}^\flat$.


Show that $3\int_{[0,1)} |f|d\lambda+4\int_{[1,2]} |f|d\lambda\leq 5\bigg( \int_{[0,2]} |f|^2d\lambda \bigg)^{1/2}$

Question: In some homework I have to show that for $f \in \mathcal{L}^2([0,2],\lambda)$ then:
$$3\int_{[0,1)} |f|d\lambda+4\int_{[1,2]} |f|d\lambda\leq 5\bigg( \int_{[0,2]} |f|^2d\lambda \bigg)^{1/2}$$
But I have run out of good ideas. I tried applying Pythagoras and Minkowski but with no luck
Any hint would be appreciated
Comment: the numbers $(3,4,5)$ are a [Pythagorean triplet](https://en.wikipedia.org/wiki/Pythagorean_triple), so we have a "hint" now
Comment: Why did you delete the other question ?
Comment: @GabrielRomon Because the question was not correctly formulated
Answer: First, by Hoelder inequality
$$
3 \int_{[0,1)} |f| + 4 \int_1^2 |f| \le 3 (\int_{[0,1)} |f|^2 ) ^{1/2} + 4 (\int_{[1,2]} |f| ^2)^{1/2}.
$$
Then by Cauchy-Schwarz on $\mathbb R^2$
$$
3 (\int_{[0,1)} |f|^2 ) ^{1/2} + 4 (\int_{[1,2]} |f| ^2)^{1/2}
= \pmatrix{3 \\ 4}^T\cdot \pmatrix{ ( \int \dots)^{1/2} \\ (\int \dots)^{1/2}}\\
\le \sqrt{3^2 + 4^2} \sqrt{ \int_{[0,1)} |f|^2  + \int_{[1,2]} |f| ^2}
= 5 \sqrt{\int_{[0,2)} |f|^2}
$$
Comment: I am not sure how you use Hölder. Is this because you are extending like this? $ \int_{[0,1)} 3\cdot |f| +  \int_{[1,2]} 4\cdot |f| \le (\int_{[0,1)} 3^2 ) ^{1/2} \cdot (\int_{[0,1)} |f|^2 ) ^{1/2} + (\int_{[1,2]} 4^2)^{1/2}\cdot (\int_{[1,2]} |f| ^2)^{1/2}=3 (\int_{[0,1)} |f|^2 ) ^{1/2} + 4 (\int_{[1,2]} |f| ^2)^{1/2}$
Comment: exactly, $\int |f| \le (\int 1^2)^{1/2} (\int |f|^2)^{1/2}$.


What is the most concise way to present a particular subgroup of $F_2$?

Question: Let $A\leq F_2$ where $F_2$ is the free group on $\{a,b\}$.
Assume $A$ is generated by words on $a,b$ such that the total powers of $a$ are $3x$ for some $x\in \mathbb{Z}$ and the total powers of $b$ are $-2x$ for the same $x$.
Explicitly, for instance, a generator of $A$ would be $a^3b^{-2}$ or $a^2b^{-1}ab^{-1}$.
Besides writing them all out, is there a way to concisely provide a presentation for $A$ using generator notation? Of course being able to write $A=\langle a^{3x}b^{-2x} \rangle$ would be nice, but $F_2$ is non-abelian.
It seems like it should be close to something like, $A = \langle a^{3x} b^{-2x} : x\in\mathbb{Z}, ab=ba \rangle$, but I'm not convinced throwing in the commutivity relation makes too much sense.
Maybe utilizing $\prod$?
Comment: You could define $\varphi\colon F_2\to\mathbb Z^2$ as the abelianization. Then $A$ is generated by $u\in F_2$ such that $\varphi(u)=(3x,-2x)$ for some $x$.
Answer: Define a group morphism $\pi:F_2 \to \Bbb Z$ by setting $\pi(a) = 2$ and $\pi(b) = 3$. Thus for instance $\pi(a^3b^{-2}) = 0$ and $\pi(a^2b^{-1}ab^{-1}) = 0$, etc.
Consequently, your group is generated by
$\ker \pi$, and since $\ker \pi$ is a group, it is actually equal to $\ker \pi$.
I claim that $\ker \pi$ is a free group generated by $a^3b^{-2}$ and by the commutator subgroup $[F_2, F_2]$ of $F_2$. Let $u \to |u|_a$ be the group morphism from $F_2$ onto $\Bbb Z$ which maps $a$ to $1$ and $b$ to zero. Intuitively, $|u|_a$ counts the number of occurrences of $a$ in $u$, with $a^{-1}$ counting as $-1$. The map $u \to |u|_b$ is defined in a similar way. Note that $$[F_2, F_2] = \{u \in F_2 \mid |u|_a = |u|_b = 0\}.$$
Let now $u \in \ker \pi$. Since $\pi(u) = 2 |u|_a + 3|u|_b$, one has $2|u|_a + 3 |u|_b = 0$ and thus $|u|_b$ is even. Now $(a^3b^{-2})^{|u|_b/2}u \in [F_2, F_2]$ since
$$
\bigl(|(a^3b^{-2})^{|u|_b/2}u|_a, |(a^3b^{-2})^{|u|_b/2}u|_b\bigr) = \bigl(3|u|_b/2 + |u|_a, -|u|_b + |u|_b\bigr) = (0, 0)
$$
which proves the claim. Finally, according to this question, $[F_2, F_2]$ is generated by the commutators $[a^n, b^n]$, for $n \in \Bbb Z \setminus \{0\}$. This gives you the following set of generators for your group:
$$
\{a^3b^{-2}\} \cup \{[a^n, b^n]  \mid n \in \Bbb Z \setminus \{0\}\}
$$
Comment: @pyridoxal_trigeminus Unfortunately, the commutator subgroup of $F_2$ is free of infinite rank, so it would be difficult to describe via a presentation. The best you can do is almost certainly what Pin does: say it is generated by $[F_2,F_2]$ and $a^3b^{-2}$.
Comment: Indeed, but is there any explicit, concise way to present $\ker \pi$?


Getting permission denied when I attempt cp ExampleTxt /home

Question: I am a student in college for CS and a new user of linux.
Regarding the question I am simply trying to copy ExampleTxt from from my directory Test_Directory to home. The exact command I am using is "cp ExampleTxt /home" and my CWD is /home/cslinux/Test_Directory. The error line I am getting reads "cp: cannot create regular file '/cslinux': Permission Denied"
Comment: `Permission Denied` this means you don't have sufficient permissions.  `/home/youruser` is your home folder not `/home` which is the directory under which all user's home folders are located.
Answer: "/home" is a directory which contains all users' home directories (much like Users folder in Windows). As mentioned by Nmath in the comments, normally only the admin has permission to alter any files in there. Your "home directory" is actually /home/cslinux, assuming your username is cslinux.
The closest, most easily doable thing to what you are attempting is achieved by:
cp /home/cslinux/Test_Directory/ExampleTxt /home/cslinux/

This copies ExampleTxt to the /home/cslinux directory instead. Notice I used an absolute path for ExampleTxt so that the command works independently of the directory you are in.
Also, an alternative way to write /home/cslinux would be "~". Using that, the above command can be shortened to this one:
cp ~/Test_Directory/ExampleTxt ~/


DNN Page disappears

Question: I have DNN 4.8 on a shared hosting server. I am facing a quite confusing situation. Whenever I add pages, after few minutes pages disappeared from menu and other page drop-down list (for example Parent Page Combo). Even this behavior repeated on DNN 5.1 as well. I am not sure whether this is issue with hosting company or DNN bug? any clue?
Answer: It's definitely not a standard DNN issue. My guess is it has something to do with the server caching and I would work with the hosting company to resolve it.
Does the page still exist? Is it just hidden in the menu? Does your login affect it?
Comment: Yup, it wasn't DNN issue. The system administrator allocated dedicate pool for my app in order to resolve this issue.

DNN Page disappears


VB.NET WinForms ListView doesn't display column headers

Question: I have below code in my Form Load event handler but the ListView doesn't show any column headers.
I want the column headers to be displayed. Any ideas?
<code>    lstBatch.Columns.Add("C1", 100, HorizontalAlignment.Center)
    lstBatch.Columns.Add("C2", 100, HorizontalAlignment.Center)
    lstBatch.Columns.Add("C3", 100, HorizontalAlignment.Center)
    lstBatch.Columns.Add("C4", 100, HorizontalAlignment.Center)
    lstBatch.Columns.Add("C5", 100, HorizontalAlignment.Center)
    lstBatch.Columns.Add("C6", 100, HorizontalAlignment.Center)
    lstBatch.Columns.Add("C7", 100, HorizontalAlignment.Center)
    lstBatch.Columns.Add("C8", 100, HorizontalAlignment.Center)
    lstBatch.Columns.Add("C9", 100, HorizontalAlignment.Center)
    lstBatch.Columns.Add("C10", 100, HorizontalAlignment.Center)
</code>
Answer: You should add
<code>lstBatch.View = System.Windows.Forms.View.Details
</code>


Why does the litteral loop outputs extra commas?

Question: I'm trying to figure out template litterals in js but don't really get the syntax. This loop outputs extra commas between every itteration:
character = () => {
    const traits = ["Kunskap", "Rörlighet","Styrka", "Utstrålning", "Uppfattningsförmåga", "Magisk kraft"];
    return `${traits.map(() => '')}`
};

Full code:
            character = () => {
                const dice = rndAssign(6, 16),
                traits = ["Kunskap", "Rörlighet","Styrka", "Utstrålning", "Uppfattningsförmåga", "Magisk kraft"];
            return `

                             	D6	Mod

                        ${traits.map(elm => trait(elm))}

`
            };

Comment: This doesn't really have anything to do with loops or template literals, you are just stringifying the array that `map` returns
Comment: How many commas do you expect and how many do you get?
Comment: What are you trying to achieve? Your map replaces every element with an empty string. Is that intentional?
Answer: Because that is default toString behaviour on arrays. You could use join on the array to create a string without commas.

const table = () => {
  const traits = ["Kunskap", "Rörlighet", "Styrka", "Utstrålning", "Uppfattningsförmåga", "Magisk kraft"];
  return `

Foo

${traits.map((e) => `<tr><td>${e}</td></tr>`).join(' ')}

    `
};

document.body.innerHTML = table()
table,
th,
td {
  padding: 5px;
  border: 1px solid black;
}
Comment: Check my answer please, a `map` is not necessary.
Comment: @marekful Maybe op wants do to something for each element of the array.
Answer: I dont really know what are you trying to do exactly. Why loops and why do you use literals if you can stringify the array using join and get a string.

character = () => {
    const traits = ["Kunskap", "Rörlighet","Styrka", "Utstrålning", "Uppfattningsförmåga", "Magisk kraft"];
    console.log(traits.join(' '))
};

character();
Answer: in map function just returning the empty string, so that empty array printing commas. if you return there value then it will print values.
character = () => {
        const traits = ["Kunskap", "Rörlighet","Styrka", "Utstrålning", "Uppfattningsförmåga", "Magisk kraft"];
        return ${traits.map(() => '')}
    };
() => {
    const traits = ["Kunskap", "Rörlighet","Styrka", "Utstrålning", "Uppfattningsförmåga", "Magisk kraft"];
    return `${traits.map(() => '')}`
}

character()
",,,,,"

character = () => {
    const traits = ["Kunskap", "Rörlighet","Styrka", "Utstrålning", "Uppfattningsförmåga", "Magisk kraft"];
    return `${traits.map((v) => v)}`
};

() => {
    const traits = ["Kunskap", "Rörlighet","Styrka", "Utstrålning", "Uppfattningsförmåga", "Magisk kraft"];
    return `${traits.map((v) => v)}`
}

character()

"Kunskap,Rörlighet,Styrka,Utstrålning,Uppfattningsförmåga,Magisk kraft"


iOS Objective C Webservice

Question: Is there any way to keep our web service delegate methods in one class and use them whenever required? Normally I used to keep writing the delegates in all classes such as didReceiveResponse and didReceiveData etc..;
Answer: There is a way to do what you want to achieve, but make sure to not overdo it. Too many use of singletons is generally recognized as bad practice.
Make a Singleton that you could use throughout your app.
https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/Singleton.html
In your Singleton: APISingleton
-(void)APIRequestWithParams:(NSMutableDictionary*)params
         onCompletion:(JSONResponseBlock)completionBlock
            onFailure:(OperationFailureBlock)failureBlock{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[manager GET:kGymEverAPIfullUrl
  parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
         completionBlock(responseObject);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         failureBlock(operation);
     }];}

How to use:
-(void)getImages{

NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",1],@"page",@"5",@"count", nil];

[[APISingleton sharedInstance] APIRequestWithParams:params onCompletion:^(id json) {
    postsArray = [json objectForKey:@"posts"];
    [self downloadImages];
} onFailure:^(AFHTTPRequestOperation *operation) {
    //Do whatever you want if it does not work.
}];}

Using : https://github.com/AFNetworking/AFNetworking

iOS Objective C Webservice


Jquery DatePicker $.get request not working

Question: I want to send some data to a script onSelect with DatePicker. Here is my code:
$( "#customdate" ).datepicker({
  nextText: "→",
  prevText: "←",
  dateFormat: "mm/dd/yy",
  maxDate: '-1d',
  onSelect: function(dateText, inst) {
    var calendiv = $(this);
    var url = calendiv.data('href');
    var deets = calendiv.data();
    delete deets.href;
    deets.fromdate = dateText;
    $.get(url, deets, function(data) {
      alert("oh");
      if (data.success == 1) {
        var dataHTML = $.parseHTML(data.contents);
        $("#ideal tbody").html(dataHTML);
        $("#ideal").trigger('footable_initialize');
      }
    });
  }
});

However, when I click a date,I get the error below. Everything outside of the $.get works as expected, but nothing inside happens.
When I click it, I get the error:

TypeError: 'click' called on an object that does not implement
  interface HTMLElement.
Answer: The first line after onSelect: function(dateText, inst) { should be event.preventDefault. Read more about it on MDN.
If you but a console.log($) above $.get(url, deets, function(data) { you will see that it will be undefined. Read more about Javascript contexts.
A working code should look like:
$( "#customdate" ).datepicker({
  nextText: "→",
  prevText: "←",
  dateFormat: "mm/dd/yy",
  maxDate: '-1d',
  onSelect: function(dateText, inst) {
    event.preventDefault();
    var calendiv = $(this);
    var url = calendiv.data('href');
    var deets = calendiv.data();
    delete deets.href;
    deets.fromdate = dateText;
    $.get(url, deets, function(data) {
      alert("oh");
      if (data.success == 1) {
        var dataHTML = $.parseHTML(data.contents);
        $("#ideal tbody").html(dataHTML);
        $("#ideal").trigger('footable_initialize');
      }
    });
  }.bind(this)
});

Comment: Thanks for the prompt reply! I tried your solution but I'm getting "ReferenceError: event is not defined"


$A$ be a nonzero finite abelian group then $A$ is not a projective or injective $\Bbb Z$ module.

Question: To prove that if $A$ be a nonzero finite abelian group then $A$ is not a projective or injective $\Bbb Z$ module.
Ref: Dummit Foote Sec 10.5 Q7.
Answer: Hints:
A finitely generated projective module over a P.I.D. is free.
An injective module over an integral domain is divisible.
A non-zero finite abelian group is neither free (it has torsion) nor divisible (it has an annihilator) over  $\mathbf Z$.
Answer: A nonzero finite abelian group is a direct sum of prime power order cyclic groups. If $p$ is prime and $n>0$, then the (canonical) short exact sequence
$$
0\to p^n\mathbb{Z}/p^{2n}\mathbb{Z}\to\mathbb{Z}/p^{2n}\mathbb{Z}\to\mathbb{Z}/p^n\mathbb{Z}\to0
$$
is not split. Note that the first and last term are isomorphic. This proves that $\mathbb{Z}/p^n\mathbb{Z}$ is neither projective nor injective. A direct summand of a projective (resp. injective) module is projective (resp. injective).
Comment: Refer to Dummit and Foote (3rd edition) 10.5.3 and 10.5.4 respectively for the last statement and see 5.2 of Dummit and Foote page 161 theorem 5 for the used theorem. very elegant argument.