Why does this javascript code that is supposed to only show results that match typed input filter only the first 10 options?

Question: I have a piece of code (only a snippet, everything else is css) that as I type shows only the options that match my typed input. But for some reason, it only filters the first 10 options. The rest of the options just show no matter what. Any ideas why?

function myFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("mySearch");
  filter = input.value.toUpperCase();
  ul = document.getElementById("myMenu");
  li = ul.getElementsByTagName("li");
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}
a { color: white }

***PAVADINIMAS***

    <input type="text" id="mySearch" onkeyup="myFunction()" placeholder="Paieška" title="Type in a category">

Option1

Test

Lorem ipsum

abcde

monday

tuesday

wednesday

thrusday

friday

saturday

sunday

test2

iii

12345

qwerty

I searched the web but haven't found anything similar to this.
Comment: In the console: `Uncaught TypeError: Cannot read properties of undefined (reading 'innerHTML')",` because your li has an error, you did not close the one
Comment: I edited your question to make it runnable and I formatted it so the error stands out. Get a linter/ beautifier on your IDE so these typos stand out. Look at your developer console since you clearly did not see the error message.
Comment: Thank you both so much, didn't see that, I am so sorry. Thank you for pointing it out.
Answer: Your extra
 tag is rendered by the browser as an empty
 element (i.e.

). Thus, when it is looped over by your for loop, the following lines fail:
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {

because the empty li element doesn't contain an a element, and thus the a variable is undefined, causing a.innerHTML to throw an error (since you can't access a property on an undefined value).
Comment: Thank you so much, didn't see that, I am so sorry. Thank you for pointing it out.
Answer: While it is valid to not have closing tags on
 sometimes that can challenge code - one reason to never omit on things like
,
 etc. that allow this
Here I updated to use a closing tab on both those that did not have it.
Out of scope but I also updated the script to account for missing elements that returned undefined (missing the  for example

function myFunction() {
  let input, filter, ul, li, a, i;
  input = document.getElementById("mySearch");
  filter = input.value.toUpperCase();
  ul = document.getElementById("myMenu");
  li = ul.getElementsByTagName("li");
  for (i = 0; i
 -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}
a { color: white }

***PAVADINIMAS***

    <input type="text" id="mySearch" onkeyup="myFunction()" placeholder="Paieška" title="Type in a category">

Option1

Test

Lorem ipsum

abcde

monday

tuesday

wednesday

thrusday

friday

saturday

sunday

test2

iii

12345

qwerty


How do you do a takedown after a smoke pellet?

Question: One of the challenges in Batman: Arkham City is

Use the Smoke Pellet to disorientate an armed enemy and follow up with a Takedown

But how exactly do you do this? Every guide I've found just says something along the lines of find an armed enemy, throw a smoke pellet at them, then do a takedown. But there is never any takedown option. I've tried just punching them, standing in front of them, standing behind them, crouching, and there's never a takedown prompt. They just stand there flailing about a little until the smoke clears.
So what exactly are the inputs required to complete this challenge?
Answer: Probably the easiest method is the Line Launcher Takedown.
After disorienting an unaware enemy from a distance (6, right-hold, left-click), fire the line launcher (8, right-hold, left-click) at them, then right-click on approach.
A Special Combo Instant Takedown (E) may also be possible, but you need a group large enough to build combo but with few enough guns that you don't just get shot. There will be a small window to drop the pellet and target the correct enemy in-between combo moves.


Set primary monitor on 16.04

Question: All windows opens on left monitor and all new files gets saved there, I want my right monitor as my primary monitor so all this happens there.
As the picture below shows I have set the launcher on my right monitor but that doesn't help with my problem.
Comment: Check solutions on https://askubuntu.com/questions/300670/is-there-any-ability-to-set-primary-monitor
Comment: "All new files get save there"?! Do you have an SD card or USB drive in your monitor to the left  or what?
Answer: I had this same problem, as well as several other problems related to having multiple monitors.
It turns out this is an open unsolved bug for Ubuntu; meaning the solution link posted in the above comment does not actually contain a solution that fully works.  See open bug report here:
https://bugs.launchpad.net/ubuntu/+source/xorg-server/+bug/1425000
Fortunately I spent a bunch of time figuring out how to configure this as well as the orientation of the login screens but that's explained in a different thread (I have four monitors and login orientation was wrong but it's all sorted now, if you also have this issue see solution here: Where does Unity/Unity-Greeter Load X Configuration From?)
The quick simple solution to the problem of not being able to set your default display, and/or the default display getting reset after reboot is to put a short shell command that changes the primary monitor as one of your "Startup Applications" which will automatically run every time you log in (this should work for any recent Ubuntu running the Unity display manager which is the default display manager and probably other DMs but I didn't test that):
1) First, you will want to install arandr to easily find your monitor display names, run this in a shell:
sudo apt-get install arandr --upgrade

2) Next, run the arandr command and look at it's user interface that loads (it will probably load on the wrong screen since you haven't configured anything yet).
3) Now, take note of which display (the names should be something like HDMI-# for hdmi or DP-# for display port, DVI-I-# for digital video, etc).  The label should be big and obvious once you run arandr. You can either write down the display name, or just keep arnadr window open, so you can see it, and launch a new shell if you need to for the next part.  My default display is called DP-4 used in the next example, but undoubtedly yours will be different so take note for the next step.
4) Next, load up the "Startup Applications" tool.  You can find it by going to the dash and typing "Startup Applications" and Ubuntu will find it for you, or you can run this command in a shell:
gnome-session-properties

5) Now, from within the Startup Applications tool, click the "Add" button and add a new program to run upon logging in.  A window will pop up asking you what to run, here is what to type:

Name: Set Default Monitor
(Note: put any name you want)
Command: xrandr --output DP-4 --primary
(Note: change DP-4 *to whatever monitor code you found you want to be the default display when you ran *arandr)
Comment: Leave blank or put a reminder for yourself later what this does.

Reboot to fully test it worked and that should do the trick.  If you aren't sure if the command will work and want to test it first, you can run xrandr --output DP-4 --primary (again, replace DP-4 with your default monitor) from a shell then launch a window and see if it shows up on the correct default monitor.  But in order to have this save and work each time, to work around the bug, you need to add that command to Startup Applications.
UPDATE:  It seems here is a second step / part 2 to this solution in order for it to fully work.  After several days of testing on Ubuntu 16.04, I discovered it was also necessary to modify ~/.config/monitors.xml to specify the primary monitor.  If you don't set the primary monitor in ~/.config/monitors.xml then it appears some windows and/or programs obey the xrandr command and some do not.   All you need to do in order to perform this step is open up  ~/.config/monitors.xml in a text editor like gedit and set the <primary> tag to yes for the display monitor you want as primary and no for all other displays.
Here are the steps:
1) In a shell, first backup your existing monitors.xml file so you can restore it if something unexpected goes wrong during the editing process:
cp ~/.config/monitors.xml ~/.config/monitors_OLD.xml

2) Open monitors.xml in gedit to change the config settings tags:
gedit ~/.config/monitors.xml

3) Now, inside of the gedit editor window, find the output tag labeled for the monitor you want to be primary, then under that <output> block, change the <primary> tag to yes.  Be sure to look at all other monitors and change the primary tag for all the other monitors to no.
For me, doing these two things has solved the problem in all cases I've encountered so far.
Comment: I've been fighting this forever I love you.
Comment: What happens if your primary monitor changes? My situation is that at home I have my laptop to the left + monitor, and at work I have another monitor + my laptop to the right.
Answer: OS: Ubuntu Studio 16.04 LTS
The issue was that my config was saving my display settings through the default display program, though not applying the "Primary" setting correctly on bootup.
I have my Laptop on the right and main screen on the left, I have the left monitor configured as primary.
On bootup, it was displaying the top tool bar on the right, whilst the os (mouse) thought it was on the left, hence to use the top tool bar, I had to blindly navigate (estimate) to where the menuitems were by looking on the right screen and using my mouse on the left. I could overcome this by changing the rotation on atleast one screen, applying the settings, then putting them back again. The top tool bar would then correctly be set to my primary (Left) screen.
The process below now does this for me automatically (many thanks to etron's post) :

Install arandr to easily find and configure your display names.
sudo apt-get install arandr --upgrade

Run the arandr command from a shell to configure and identify your displays.
-- For Layout you can drag the monitors around.
-- For Active, Primary, Resolution and Orientation settings goto menu option Outputs > %Display.
Once the above is set as you'd like, goto menu option Layout > Save as:
and enter ~/.screenlayout/ScreenLayout.sh in the name field.
Edit the ~/.screenlayout/ScreenLayout.sh file in a text editor and duplicate (copy & paste) the entire xrandr line.
Now modify a value in the first xrandr line.
I changed the --rotate normal option value to --rotate left. When this script runs it will briefly change the rotation left, then back to normal, re-activating the config. Same as what I had to do manually as described above.
My ScreenLaout.sh file now looks like this:
#!/bin/sh
xrandr --output LVDS-1 --mode 1680x1050 --pos 1680x0 --rotate left --output HDMI-1 --off --output VGA-1 --primary --mode 1680x1050 --pos 0x0 --rotate normal
xrandr --output LVDS-1 --mode 1680x1050 --pos 1680x0 --rotate normal --output HDMI-1 --off --output VGA-1 --primary --mode 1680x1050 --pos 0x0 --rotate normal

Next, load up the "Startup Applications" tool. You can find it by going to the dash and typing "Startup Applications" and Ubuntu will find it for you, or you can run this command in a shell:
gnome-session-properties

Now, from within the session and Startup tool, navigate to the "Applcation Autostart" tabe, click the "Add" button and add a new program to run upon logging in. A window will pop up asking you what to run, here is what to type:
Name: Set Default Monitor (Note: put any name you want)
Description: Leave blank or put a reminder for yourself later what this does.
Command: ~/.screenlayout/ScreenLayout.sh
Reboot to fully test it worked.

Note: If you aren't sure if the command will work and want to test it first, you can run the script manually i.e. in my case I would run this
~/.screenlayout/ScreenLayout.sh in a shell. Also, if you would prefer to use keybindings to set multiple configuration, I believe you can do this within arandr, though it requires Metacity, which I haven't investigated so you're on your own here.
Answer: In addition to etron's answer - that didn't work for me, my secondary screen (HDMI1) which is on the left, still would act as if it was to the right of the primary (HDMI2) after a reboot, even though it was all correct in my monitors.xml. What worked for me was as etron describes, but I put the following command in my startup applications instead:
xrandr --output HDMI2 --pos 1920x0 --output HDMI1 --pos 0x0

This forces my primary (HDMI2) on the right (horizontal offset x=1920) and the secondary (HDMI1) on the left (x=0)
Comment: This works. But the problem is that you have to move your mouse at the left side of the left screen, to appear on the right screen.
Answer: You can also try switching off and on the currently main monitor in the display configuration, as indicated here: Is there any ability to set my primary monitor?

Set primary monitor on 16.04


RegEx character limits

Question: I want to change the RegEx below too a-Z 0-9 and underscore only
var nameRegex = /^[a-zA-Z]+(([\'\,\.\-][a-zA-Z])?[a-zA-Z]*)*$/;

The 2,4 what does that mean? does that mean check the TLD is a min. of 2 to 4 char. max?
var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;

How would I add a required 250 char, would {250,250} at the end do it?
// original
      var messageRegex =
new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);

// would this work?
      var messageRegex =
new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim){250,250}$/;

Comment: Don't reinvent the dead horse. Email address valudation by regex is a bad idea.
Comment: Do you want exactly 250 characters?
Comment: @Josh 250 to 500 chr... should it be 250,500 ?
Comment: Posted a possible answer. Let me know if this is what you're asking :)
Comment: Retagged, I assume you're talking JS, but if you're not go ahead and slap me :)
Comment: @tripleee what are the other options?
Comment: Look for similar questions on StackOverflow.  If you need to be able to send mail to the guy, send a message with an activation link.  If you don't really need the email address, be very liberal in what you accept.
Answer: If I get your question correctly, then these should be what you're looking for:

Matching a set of characters within A-z, 0-9, and _.
// Would match any input with A-z 0-9 or _ in any position, given at least one char.
var nameRegex = /^[A-Za-z\d_]+$/;

You're right about the {2,4}. it specifies that [\w-] should
match two, three, or four characters.
Your message RegExp will force the input to be exactly 250 characters long to get a match. If you want more than 250 and less than 500, then append {251,500} instead.
Final note, RegExp literals look like /someRegex/ig. If you're using a literal then there's no reason to wrap in the constructor (i.e. new RegExp).
Last note, I, personally avoid * in my RegExp's, since this can lead to fun bug if the star runs into the the closing slash and someone attempts to comment out the expression.
/* Comment out some code
var myRe = /[a-z]*/i; // The comment stops before the i.
*/ // This line breaks your code.

Edit: Updated point three based on OP feedback.
Comment: Do not use `[A-z]` to match upper- and lowercase letters.  It works, but it also matches the characters `[`, `]`, `^`, `_`, backslash and backtick, whose code points happen to lie between `Z` and `a`.  Use `[A-Za-z]` or the `/i` modifier instead.

RegEx character limits


Static speaker noise when booting

Question: I just installed Ubuntu 15.10 on my HP ZBook Studio G3.
When booting, there is a loud static noise from my speakers somewhere where the bios logo shows, which then gets muted. A very brief noise is also played just before the login screen of Ubuntu.
After that, the usual drum sound plays and everything is fine. No noise, audio is perfect.
Answer: This happens for me as well with my HP ZBook Studio G3 and I am on Windows 10. Usually it is a static hiss, but today it was a loud beeping noise.
Guess it is something with the startup and not related to Ubuntu.
Answer: I was unable to do the BIOS update despite many attempts, but since I don't use the internal speakers for anything, I got rid of the hiss by disabling the internal speakers from BIOS.
Answer: I also used to have the same problem, first with Windows 7 then Windows 10. A BIOS upgrade took care of it.
You can download the BIOS update from here:
HP Drivers & Software
I am using version 01.14 Rev.A (12 Sep 2016)
The upgrade is a simple Windows application, it will do several reboots. It takes A WHILE (I don't remember exactly how long, but it was a lot more than I expected with no notification of any progress), so don't panic and let it do its thing for as long as it's needed.

Static speaker noise when booting


What is the sectional curvature of this explicitely given n-dimensional submanifold of R^(n+1)?

Question: Let $n>1$ be an integer. Consider $\mathbb{R}^{n+1}$ with the coordinates $x_1,\ldots,x_n,y$ and the closed submanifold
$$
M_n := \left\{ (x_1,\ldots,x_n,y)\in\mathbb{R}^{n+1}\ \mid\ y \sum_{j=1}^n x_j^2 = 1\right\}.
$$
Since it is a submanifold of Euclidean space with its canonical flat metric, $M_n$ becomes a Riemannian manifold. I want to compute its sectional curvature (for a given point $(x,y)\in M_n$ and a two vectors $v,w\in T_{(x,y)}M_n$), but do not know how to proceed. For $n=2$, sectional curvature is the same as usual Gaussian curvature and I found a formula for computing it, but for higher dimensions my differential geometry skills are not enough.
It is clear that $M_n$ is the graph of a smooth function on $\mathbb{R}^n\setminus\{0\}$ and it is "rotational invariant", in the sense that the value of the curvature at a point $(x,y)$ should only depend on $\|x\|=\sqrt{\sum_{j=1}^n x_j^2}$, but I don't know if that is of any help.
What I would expect to happen is that the sectional curvature is everywhere non-positive.
But I would like to know wether the sectional curvature of the manifold is bounded below (I would guess yes, because that is what happend for $n=2$) and whether there is a lower bound that does not depend on $n$ (I have no idea what to guess here).
Any help would be greatly appreciated.
Comment: How much do you know about sectional curvature and the second fundamental form?
Comment: This can be computed by first computing the second fundamental form and using the Gauss equations, which provide formulas for the components of the Riemann curvature in terms of the components of the second fundamental form. One way to proceed is to first derive the formula for the second fundamental form of a graph $$ M = \{ (x^1, \dots, x^n, y)\ :\ y = f(x^1, \dots, x^n) \} $$ and apply it to your specific example.
Answer: $\newcommand{\Two}{\mathsf{I}\mathsf{I}}$
$\newcommand{\rD}{\mathrm{D}}$
You can use the second fundamental form and the Gauss-Codazzi equation. For embedded manifolds in a vector space, the Gauss-Codazzi equation reads:
$$R_{vw}w.v = \Two(v, v). \Two(w, w) - \Two(v,w). \Two(v,w)
$$
and the sectional curvature is
$$sec(v, w) = \frac{R_{vw}w.v}{(v.v)(w.w) - (v.w)^2}.
$$
The formula for the second fundamental form with the embedded metric is simply $$\Two(v, w) = (\rD_v\Pi)w = (\rD_w\Pi)v$$
where $\Pi$ is the metric compatible projection to the tangent space. The second fundamental form is a covariant derivative of the projection, but it just works out to that directional derivative if you use the embedded metric in a vector space.
Let $z = (x, y)$ satisfying the defining equation and $C(z) = yx^Tx-1$, then its Jacobian is
$$J:\omega=(\omega_x, \omega_y) \mapsto  2y(x^T\omega_x)+ \omega_yx^Tx
 $$
or in matrix form $J$ is the $1\times (n+1)$ matrix $(2yx^T, x^Tx)$
$$\Pi(z)\omega = \omega - J^T(JJ^T)^{-1}J\omega.$$
Here, $JJ^T = |J|^2 = 4y^2x^Tx + (x^Tx)^2$
$$\Pi(z)\omega = \begin{bmatrix}\omega_x\\ \omega_y\end{bmatrix}
  - \frac{2y(x^T\omega_x)+ \omega_yx^Tx}{4y^2x^Tx + (x^Tx)^2}\begin{bmatrix}2yx\\ x^Tx\end{bmatrix} $$
if $v=(v_x, v_y), w = (w_x, w_y)$ are two tangent vectors then
$$\Two(v, w) =- \frac{2v_y(x^Tw_x)+
  2y(v_x^Tw_x) + 2 w_yx^Tv_x}{4y^2x^Tx + (x^Tx)^2}\begin{bmatrix}2yx\\ x^Tx\end{bmatrix}
  $$
noting that since $w$ is a tangent vector, when you take directional derivative, any term that leaves the Jacobian intact will evaluate to zero. From here, you can evaluate the sectional curvature. You can simplify using $v_y =-\frac{2yx^Tv_x}{x^Tx}$.
See https://arxiv.org/abs/2307.10017 for some other examples of this type of calculation.
As this type of question appears quite often, let's give a general answer. If a hypersurface $M$ is given by a level set equation $\phi(x) = C$ in an inner product space $E$ with $\phi$ is a scalar function, let $g_{\phi}$ be its gradient and $hess_{\phi}$ be its hessian, consider as a bilinear form, so $hess_{\phi}(\xi, \eta)$ is a number for two vectors $\xi, \eta$. Then under the embedded metric

The Levi-Civita connection is
$$\nabla_XY = D_XY + \frac{hess_{\phi}(X, Y)}{|g_{\phi}|^2}g_{\phi}$$
Here, two vector fields $X, Y$ on $M$ are considered as vectors in $E$, and $D_XY$ is the flat connection on $E$, ie simple Lie derivative.
The second fundamental form is $-\frac{hess_{\phi}(X, Y)}{|g_{\phi}|^2}g_{\phi}$.
The sectional curvature numerator is
$$R_{XY}Y.X = \frac{1}{|g_{\phi}|^2} \{hess_{\phi}(X, X)hess_{\phi}(Y,Y)- hess_{\phi}(X, Y)^2\}.
$$

Proof: For 1, the right hand side is a vector field, as differentiating $g_{\phi}^ . Y = 0$ using $X$, we get
$$hess_{\phi}(X, Y) + g_{\phi}. D_XY = 0$$
which implies $g_{\phi}. \{D_XY + \frac{hess_{\phi}(X, Y)}{|g_{\phi}|^2}g_{\phi}\} =0$, it satisfies the usual conditions of a covariant derivative, and metric compatibility follows from
$$2Y . (D_XY + \frac{hess_{\phi}(X, Y)}{|g_{\phi}|^2}g_{\phi}) = 2Y . D_XY= D_X (Y. Y)
$$
as $Y.g_{\phi} = 0$.
For 2, it is well-known $\nabla_XY = \Pi D_XY$ if $\Pi$ is the metric-compatible projection, hence $\Two(X, Y) = D_XY - \Pi D_XY =
D_XY - \nabla_XY=-\frac{hess_{\phi}(X, Y)}{|g_{\phi}|^2}g_{\phi} $. The Gauss-Codazzi equation gives 3.
Comment: Thank you for this nice answer. I will try to work through the details and then accept it, when I understood it (or when I gave up trying to understanding it, but it still sounds nice ;-) )
Comment: $\newcommand{\Two}{\mathsf{II}}$
Another way to derive the SFF is to use the [formula](https://en.wikipedia.org/wiki/Second_fundamental_form)
$$\Two(v, w) = - ( D_v\nu . w ) \nu
$$
where $\nu$ is the Gauss map, so $\nu = \frac{1}{|grad_{\phi}|}grad_{\phi}$, thus
$$D_v\nu .w  = \{D_v(\frac{1}{|grad_{\phi}|})grad_{\phi}
+ \frac{1}{|grad_{\phi}|} D_v grad_{\phi}\} . w
= \frac{1}{|grad_{\phi}|} hess_{\phi}(v, w)
$$
where $grad_{\phi}.w=0$ in the first summand, as $w$ is a tangent vector, and we again have $\Two(v, w) = -\frac{hess_{\phi}(v, w)}{|grad_{\phi}|^2}grad_{\phi}$.
Comment: I did a lot of calculations and - using your formulas - arrived at the conclusion that at a point $(x,y)\in M \subset \mathbb R^{n+1}$, the sectional curvature is $\frac{4}{(4+r^6)r^2}(1+4\cos^2\alpha+4\cos^2\beta)$, where $r=\| x\|$ and $\alpha$ is the angle between x and the first n comonents of the first vector spanning my 2dim subspace of the tangent space, similarly $\beta$ corresponds to the second vector. The problem is: This contradicts my previous computation of the Gauss-curvature in $n=2$, where I got $-\frac{12 r^4}{(4 + r^6)^2}$ ... I am confused ... :-/
Comment: The Gauss-curvature is always below 0 but tends to 0 when r goes to 0. My sectional curvature is always above 0 and goes off to infinity when r approaches 0. I assume I did a stupid calculation mistake somewhere, but so far I could not find it ...
Comment: Thanks! Will check
Comment: Okay, I think I found my mistake. I forget the denominator of the sectional curvature because I thought it would be zero. Now, the formula looks more similar to the Gauss-curvature but the sign is still wrong. And for my original question: It looks as if the section curvature is no longer bounded as soon as n>=3 , which is quite unexpected ...
Comment: Onething when you use these $R^{n+1}$ formulas is for a tangent vector, $(\Delta_x, \Delta_y)$ you have $\Delta_y = -\frac{2yx^T\Delta_x}{x^Tx}$, and you probably need to use this to convert everything to $\Delta_x$. Will get back in a bit.
Comment: For  $\phi(x, y) = yx^Tx$, the Hessian is
$$2w_yx^Tv_x + 2yw_x^Tv_x + 2v_yx^Tw_x
=-\frac{8x^Tv_xx^Tw_x}{(x^Tx)^2} +\frac{2v_x^Tw_x}{x^Tx}
$$
for $v=(v_x, v_y=-\frac{2yx^Tv_x}{r^2}), w=(w_x, w_y=-\frac{2yx^Tw_x}{r^2})$, replacing $y=\frac{1}{x^Tx}$.
Comment: The gradient is $(\frac{2}{x^Tx}x, x^Tx)$
Thus, the numerator and denominator are

$$N = \frac{4}{(4x^Tx+ (x^Tx)^4)}\{(-\frac{4}{x^Tx}(xv_x)^2 + |v_x|^2)(-\frac{4}{x^Tx}(xw_x)^2 + |w_x|^2)
         -(-\frac{4}{x^Tx}(x.v_x)(x.w_x) + v_x.w_x)^2 \}\\
D = ((v_x^Tv_x) + \frac{4(x^Tv_xx^Tv_x)}{(x^Tx)^{4}})
 ((w_x^Tw_x) + \frac{4(x^Tw_xx^Tw_x)}{(x^Tx)^{4}})
  - ( ((v_x^Tw_x) + \frac{4(x^Tv_xx^Tw_x)}{(x^Tx)^{4}})
  )^2.$$
If the tangents are such that $x^Tv_x=0 = x^Tw_x$ we have curvature $\frac{4}{4x^Tx + (x^Tx)^4}$, when $x^Tx = r^2$ goes to infinity, the curvature goes to zero.


Fully Understanding hreflang

Question: I have a website which currently displays all prices in US dollars. I'd like to change it to pounds if you are from the UK and euros if you are from France or Germany. The text on the page will always be displayed in English.
I've explored the various options and most say that Google prefers you to offer different urls for each variation rather that simply render different content based on the users location/ip address.
Therefore say I'm on my shop home page I would offer the following urls (which display the appropriate currency):

www.example.com/shop - default which is US dollars
www.example.com/uk/shop - UK
www.example.com/fr/shop - France
www.example.com/de/shop - Germany

Obviously I don't want Google to penalise me for duplicate content. I have been researching hreflang to get by this but haven't quite fully grasped it as a lot of the examples are over simplified.
Say for example I am on www.example.com/shop. Would I simply render the following within the head?:
<code><link rel="alternate" href="http://www.example.com/uk/shop" hreflang="en-gb" />
<link rel="alternate" href="http://www.example.com/fr/shop" hreflang="fr-fr" />
<link rel="alternate" href="http://www.example.com/de/shop" hreflang="de-de" />
<link rel="alternate" href="http://www.example.com/shop" hreflang="x-default" />
</code>
Now if I was on www.example.com/fr/shop would I need to render the same as above?
Additional Questions:
Should I provide a variant for en-us even though it would be the same as the default?
Also if the user was on www.example.com/shop and I detected the user was from France would I simply redirect the user to www.example.com/fr/shop? My trouble with this is how could someone in France see prices in dollars? I'm assuming I could store a cookie to make sure this redirection only happens the first time.
My final question is does this make sense to do this even though the text will still be in English and the content will only vary by price/currency?
I know that's quite a few questions but I'd really appreciate the clarification. Thanks
Comment: I'm voting to close this question as off-topic because it's not programming but about SEO
Comment: I'm not sure how this is off-topic. It's a programming question which affects SEO. I have added the HTML 5 tag to make it a little clearer.
Answer:
Obviously I don't want Google to penalise me for duplicate content.

Google does not penalize websites for duplicate content.

Say for example I am on www.example.com/shop. Would I simply render the following within the head?

Yes.

Now if I was on www.example.com/fr/shop would I need to render the same as above?

Yes.

Should I provide a variant for en-us even though it would be the same as the default?

No.

Also if the user was on www.example.com/shop and I detected the user was from France would I simply redirect the user to www.example.com/fr/shop? My trouble with this is how could someone in France see prices in dollars?

You should. Add a conversion button on your page.

My final question is does this make sense to do this even tough the text will still be in English and the content will only vary by price/currency?

Not really, you should have translated text too.
Comment: Thanks @JVerstry. In response to the final question. If I didn't do it this way then how else could I display the different currencies? I don't wish to translate all the pages as this would take too much work.
Comment: Let the user configure their preferred currency and set it in a cookie. Then extract the currency from the cookie when they fetch the page.
Comment: That's kind of defeating the purpose. I'd like the user to automatically see the prices in their currency as soon as they come from the search engine.
Comment: Then you want to use Geotargetting: www.w3schools.com/htmL/html5_geolocation.asp or something based on their IP address. You will need to access a free service to convert the latitude and longitude into a country.
Comment: Hmm I'm not sure I like that approach. I'm going to leave this question open for abit longer to see if anyone else has an opinion on the final question. Thanks for your clarification with the remaining points.
Comment: Why don't you like it?
Comment: For now I've decided to ignore the French and German versions and stick to English. This way I can utilize the hreflang and not have to worry about translating any content. Thanks again.

Fully Understanding hreflang


how to fix undefined variable in php?

Question: I have an index.php page. The function of this page is infinite scrolling using AJAX, PHP and MySQL. The top portion contains PHP MySQL codes and bottom contains JavaScript.
I want to print the total number of rows in center of the page, but every time I try it shows "undefined variable" error.
I think when loading the page, the total number of variable tries to print first and then the PHP query takes place, so it shows "undefined variable", but when I put the total number of variable inside the PHP codings, there is no problem.
How can I prevent this?
My index.php is
//my php part here
<?php

if(isset($_POST["anotherID"])){
require_once("config.php");

$limit = (intval($_POST['limit']) != 0 ) ? $_POST['limit'] : 10;
$offset = (intval($_POST['offset']) != 0 ) ? $_POST['offset'] : 0;
$id = $_POST["anotherID"];
$query = $id;
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM x where title like '%xx%'  ORDER BY rand() LIMIT $limit OFFSET $offset";

try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();

$row_object = $DB->prepare("Select Found_Rows() as rowcount");
$row_object->execute();
$roww_object =$row_object->fetchobject();
$actual_row_count = $roww_object->rowcount;

} catch (Exception $ex) {
 echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo'something';
}
}
 $count = $actual_row_count;
 exit;
 }
 ?>

//my html part here

  //some html codes

  <?php echo $count; ?>

 //some html codes here

 //my java scripts here

//some html codes her

I know when a page is loading, the HTML parts are first loaded and then my jQuery stimulates the PHP part and then my results appear.
How can I fix this?
Why does $count always show "undefined variable"?
Thanks in advance.
Comment: If `if(isset($_POST["anotherID"])){` is false, $count will be undefined.  If any statement in the `try {` block generates an exception, $count will be undefined because $actual_row_count will be undefined.  Try to find out where it's happening.
Comment: but i must need the $count value
Comment: @ahgh But the exact value of what? You don't get an ID or anything, so of what do you want the exact count?
Comment: the exact value of no.of rows found in the result. because i'm printing something like " $count items found on this page " ex : "152 items found on this page" bcz i'm using this code to shopping website.
Comment: If you always initialize all of your variables, you won't have this kind of problems...
Answer: You get an error of undefined $count because $count is defined only inside the if statement.
When the if clause doesn't apply $count is not defined.
Add an else clause to the if and initialize $count=0; and it will solve your problem.
Example:
....
$count = $actual_row_count;
exit;
}
else $count = 0;
?>

Comment: but i must need the exact $count value
Comment: But if you never initalized the value of $count, shouldn't it be zero for a start?
Comment: @Amarnasan nope, it should be undefined, but I think the underlying issue in the OP's request is more than just initialization.
Comment: I mean HE should force initalialize its value with a zero in case the code gets an exception and does not set the variable with any result.

how to fix undefined variable in php?


pymongo insert W=2 , J=True speed up

Question: Im using python 2.7.8 and pymongo 2.7
and the mongoDB server is a ReplicaSet group one primary two secondary .
the mognodb server is built on AWS server EBS:500GB, IOPS3000 .
I want to know is there any way to speed up the insert.when W=2, j=True
Using pymongo to insert a million of files takes a lot of time
and i know that if i use the W=0 it will speed up ,but it isn't safe
So any suggestion ? Please help me thanks.
Answer: Setting W=0 is deprecated. This is the older model of MongoDB (pre-3.0), which they don't recommend using any more.
Using MongoDB as a file storage system also isn't a great idea; but, you can consider using GridFS if that's the case.
I assume you're trying some sort of mass-import, and you don't have many (or any) readers right now; in which case, you will be okay if any reader sees some, but not all, of the documents.
You have a couple of options:

set j=False. MongoDB will return more quickly (before the documents are committed to the journal), at the potential risk of documents being lost if the DB crashes.
set W=1. If replication is slow, this will only wait until one of the nodes (the primary) has the data before returning.

If you do need strong consistency requirements (readers seeing everything inserted so far), neither of these options will help.
Comment: Thank you for  your help
Answer: You can use unordered or ordered bulk inserts
This speeds up things alot. May be also you take a look at my muBulkOps a wraper of pymongo bulk operations.
Comment: @周辰彩 may be then you can mark my answer as the acceptable one as it seems people here din't like it much and degraded it, although the link I provided points to mongoDB's official site and will never die, not until the product dies any way:-)

pymongo insert W=2 , J=True speed up


How to seal hole from bundle of ethernet cables running through wall/floor?

Question: I'm setting up a home ethernet network in a spare bedroom. I envision running up to two dozen ethernet cables out of a patch panel in this room to the rest of the house. I'll likely bundle these cables, punch through an interior wall and down into our crawl space.
How do folks recommend getting this many cables out of the room and down to the crawl space?
When I've previously run single ethernet cables between rooms, I've drilled small holes in bottom plates and sealed up these holes with caulk.
But, to make a hole large enough for 24 cables, I'm picturing having to make a much bigger hole. Sealing a hole this big with caulk seems like a mess, particularly if I have to run new cables in the future. But, if I don't seal the hole, I worry we'll get vermin coming up from the crawl space into the house (we've got a mouse problem).
I've also seen recommendations to place the cables in a pipe or conduit running down to the crawl space. But, it seems you'd have the same problem at the end -- how do you seal the end of the conduit where the cables come out?
Comment: In many jurisdictions, there is a code requirement that all holes through the floor plate be sealed with fire resistant foam. This is to prevent fire from moving from floor to floor, similar to requirements for fire block framing.
Comment: I imagine, on the end of a conduit through the floor, you could put a piece of rubber, like a balloon, that you can seal against the conduit, but will allow for stretch and expansion as needed. Or a plastic hole grommet that has a flexible out like a j-box clamp.
Comment: Thanks both for these informative responses. I particularly like idea of flexible clamp at the end of the conduit!
Answer: Conduit & Patch Panel
If you're patch panel is embedded in the wall, you might need some additional structural support around it. I would make 2 runs of 2" conduit down to your crawl out of the patch panel. The reason for using conduit rather than just plain wires is that it makes a more finished result and will be easier to add new wires/remove  wires in the future. It'll also be easier to seal it with fire resistant caulk. Once you get into your crawl, you can just put a bushing on the end to terminate the conduit and run your Ethernet freely. Ethernet is low voltage which allows you to run it how you see fit. However, my recommendation would be to use zip-tie tags to group the cables together by room and use the label to notate which room the cables lead to. You can keep the cables up off the ground with zip-ties with screw mounts. However, it's critical not to over tighten the zip ties as it can damage the cable.
Fire Block
Most places require that all holes between levels of a building be sealed with some fire block. There are several different methods for this, but probably the easiest with fire-resistant caulk. Basically, the job of the caulk is to seal off the cavity so that the fire in one area cannot use the small holes in the cavity to pull air from to fuel itself. When the caulk is heated up, it expands in the hole working to keep a consistent seal. Another purpose is to prevent the fire from spreading up the wire.
Comment: No worries and this is still super-helpful! I haven't started the job and will take this into account!
Comment: Just saw this is a 6 month old question. Sorry for being late to the party
Comment: Is your recommendation here to put 2" conduit through the wall and toe plate or along the wall and through the floor? (Sorry... Old thread).
Comment: I think the short answer is whatever gets the job done. Ideally, you'd get a patch panel enclosure to sit between your studs ([like this](https://a.co/d/cI6SSxW)). Then run some conduit through the toe plate between the panel and craw space in the wall cavity. So in that case, yes it'd be through the toe plate. If you're uncomfortable with it (eg: on an exterior wall/load bearing), just drill through the floor, but that defeats the purpose of a wall recessed panel. As long as you're dead center in the toe plate, you should be okay. YMMV
Answer: I would use Conduit with cable management grommet on the living space end and stuff steel wool in the end in the crawl space.
Easy to take out the steel wool if new cable is needed, keeps out mice and voles.


Schedule to turn off monitor via crontab?

Question: I want to turn off monitor on a specific period of time automatically (for example between 07:00 and 11:00). Is there any command to be set in crontab file? Is there any better way?

In summary:
Turning off the monitor at 07:00 automatically.
Turning on the monitor at 11:00 automatically.

scren-saver & lock screen are disabled!
Comment: Close-voter(s): The answer here is generally applicable to other people who want something similar--even if the OP never replied back this should still not be closed as not reproducible. (Also, the OP said it would take about *one day* to come back and check if the answer worked.) If there's some other reason to close this, I recommend commenting.
Comment: Related [Manually turn off monitor](https://askubuntu.com/questions/253818/manually-turn-off-monitor/253821#253821)
Answer: Assuming that you are using the default gnome-screensaver for Ubuntu, open a terminal and run next commands followed by instructions:

mkdir -p bin - this command will make a bin directory in your home folder if you don't already have it.
gedit ~/bin/screen_on_or_off.sh - this will create the new file screen_on_or_off.sh in gedit.
Copy and paste the next script:
#!/bin/bash

export DISPLAY=:0 #very important if you want to be runned by a cron job

current_hour=$(date +"%k")

# Defining the disable_screensaver function
function disable_screensaver {
    # Disabling sleep time
    # 0 value will never turn the screen off; you can change this value as you wish:
    # for example to turn the screen of after 10 min, use 600
    gsettings set org.gnome.settings-daemon.plugins.power sleep-display-ac 0
    gsettings set org.gnome.settings-daemon.plugins.power sleep-display-battery 0
    gsettings set org.gnome.desktop.session idle-delay 0
}

# Defining the enable_screensaver function
function enable_screensaver {
    # Enabling sleep time to 1 second
    gsettings set org.gnome.settings-daemon.plugins.power sleep-display-ac 1
    gsettings set org.gnome.settings-daemon.plugins.power sleep-display-battery 1
    gsettings set org.gnome.desktop.session idle-delay 1

    notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "Let's go to sleep now!"
}

if [ "$current_hour" -ge "7" ] && [ "$current_hour" -lt "11" ]; then
    enable_screensaver
else
    disable_screensaver
fi

exit 0

Save the file and close it.
Go back into terminal and run: chmod +x screen_on_or_off.sh - to grant execute access for the script.
Just for test, to run your new script, type in terminal ~/bin/screen_on_or_off.sh.
Edit the crontab entries using crontab -e command (by default this will edit the current logged-in users crontab) and add the following line:
*/1 * * * * /home/$USER/bin/screen_on_or_off.sh  #change $USER with your username

I have set the cron job for every minute, but you can change as you wish or as you think is better. See http://en.wikipedia.org/wiki/Cron in this sense.
Save the file and check the new crontab entry with crontab -l.

Now your screen will turn off every day between 7 and 11.
Comment: I've disabled gnome-screensaver and lock-screen, this is the reason that I want to turn off the monitor by command line automatically! Another note: The computer is at work, I'm on vacation now; however, I'll check your instruction tomorrow and put a feedback here :)
Answer: Newer and much simpler answer, put this in cron:
0 07 * * *  export DISPLAY=:0 && xset dpms force off
0 11 * * *  export DISPLAY=:0 && xset dpms force on


How can I push one Git commit without an earlier one?

Question: I have made a git commit but I have not pushed. And I am now working on a new bug fix, which should not touch the same files as the first commit.
Is it possible for me to commit this bug fix AND git push only this commit?
Comment: It looks like you have asked over 50 questions but have accepted answers to only a small fraction of those. Please consider using the "accept" function to mark the answer that was the most helpful for you.
Answer: All of the commits leading up to a particular commit are what defines that new commit.
That is, if you have a master → dev → bugfix as shown in the image below:
master → dev → bugfix http://img.skitch.com/20091029-tbffrg53q73mdipiwcr3g2ywuh.png
you can push dev alone but not bugfix alone, but the definition of bugfix includes dev, so dev has no meaning without bugfix
However, if you build this bugfix out as a feature branch, you'd have something that looked more like this:
feature branch http://img.skitch.com/20091029-t3w5qk3bhj3ftx1d9xnk32ibkb.png
You could still retroactively do that (create a new branch from origin/master, cherry-pick the change, and then git reset --hard HEAD^ on your development branch to get the bugfix change off of it).
Once that's complete, you can forward-port your dev branch with a simple git rebase master and it'll look like this:
new master http://img.skitch.com/20091029-1ts3enwsmsr29imcu7tyk75ett.png
In practice, starting bug fixes from a branch will make this kind of thing a lot easier in general.
Answer: What you can do is move the previous commit to a (temporary) branch, and cherry-pick your new commit to the master. For example:
# first commit your current work
git branch temp_branch
git reset --hard HEAD~2
git cherry-pick temp_branch
git push

Then, temp_branch will contain both your new commits. You can then later pick your previous one back to master:
git cherry-pick temp_branch^
git branch -D temp_branch

After doing this, your master branch will contain the same two commits as you started with, but in the opposite order.
Answer: just do another clone and push your bug fix from there.
Answer: Our shop uses personal branches extensively. Basically the process would go like this:
Given that you are currently on the master branch
git checkout -b bug_fix_name_that_I_dont_want_to_commit

The above creates a branch and checks it out...this is where you put the commits that you are not ready to push.
Now you should be able to make commits to the current branch without affecting the master branch.
When you're ready to publish/push that one commit, just do:
git push origin master

and your other commits will not go to the origin repository.
When you're ready to incorporate the "bug fix" into the master branch, checkout the master branch and do;
git merge bug_fix_name_that_I_dont_want_to_commit

I think this answers the question, but if not, just let me know!


How to use virtualenv in Python project?

Question: I'm trying to use virtualenv in my new mainly Python project. The code files are located at ~/Documents/Project, and I installed a virtual environment in there, located at ~/Documents/Project/env. I have all my packages and libraries I wanted in the env/bin folder.
The question is, how do I actually run my Python scripts, using this virtual environment? I activate it in Terminal, then open idle as a test, and try

"import django"

but it doesn't work. Basically, how can I use the libraries install in the virtual environment with my project when I run it, instead of it using the standard directories for installed Python libraries?
Comment: If you start a virtualenv, and then open IDLE, I don't think IDLE will open referencing your virtualenv.
Answer: Check out the example below, and also the virtualenv documentation. It's actually fairly straightforward if you follow the steps:
virtualenv Project  # creates a new Project dir
cd Project/bin      # could just call Project/bin
. activate          # should now have (Project) in the prompt name
pip install django  # without this, won't be able to import django
deactivate          # switch of virtual mode

I tried the above out in my Mac and worked fine. Here's a transcript for reference.
Transcript of operations
[MacMini]<Documents> :virtualenv Project

[MacMini]<Project> :cd bin/

[MacMini]<bin> :python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named django
>>> quit()

[MacMini]<bin> :. activate

(Project)[MacMini]<bin> :pip install django
You are using pip version 6.0.6, however version 8.1.0 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting django
  Downloading Django-1.9.4-py2.py3-none-any.whl (6.6MB)
    100% |################################| 6.6MB 1.2MB/s
Installing collected packages: django

Successfully installed django-1.9.4

(Project)[MacMini]<bin> :python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> quit()

(Project)[MacMini]<bin> :deactivate

Comment: I think the problem might be that I don't have my Python code in the right place. Right now, I have all of my source code under /Documents/Project, and the env is also within that. Do I have to put my project Python files within a special directory in the environment folder? @abehrens
Comment: That shouldn't be a problem unless your code directory structure conlicts with the virtualenv structure that prevents 'activate' being sourced correctly. Try creating a brand new temp env first and then copying your code to that temp env. Remember to 'source the activate' script and not actually executing it. Also, check you have cleared any PYTHONPATH variable.
Answer: It's also good practice to make a requires.txt file for all your dependencies.  If for example your project requires Flask and pymongo, create a file with:
Flask==<version number you want here>
pymongo==<version number you want here>

Then you can install all the necessary libraries by doing:
pip install -r requires.txt
Great if you want to share your project or don't want to remember every library you need in your virtualenv.


How to Merge/Combine 2 select statemenst based on a condition

Question: I have the following 2 select statements which I would like to merge having the entry and exit times next to each other in table based on the Date column which must match.
<code>     SELECT NAME, SURNAME,IDENTIFIER, CONVERT(VARCHAR,(MIN(TRANSIT_DATE)),114) AS [ENTRY],'' AS      [EXIT], CONVERT(VARCHAR(10),TRANSIT_DATE,103)AS [DATE]
  FROM [10.230.0.15].[SCAT].[dbo].[HA_TRANSIT] a
  WHERE STR_DIRECTION = 'Entry'
  and a.IDENTIFIER = '20045619'
  AND STR_TRANSIT_STATUS = 'Granted'
  AND TRANSIT_DATE BETWEEN @CompleteSDate AND @CompleteEDate
  GROUP BY NAME, SURNAME,IDENTIFIER,CONVERT(VARCHAR(10),TRANSIT_DATE,103)

 SELECT NAME, SURNAME,IDENTIFIER, '' AS [ENTRY],CONVERT(VARCHAR,(MAX(TRANSIT_DATE)),114) AS [EXIT], CONVERT(VARCHAR(10),TRANSIT_DATE,103)AS [DATE]
 FROM [10.230.0.15].[SCAT].[dbo].[HA_TRANSIT] a
 WHERE STR_DIRECTION = 'Exit'
 and a.IDENTIFIER = '20045619'
 AND STR_TRANSIT_STATUS = 'Granted'
 AND TRANSIT_DATE BETWEEN @CompleteSDate AND @CompleteEDate
 GROUP BY NAME, SURNAME,IDENTIFIER,CONVERT(VARCHAR(10),TRANSIT_DATE,103)
</code>

RESULTS of Query 1 NAME   SURNAME IDENTIFIER  ENTRY    EXIT   DATE
  ANTONETTE COLEMAN 20045619          07:11:01:000      10/09/2013
  ANTONETTE COLEMAN 20045619          06:58:58:000      11/09/2013
  ANTONETTE COLEMAN 20045619          07:04:27:000      12/09/2013
  ANTONETTE COLEMAN 20045619          07:02:48:000      13/09/2013
  ANTONETTE COLEMAN 20045619          07:17:43:000      16/09/2013
  ANTONETTE COLEMAN 20045619          06:54:35:000      17/09/2013
  ANTONETTE COLEMAN 20045619        07:00:36:000        18/09/2013
  ANTONETTE COLEMAN 20045619          06:57:33:000      19/09/2013
RESULTS of Query 2 NAME   SURNAME IDENTIFIER     ENTRY    EXIT
  DATE ANTONETTE    COLEMAN 20045619        16:09:39:000    10/09/2013
  ANTONETTE COLEMAN 20045619        16:01:19:000    11/09/2013
  ANTONETTE COLEMAN 20045619        16:18:49:000    12/09/2013
  ANTONETTE COLEMAN 20045619        16:04:28:000    13/09/2013
  ANTONETTE COLEMAN 20045619        16:06:04:000    16/09/2013
  ANTONETTE COLEMAN 20045619        16:05:30:000    17/09/2013
  ANTONETTE COLEMAN 20045619        16:02:00:000    18/09/2013
Answer: You probably don't need two SELECTs, the only difference in your WHERE-conditions is STR_DIRECTION. Just move it into CASEs:
<code>   SELECT NAME, SURNAME,IDENTIFIER,
       CONVERT(VARCHAR,(MIN(CASE WHEN STR_DIRECTION = 'Entry' THEN TRANSIT_DATE END)),114) AS [ENTRY],
       CONVERT(VARCHAR,(MAX(CASE WHEN STR_DIRECTION = 'Exit'  THEN TRANSIT_DATE END)),114) AS [EXIT],
       CONVERT(VARCHAR(10),TRANSIT_DATE,103)AS [DATE]
   FROM [10.230.0.15].[SCAT].[dbo].[HA_TRANSIT] a
   WHERE STR_DIRECTION IN ('Entry', 'Exit')
   AND a.IDENTIFIER = '20045619'
   AND STR_TRANSIT_STATUS = 'Granted'
   AND TRANSIT_DATE BETWEEN @CompleteSDate AND @CompleteEDate
   GROUP BY NAME, SURNAME,IDENTIFIER,CONVERT(VARCHAR(10),TRANSIT_DATE,103)
</code>
Comment: This looks like what im looking for but its complaining about a Incorrect syntax near ')' Can't seem to be a bracket as they are all tying up...
Comment: I just forgot the ENDs in my CASEs. FIxed my answer
Answer: <code>SELECT NAME, SURNAME,IDENTIFIER, CONVERT(VARCHAR,(MIN(TRANSIT_DATE)),114) AS [ENTRY],''     AS      [EXIT], CONVERT(VARCHAR(10),TRANSIT_DATE,103)AS [DATE]
  FROM [10.230.0.15].[SCAT].[dbo].[HA_TRANSIT] a
  WHERE STR_DIRECTION = 'Entry'
 and a.IDENTIFIER = '20045619'
 AND STR_TRANSIT_STATUS = 'Granted'
 AND TRANSIT_DATE BETWEEN @CompleteSDate AND @CompleteEDate
 GROUP BY NAME, SURNAME,IDENTIFIER,CONVERT(VARCHAR(10),TRANSIT_DATE,103)

UNION

 SELECT NAME, SURNAME,IDENTIFIER, '' AS [ENTRY],CONVERT(VARCHAR,    (MAX(TRANSIT_DATE)),114) AS [EXIT], CONVERT(VARCHAR(10),TRANSIT_DATE,103)AS [DATE]
FROM [10.230.0.15].[SCAT].[dbo].[HA_TRANSIT] a
WHERE STR_DIRECTION = 'Exit'
and a.IDENTIFIER = '20045619'
AND STR_TRANSIT_STATUS = 'Granted'
AND TRANSIT_DATE BETWEEN @CompleteSDate AND @CompleteEDate
GROUP BY NAME, SURNAME,IDENTIFIER,CONVERT(VARCHAR(10),TRANSIT_DATE,103)
</code>
Comment: YOU used Union to merge or combine two or more than two select statements
Comment: No you can't just do a union, as the exit and entry dates must be next to each other in 1 row if the dates are the same


Export Data-tier application error

Question: I am trying to export a rather simple database using the Export Data-tier application and keep getting the following error:
One or more unsupported elements were found in the schema used as part of a data package.
Error SQL71564: The element Extended Property: [dbo].[DailyResult].[ScanTypeID].[MS_Description] is not supported when used as part of a data package (.bacpac file).
I have removed the description for the indicated column, but continue to receive this error. Any ideas?
Answer: I had a database reference in the offending object.  Once i removed that it exported without an issue. I changed;
    [MyDatabase].[Work].[Job]
to
    [Work].[Job]
Answer: You can do as Amir978 suggested to remove the extended property, however, if you want to keep the extended property in your database and use Export, you can do this using the latest version of SQL Server Data Tools.
The latest update to Microsoft Azure SQL Database (Azure V12) added support for Extended Properties, and the DacFx Export operation has been updated to allow extended properties.
Alternatively, if you are targeting more than just Azure, you can use the Extract functionality to produce a dacpac. A dacpac is not limited to just the set of features supported on Microsoft Azure SQL Databases.
I hope this helps
Lonny
Answer: You should not remove Description manually. Instead try this script:
GO
EXEC sp_dropextendedproperty
    @name = N'MS_Description'

    ,@level0type = N'Schema', @level0name = dbo
    ,@level1type = N'Table',  @level1name = 'tableName'
    ,@level2type = N'Column', @level2name = 'fieldName';
GO

Export Data-tier application error


Set a theme and palette for all plots

Question: I'm trying to simplify my plots in ggplot2. Suppose I want to create a scatterplot from iris dataset:
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point()

But suppose I don't like ggplot2 default theme and palette. Let's say I want to use theme_bw and Dark2 palette:
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point() +
  theme_bw() +
  scale_color_brewer(palette="Dark2")

And suppose I have lots of plots and I want all of them using theme_bw and Dark2 palette. I know I can use theme_set(theme_bw()) to make all my plots have the black and white theme. Is there a similar function to make all my plots use Dark2 palette? In other words, how can I run a code like
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point()

and have theme_bw and Dark2 palette in all my plots?
Answer: One solution would be to write a custom wrapper:
ggcust <- function(...){
  ggplot(...) +
    theme_bw()
}

fill in all the theme options you need, then use it like this:
ggcust(data = mtcars, aes(x = mpg, y = cyl)) +
  geom_point()

Comment: Yeah, you can fill in anything you need within the wrapper, I just wanted to keep the example simple. Glad it helped.
Comment: Since I wanted both theme and palette, I had to add a line with `scale_color_brewer(palette="Dark2")` in your suggested code, but it worked. Thanks.
Answer: You can also put layers into a list:
gglayer_theme <- list(
  theme_bw(),
  scale_color_brewer(palette="Dark2")
)

And treat the list like a new layer (Note + becomes , in this list notation):
ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point() +
  gglayer_theme

The advantage to the custom wrapper approach is the ability to easily mix layers:
gglayer_labs <- list(
  labs(
    x = "x",
    y = "y"
  )
)

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point() +
  gglayer_theme +
  gglayer_labs

Or combine them beforehand:
gglayer_all <- c(gglayer_theme, gglayer_labs)

ggplot(iris, aes(x=Petal.Length, y=Petal.Width, colour=Species)) +
  geom_point() +
  gglayer_all

Set a theme and palette for all plots


Is there currently lighting on the market that can simulate sunlight?

Question: During northern winter I always wish I had lighting powerful enough to simulate sun shining in my window (or from my ceiling). Are there currently products on the market powerful enough to do so?
I'm using 1500Lm LED lamps with a 2700k color rating, but they're very much far from what sunlight looks like.
Comment: Powerful enough: no. You need absurd amounts of power to approach the brightness of sunlight (100,000 Lm). You can however get lighting that replicates the spectrum of sunlight, which is more important.
Comment: Answers posted so far are weak.  You need office style lighting, which is Very Bright compared to traditional home lighting.  A single 6-lamp T8 fixture is *twice as bright* as that dangerous 500W halogen, and you can get fluorescent tubes cheaply in 5000-6500K and high CRI, which does a better job emulating the sun.  Talk the people who do office or better the "indoor horticulture" people doing grow lighting, they put a staggering amount of light in small spaces.
Comment: VTC - This is an off topic shopping question.
Comment: @Hobbes it's reachable. two 400W HPS lights will give you that many lumens.  So will 32 T8 tubes.  That's eight 4-lamp 2x4 troffers, or 6 if they are 6-lamp.
Answer: Yes, look for lighting solutions used to treat Seasonal Affective Disorder (SAD).
Desktop Panels

The theory behind conventional Full Spectrum (White Light) light boxes is that they effectively replicate sunshine. As a result they give the user a positive response when they are lacking sunshine.

- Buying a SAD light

Bulbs
There are also replacement lightbulbs that claim to have similar purposes

6 watt LED R50 E27 ES Edison screw globe bulbs with opal cover
  DAYLIGHT WHITE SUITABLE FOR SAD Sufferers
  480 lumen, daylight white 6400k, 30000 hour bulbs

6400K is obviously higher than 2700K
Of course, 480 lumens is very little, You'd need a ceiling fixture that can take many E27 bulbs.
There are 800 lumen E27 bulbs and higher output bulbs in T8 tube format etc.
search for "full spectrum" "seasonal affective disorder" light bulb
Comment: Though I cant find a reputable source to link ATM, effective treatment for SAD is more about brightness than spectrum.  Newer ones are not always full spectrum, the main requirement is that they put out about 10000 lux.
Comment: This looks great, but most look like they're handheld lamps for direct exposure. Are there solutions to install on the wall/ceiling to provide lighting for an entire house?
Comment: @JonathanReez: answer updated.
Comment: @Grant I'd be great to have 10000 Lux panels covering the whole ceiling, but I can't seem to find any manufacturers of such powerful lighting
Answer: If it's Seasonal Affective Disorder you are trying to cure, see a doctor.  Light therapy can work, but needs to be managed properly.
I suspect part of your problem is not the color spectrum, but brightness.  I've noticed in the winter everything seems so much darker - part of that is replacing all the 100w light bulbs with 40 or 60w equivelent LED bulbs.  They don't put out nearly as much light.
If you just want to make your room bright again for awhile, the cheapest way is halogen work lights with T3 halogen bulbs.  I use them in my office for a couple hours a day and it's wonderfully bright.  They put out a lot of heat as well, which is fine in the winter.  I found I was fine with the yellowish light (same as any old incandescent bulb) as long as it made the room nice and bright.
You can get 500w halogen work lights for under $20 that put out 8000 lumens.  Ten times what a 60w LED bulbs puts out.
There are similar permanent fixtures (though usually only for up to 200w bulbs) you can install.  I used to have one above the bathroom mirror which was wonderful.  This isn't a very power efficient option, but if you are only using it an hour or two a day it won't make that big a difference.


King Composer - add multiple JS file for Google Map Field

Question: I need to add multiple JS file in using king composer.
I follow Add Map
but could not load multiple files.
Code is use for WordPress theme option for show map on selection page.
<code><?php
$kc->add_map(array(
    'location' => array(
        'name' => 'Locations',
        'description' => 'Add your location details',
        'icon' => 'cpicon kc-icon-map',
        'category' => 'Content',
        'assets' => array(
            'scripts' => array(
                'googlemap_js' => "MY JS FILE PATH",
                'type' => 'javascript',
                'jquery' => '',
            ) ,
            'scripts' => array(
                'location_js' => 'MY JS FILE PATH',
                'type' => 'javascript',
                'jquery' => '',
            ) ,
        ) ,
        'params' => array(
            array(
                'name' => 'image',
                'label' => 'Upload Images',
                'type' => 'attach_images',
                'admin_label' => true,
            ) ,
        )
    ) ,
));
?>
</code>
Comment: And the error is...? https://stackoverflow.com/help/mcve
Comment: @MaciejJureczko I didn't got any error but load only one JS fine, is there missing from my side?
Answer: You are using wrong ways to add the scripts;
It must be
<code>    <?php
$kc->add_map(array(
    'location' => array(
        'name' => 'Locations',
        'description' => 'Add your location details',
        'icon' => 'cpicon kc-icon-map',
        'category' => 'Content',
        'assets' => array(
            'scripts' => array(
                'googlemap_js' => "MY JS FILE PATH",
                'location_js' => 'MY JS FILE PATH',
                'js_lib1' => 'MY JS FILE PATH',
                'js_lib2' => 'MY JS FILE PATH',
                'jquery' => '', //calling the script enqueue before - enqueue from other place.
            ) ,
        ) ,
        'params' => array(
            array(
                'name' => 'image',
                'label' => 'Upload Images',
                'type' => 'attach_images',
                'admin_label' => true,
            ) ,
        )
    ) ,
));
?>
</code>
Comment: Thank you for your answer I'll check. :)


filter free hour from javascript time array

Question: I have javascript array with a teaching hour of a teacher in a day
{
"time": [
  { "start":"10:00","end":"11:00" },
  { "start":"12:00","end":"01:00" },
  { "start":"04:00","end":"06:00" }
]
}

I want to find out free hour of from above array between 10 AM to 6PM
Output array will like this :
{
"time": [
  { "start":"09:00","end":"10:00" },
  { "start":"11:00","end":"12:30" },
  { "start":"01:00","end":"04:00" }
]
}

please help me out to solve this
Comment: Where's your code? What have you tried so far?
Answer: I have compared end of one object with the start of next object;
based on their difference I decide whether or not to include it in freetime.

let timeObj =  {
"time": [
  { "start":"10:00","end":"11:00" },
  { "start":"12:00","end":"01:00" },
  { "start":"04:00","end":"06:00" }
]
}

let newObj = {"time" : []}
let timeArr= timeObj["time"];
for(i=0;i<timeArr.length; i++) {
  if(timeArr[i+1] != undefined) {
    if(timeArr[i]["end"] != timeArr[i+1]["start"]) {
      let freetime = {
       "start" : timeArr[i]["end"],
       "end" : timeArr[i+1]["start"]
      }
      newObj["time"].push(freetime);
    }
  }
}

console.log(newObj)
Answer: Try this approach

var obj = {
  "time": [{
      "start": "10:00",
      "end": "11:00"
    },
    {
      "start": "12:00",
      "end": "01:00"
    },
    {
      "start": "04:00",
      "end": "06:00"
    }
  ]
};
var numConvert = (t) => (t = Number(t.replace(":", ".")), t += t < 10 ? 12 : 0, t);
var output = [];
var output = obj.time.map(s => [numConvert(s.start), numConvert(s.end)])
  .reduce(function(a, b, i, arr) {
    (i < arr.length - 1) ? (a || []).push([b[1], arr[i + 1][0]]): [];
    return a;
  }, []).map(s => ({
    start: s[0],
    end: s[1]
  }));

console.log(output);


USB device not mounting in Ubuntu 14.04

Question: When I do
lsblk

This is what I see...
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 465.8G  0 disk
├─sda1   8:1    0   500M  0 part
├─sda2   8:2    0  99.5G  0 part /media/archisman/Windows
├─sda3   8:3    0 335.8G  0 part /media/archisman/DINDA
├─sda4   8:4    0     1K  0 part
└─sda5   8:5    0    30G  0 part /
sdb      8:16   1  14.7G  0 disk

That sdb is my USB device.
But then I cannot see the device in my file manager.
Somebody please help, I am new to Linux.
Comment: Maybe this can help --> http://askubuntu.com/questions/522515/sandisk-usb-not-detected-by-ubuntu-14-04-but-detected-by-windows-7
Comment: @Parto It did not.
Answer: NTFS file system is not supported in Linux
Try formatting your USB drive with a fat filesystem
Then it will automatically get mounted
Comment: And how can i do that?

USB device not mounting in Ubuntu 14.04


VMware Tool up to date or not via commandline (Windows)

Question: I have been trying to automate Windows server build QA in my company. One of the tasks is to make sure vmware tools is up to date or not. Servers are built off of templates which may not be up to date.
Obviously I thought of getting the vmware tool version on the new build and comparing it with a standard build number to determine uptodateness. But that leaves little room for flexibility.
Now, if the vmtools are not upto date, the server shows a notification in the tray. So I am looking for a way to obtain that result remotely through commandline(I am open to using psexec). Am I asking for the impossible?
Answer: You can download all VMWare Tools manually Here
Write a program to compare the file size of online and offline files
and update it if they are outdated.
Schedule the Program as per your requirements
Answer: This is what I am using right now. Getting the installed version and comparing with the current version number. It is not the best way but it works for me.
<code>$VMtoolVersion = Invoke-Command -ComputerName $FQDN -Credential $PSCredential -ScriptBlock { & 'C:\Program Files\VMware\VMware Tools\VMwareToolboxCmd.exe' -v} -ErrorAction Stop
if($VMtoolVersion -match "220.127.116.11277")
            {
                Write-Host "`tUPTO DATE" -ForegroundColor Green
            }
            else
            {
                Write-Host "`tOUT OF DATE. Please Update VMWare Tools " -ForegroundColor Red
            }
</code>
Problem is when the tool version is higher than 22.214.171.124277, it is still gonna give me "Outdated" message. So the script will need to be updated as tools get updated.


MG 42 Chrome customization special assignment unlock

Question: In Battlefield V, there is a chrome skin for the MG 42 that says it can be unlocked via a special assignment. I found this reddit thread that asks the same question, but an answer was not found.

What is the assignment, and how can it be unlocked?
Answer: This was a bug, and it no longer exists in the game as of June of 2019. The chrome skin for the MG 42 no longer says there is a special assignment; it is only obtainable with company coin.

The Urban Blue skin is unlocked through leveling up the gun, the Mint skin is unlocked by completing the MG 42 Proficiency assignment series, and the Gold Plated skin is unlocked by completing the MG 42 Mastery assignment series.
Answer: I believe the chrome skin is awarded after completing the mastery assignment with the gun. Once you level up the MG42, it will unlock an assignment. Complete that and you get the skin for mastering the gun.
Since this is a special assignment, maybe it isn't in the game yet? It is also, not inconceivable, that there is a bug in the game preventing either the assignment from being unlocked or the skin simply not being awarded.


Changing the Cross-Hair Scale After the Update?

Question: Since the large update Valve made to Counter-Strike Source about 6 months ago, I stopped playing for a bit. Now that I've come back, I've noticed something peculiar. I used to be able to change the size of my cross-hair with the command
cl_crosshairscale 20000

This would scale it down to as small as possible - the way I liked it. When I run that command now, the scale doesn't change. Is it still possible to change the scale? If so, how?
Answer: Commands for setting crosshair properties have changed recently.
Check this sticky thread for details.
As for your specific issue, setting cl_legacy_crosshair_scale 1 will fix it.


C# LINQ query fails when using IsAbstract property during derived class scan with reflection?

Question: I am using reflection to scan for all the class types that derive (are assignable) from a particular base class.  That part works fine.  But when I try to filter the resulting list by the IsAbstract property to get a list of only the non-abstract classes, the LINQ query that does the filtering fails to work correctly.  Instead, I had to resort to a foreach loop and do it "manually."  I tried this query first:
       if (!bAcceptAbstract)
           retListFiltered = (from typeClass in retList where typeClass.GetType().IsAbstract == false select typeClass).ToList();

But that didn't filter out the class types marked as abstract.
I then tried:
retListFiltered = (from typeClass in retList where !typeClass.GetType().IsAbstract select typeClass).ToList();

But again, no filtering.  Why doesn't the LINQ query seem to respect the value of the IsAbstract propery?
Below is the code I ended up having to use:
   public static List<System.Type> GetAllDerivedTypes<T>(Assembly primaryAssembly, bool bAcceptAbstract = true) where T : class
    {
        if (primaryAssembly == null)
            throw new ArgumentNullException("The primary assembly is unassigned.");

        List<System.Type> retList =
            primaryAssembly.GetTypes().Where(type =>
                typeof(T).IsAssignableFrom(type))
            .ToList();

        List<System.Type> retListFiltered = new List<System.Type>();

        foreach (System.Type typeClass in retList)
        {
            if (bAcceptAbstract || !typeClass.IsAbstract)
            {
                Debug.WriteLine(String.Format("INCLUDED {0} class, abstract value: {1}.", typeClass.Name, typeClass.IsAbstract.ToString()));

                retListFiltered.Add(typeClass);
            }
            else
                Debug.WriteLine(String.Format("IGNORED abstract class: {0}.", typeClass.Name));
        }
        return retListFiltered;
    }

Comment: why are you calling GetType on typeClass? `typeClass.GetType().IsAbstract` should be `typeClass.IsAbstract`, so:
`(from typeClass in retList where typeClass.IsAbstract == false select typeClass).ToList();`
Comment: The other comments are right. The sequence `obj.GetType().IsAbstract` wil always return false because `GetType()` always finds the concrete (non-abstract) actual type at runtime, and by nature, that is not abstract. **Addition:** If `obj` is already an object that represents a type, i.e. if `obj` is declared as a `System.Type` variable, then `obj.GetType()` will return a concrete derived class of `System.Type` which is the `internal` class `System.RuntimeType`.
Comment: @FrédéricHamidi Well, `typeof(System.Type).IsAbstract` is true, but clearly `typeClass.GetType()` will return the actual concrete subclass of `System.Type` which is used. It happens to be an `internal` (non-abstract of course) class `System.RuntimeType` (as I just said).
Answer: In your example
if (!bAcceptAbstract)
       retListFiltered = (from typeClass in retList where typeClass.GetType().IsAbstract == false select typeClass).ToList();

the typeClass is already a Type, so there's no need to call GetType() on it again. The following works:
(from typeClass in retList where typeClass.IsAbstract == false select typeClass).ToList();

You can write
public static List<System.Type> GetAllDerivedTypes<T>(Assembly primaryAssembly, bool bAcceptAbstract = true) where T : class
{
    if (primaryAssembly == null)
        throw new ArgumentNullException("The primary assembly is unassigned.");

    return !bAcceptAbstract ? primaryAssembly.GetTypes().Where(type => typeof(T).IsAssignableFrom(type) && !type.IsAbstract).ToList() : primaryAssembly.GetTypes().Where(type => typeof(T).IsAssignableFrom(type)).ToList();
}

Comment: Thanks and thank you to all those that pointed that out in their comments.


How do I connect with my friend that also has shaders?

Question: I have Sildur's Shaders for 1.8 the same with my friend, we also have the same Forge version same Optifine version too, How can he connect to me or me to him while having Shaders?
When we try to connect to each other using LAN (Open To Lan)
The message: "Failed to login: Access Token can not be null or empty"
We can't make a Server though
Comment: Why couldn't you use a server?
Answer: This isn't a problem with the shaders mods you have. The error "Failed to login: Access Token can not be null or empty" is an error indicating that the way you logged in to minecraft bugged out.
If the person getting that error is still logging in with their username instead of a new style account they can need to go to Mojangs account migration page and migrate to a new style account (where you log in with your email address).
If that isn't it they should try to log out and log back in again, that might fix it (it's a bit of a vague error according to my research).
Also note: I'm not 100% sure but you might get this error if you are both logging in with the same account information, you will need 2 separate Minecraft accounts.
Comment: @Dudamesh Just so that you know, we do not offer help, if the problem is piracy spesific or if the game is admittingly pirated.
Comment: I cannot do that BECAUSE I am NOT using Official Minecraft, nor am I using Cracked Launchers.


What is causing my logs to flood with low-speed USB device notices?

Question: I have a box running Ubuntu 14.04 with all patches installed. Suddenly about a week ago my logs started getting flooded with hundreds of messages a minute that look like the following:
<code>Jun 18 11:28:49 Serv kernel: [778682.205315] usb 2-1.5: new low-speed USB device number 24 using ehci-pci
Jun 18 11:28:49 Serv kernel: [778682.461172] usb 2-1.5: new low-speed USB device number 25 using ehci-pci
Jun 18 11:28:49 Serv kernel: [778682.717029] usb 2-1.5: new low-speed USB device number 26 using ehci-pci
Jun 18 11:28:50 Serv kernel: [778682.972886] usb 2-1.5: new low-speed USB device number 27 using ehci-pci
Jun 18 11:28:50 Serv kernel: [778683.228750] usb 2-1.5: new low-speed USB device number 28 using ehci-pci
Jun 18 11:28:50 Serv kernel: [778683.484602] usb 2-1.5: new low-speed USB device number 29 using ehci-pci
Jun 18 11:28:51 Serv kernel: [778683.740444] usb 2-1.5: new low-speed USB device number 30 using ehci-pci
Jun 18 11:28:51 Serv kernel: [778683.996318] usb 2-1.5: new low-speed USB device number 31 using ehci-pci
Jun 18 11:28:51 Serv kernel: [778684.252176] usb 2-1.5: new low-speed USB device number 32 using ehci-pci
Jun 18 11:28:51 Serv kernel: [778684.508035] usb 2-1.5: new low-speed USB device number 33 using
</code>
These will start being numbered at 1, usually stop between 100-150, will pause for about 10 seconds and then start all over again. I have made no changes to this system other than installing updates, none of which sparked any interest (apache, php, teamviewer, etc) with the exception of a kernel upgrade. I see no other errors in my logs that would be relevant. I did notice though that the mouse works only on the sidebar, but you cannot click anything on the desktop or any windowed program so I have to navigate with my keyboard. I have tried a new mouse and have the same issue. Does anyone know where I can start to look here? My syslog server is being flooded and parsing logs is nearly impossible now.
Comment: Did you try using another USB port for the mouse?
Comment: What does `uname -a` says?
Comment: Some other USB device is causing your problem. Unplug ALL USB devices except for the mouse. Reboot. Retest.
Comment: @ubfan1: Yes, I tried another port but it didnt make a difference. The messages above kept coming full speed even when it was completely unplugged.
Comment: @Hi-Angel: Linux Serv 3.13.0-119-generic #166-Ubuntu SMP Wed May 3 12:18:55 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

heynnema: I am not on location right now, as soon as I get back tonight I will give that a try. There should only be one other device --an external HDD. Maybe that is it!
Comment: Alright, since as you said the problem appeared after kernel update, try installing `linux-generic-lts-xenial` which is 4.4 kernel, reboot, and check if it helps.
Answer: Alright, so this took a lot of troubleshooting, and I am not sure how this is possible but it was in fact causing the issue.
I unplugged all of the devices I could think of and the messages were coming yet. I thought guiverc may have been correct regarding a controller failure as the messages kept coming even after all USB devices were removed. This is usually a headless box and RDP wasn't playing nicely with resolution (max 640x480), so I bought an HDMI display emulator.
https://www.amazon.com/gp/product/B06XT1Z9TF
This device seems to have failed and somehow appeared to the server that it was a monitor which supported CEC. The server was trying to wake up the monitor repeatedly when I was using the system over RDP. I noticed that verbose logging was only happening when I was actively on the server, logs would stop about 5 minutes after I would disconnect.
My solution was to swap out the emulation device and the new one is working perfectly. I was also able to go into the BIOS and turn off CEC support which also fixed the issue, but the resolution over RDP was wonky due to the device failure.
Answer: I've seen this before on two 'older' boxes, the first box had all-usbs cease working ~two months after issue started, the second was still going when I left the organization.
I'd take it as a possible sign of a failing part. Low-speed is usually keyboard or mouse; maybe an "iffy" electrical connection is causing disconnect-reconnect and resultant message, but both boxes I saw it on had the message continue with all usb devices removed.
I realize this is all CONJECTURE, but I'd take it as a sign of a possible-hardware failure coming.  (I can't comment; hence comment as answer)

ps: I created a dirty .pl script to just delete those lines from the logs I had to watch...
Comment: I thought you were correct with a controller hardware failure of the controller, but I found the solution and have posted it below. Thank you for the advice!


Sequelize returns _previousDataValues, _options, options, and all kinds of other junk

Question: If I run a simple query like the following, I get an object with all this extra junk ( _previousDataValues, _options, options, etc). How do I disable this meta data and return only the actual dataValues? I can't find anything in the spotty documentation.
models.Product.findAll({
  attributes: ["id", "name"]
})

Answer: All this 'junk' is used by sequelize to do the fancy stuff that ORMs do: keep change of changed values etc. etc...
They will be removed automagically when you serialize the instances to JSON, or you might do so manually using .get({ plain: true }) or .toJSON()
Comment: `.get({ plain: true })` is the correct answer. But it's worth noting that you should probably put off calling it for as long as possible: the "plain" version is not a model instance, and therefore does not provide any of the ORM sugar that attracted you to sequelize in the first place.
Answer: You can also use {raw: true} like this:
const users = await User.findAll({raw: true})

Answer: models.Product.findAll({
    attributes: ["id", "name"]
}).then(function(produts) {
     // only products here
})

Comment: Molda, thanks for your response but this still returns all the extra parameters (_previousDataValues, __options, etc).
Comment: Do you mean that the products objects have properties like _previousDataValues and __options. So it looks like products = [{id: 654,_previousDataValues: },{id: 987,_previousDataValues: }]
Answer: In my case, I used ".toJSON()", and it worked.


How to determine number of solutions modular

Question: Is there a formula for determine the number of solutions (#S) to $x^{3}=1$ mod $(mn)$ where $n \neq m$ are both prime ( ie in the ring $\mathbb{Z}/mn\mathbb{Z}$)
I think from the Chinese remainder theorem it would tell us that the number of solutions would be the product of the number of solutions in $m$ and in $n$.  So would there be a limit of the number of solutions? I guess the most solutions one could have for n or m individually would be 3, so would the most solutions in the whole ring just be 9?
Answer: A ring $\mathbb Z_p$ is a field, if $p$ is prime. A polynomial of degree $n$ has at most $n$ roots in such a field. So, the equation $x^3=1$ has at most $3$ solutions in $\mathbb Z_m$ and at most $3$ solutions in $\mathbb Z_n$. So, you correctly assumed that the maximum number of solutions modulo $mn$ is $9$ due to the chinese remainder theorem.
Answer: Your reasoning about the Chinese remainder theorem is not only correct, it also implies that one should investigate the number of cubic roots of unity in the finite field $\mathbb Z_p$. According to this article
https://mathoverflow.net/questions/58357/number-of-n-th-roots-of-unity-over-finite-fields
the answer is 3 if $p-1$ is divisible by 3 and 1 otherwise. The smallest prime with 3 solutions is $p=7$: $\{\overline 1, \overline 2, \overline 4\}.$


Cannot convert Double to expected argument type CGFloat

Question: How do i convert this function to swift? I'm getting an error I do not understand. You'll need "import QuartzCore" in your class.
Objective C Code
void DrawGridlines(CGContextRef context, CGFloat x, CGFloat width)
{
    for (CGFloat y = -48.5; y <= 48.5; y += 16.0)
    {
        CGContextMoveToPoint(context, x, y);
        CGContextAddLineToPoint(context, x + width, y);
    }
    CGContextSetStrokeColorWithColor(context, graphLineColor());
    CGContextStrokePath(context);
}

Swift Code
func DrawGridLines(context:CGContextRef, x:CGFloat, width:CGFloat)
{
    for var y = -48.5; y <= 48.5; y += 16.0
    {
        CGContextMoveToPoint(context, x, y);
        CGContextAddLineToPoint(context, x + width, y);
    }
    //CGContextSetStrokeColorWithColor(context, graphLineColor());
    //CGContextStrokePath(context);
}

Comment: I'm unclear on the problem.  Is the title your error text?  Did you get the error on the first line of your loop?
Answer: Swift is very strict with variable types.  Since you didn't give y a type, Swift inferred that it was a Double.
Variable y needs to be a CGFloat because the function prototype that it is passed to is func CGContextMoveToPoint(c: CGContext?, _ x: CGFloat, _ y: CGFloat).  You can declare the type inline in the for statement:
for var y:CGFloat = -48.5; y <= 48.5; y += 16.0

Answer: In my case I had to cast the Double value as CGFloat and the error went away.
let newCGFloatVal = cgFloatVal * CGFloat(doubleVal)


C# - Running a SSIS on a SQL Server from a wpf Application

Question: I cannot seem to find any useful documentation for the specific situation i need. I am trying to Launch and pass variables into an SSIS package that is deployed on a sql server.
In management studio the package can be found under Integration Services Catalog\SSISDB\IhsDataSync\Projects\LoadHeader\Packages\Package.dtsx. From the sources I have found it appears that I need to use the Microsoft.SqlServer.Dts.Runtime;assembly. When I go to write the rest of the code is where i am having thousands of questions.
So far I have:
            try
        {
            Application app = new Application();
            Package package = null;

            package = app.LoadFromSqlServer("SSISDB\IhsDataSync\Projects\LoadHeader\Packages\Package.dtsx","servername","username","password",IDTSEvents);
        }
        catch
        {

        }

Most examples only show how to load a local package in which case the first method parameter is quite obvious. What is the path for using a package on the sql server?
What is the last parameter of LoadFromSqlServer()--> IDTSEvents???
How do I inject variables?
Answer: Can you call dtexec from a shell?
If you use this approach you lose the exception hooks you get with the pure programmatic approach  but passing values into ssis variables is as easy as /SET
You can still interrogate the return code for success.
It might do as a workaround.
Answer: I gather that the primary question you are asking is how you can assign values to Variables before execution? If so, you can use the respective DtsContainer (or its child) object to access the variables and then assign the value to a specific variable.
Let us say you have variable with the name "ABC" in the namespace "User" on the package itself. You can do this:
package = app.LoadFromSqlServer("SSISDB\IhsDataSync\Projects\LoadHeader\Packages\Package.dtsx","servername","username","password", idtsEvents);
package.Variables["User::ABC"].Value = <value of approproate type>

If your variable is associated to a child container or task, then you can obtain a reference to that sepcific container/task and then access the Variables property like the above example.
The last param of the LoadFromSqlServer is for you to access Events that can happen as part of the Load call.


volume and mute buttons not working on Ubuntu

Question: It has been days since my volume buttons and the mute button work correctly. I have been trying everything related to pulse audio that could have caused this. Reinstalling, resetting my volume and mute keys, and doing an alsa force reload but nothing works.
Comment: Thank you for your suggestion, I have made the change
Comment: Please write it in question/answer format. [Edit](https://askubuntu.com/posts/1435784/edit) the question as a "question", and post the solution as an answer
Answer: I was messing around with the audio system and had installed various packages to play the audio. I had installed so many that I lost track of them. after a few days, I noticed my audio buttons would not respond. I started to think what are the packages that may have caused this issue. I noticed I had pulse audio installed and so I tried reinstalling it safely by following a proper guideline this time but nothing seemed to work when I had almost given up I thought, wait! I should try tracing back the list of packages I downloaded I used the following code for it ...
grep " install " /var/log/dpkg.log
after this step, I noticed that I had pipewire-pulse which actually caused the issue (I googled and learned a few things). The following are the codes I used to resolve
sudo touch /usr/share/pipewire/media-session.d/with-pulseaudio
systemctl --user restart pipewire-session-manager
and it worked!
Ps: this post is for me when I find myself stuck in the future but if it helps somebody I would love that :)
Comment: Do you have a "/usr/share/pipewire/pipewire-pulse.conf" file? It should take care of the pulse/pipewire connection. Else this looks like bug which you might report on launchpad..


Error: Not detached model found

Question: I am getting the following error while working with Wicket 6.19:
    Caused by: org.apache.wicket.core.util.objects.checker.CheckingObjectOutputStream$ObjectCheckException: Not detached model found!
A problem occurred while checking object with type: com.test.web.components.CurrentUserModel
Field hierarchy is:
   [class=com.test.web.base.pages.HomePage, path=0]
    private java.lang.Object org.apache.wicket.MarkupContainer.children [class=[Ljava.lang.Object;]
      java.lang.Object org.apache.wicket.Component.data[1] [class=com.test.web.HeaderPanel, path=0:headerPanel]
        private java.lang.Object org.apache.wicket.MarkupContainer.children [class=[Ljava.lang.Object;]
          private java.lang.String org.apache.wicket.markup.html.image.resource.LocalizedImageResource.variation[2] [class=com.test.web.LoginStatusPanel, path=0:headerPanel:loginStatusPanel]
            java.lang.Object org.apache.wicket.Component.data [class=com.test.web.components.CurrentUserModel] <----- field that is causing the problem

Code:
@RequireHttps
public class HomePage extends WebPage {
    private HeaderPanel headerPanel;
    private LoginStatusPanel loginStatusPanel;
    private MenuPanel menuPanel;

    public HomePage(String id) {
        super();
        initialize();
    }

    public HomePage(String id, PageParameters parameters) {
        super(parameters);
        initialize();
    }

    @Override
    protected void onInitialize() {
        Request request = RequestCycle.get().getRequest();
        if (request instanceof ServletWebRequest)
        {
            ServletWebRequest wr = (ServletWebRequest) request;
            HttpSession session = wr.getContainerRequest().getSession();
            if (session != null) {
            }
        }
        super.onInitialize();
    }

    public String getApplicationId(){
        return applicationId;
    }

    private void initialize() {
        add(headerPanel = new HeaderPanel("headerPanel"));
        headerPanel.add(loginStatusPanel = new LoginStatusPanel("loginStatusPanel"));
        headerPanel.add(menuPanel = new MenuPanel("menuPanel"));
    }
}

public class HeaderPanel extends Panel {
    private Label headerTitleLbl;

    public HeaderPanel(String id) {
        super(id);
        add(headerTitleLbl=new Label("headerTitle", WebApplication.getAppTitle()));
        headerTitleLbl.setOutputMarkupId(true);
    }
}

public class LoginStatusPanel extends Panel {

    public LoginStatusPanel(String id) {
        super(id, new CurrentUserModel()); // Line 1
    }

    protected void onInitialize() {
        IModel<Authentication> authModel = (IModel<Authentication>) getDefaultModel();
        final Authentication auth = authModel.getObject();

        if (auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken))
        {
            Fragment fragment = new Fragment("frag", "loggedInFragment", this);
            Label status;
            fragment.add(status = new Label("status", "Logged in as "));
            fragment.add(new Label("userId", new PropertyModel<String>(authModel, "name")));
            add(fragment);
        }
        else
        {
            Fragment fragment = new Fragment("frag", "loggedOutFragment", this);
            fragment.add(new Label("status", "Logged out"));
            fragment.add(new ExternalLink("login", "/LoginPage", "Log In"));
            add(fragment);
        }
        super.onInitialize();
    }
}

public class MenuPanel extends Panel {
    public MenuPanel(String id) {
        super(id);
        add(new MenuPanel("menu", WebApplication.getMenuList()));
    }
}

public class CurrentUserModel extends LoadableDetachableModel<Authentication> {
    protected Authentication load() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}

Note: If I update the code in comment marked as 'Line 1' with the following:
super(id, new Model(SecurityContextHolder.getContext().getAuthentication()));

The error doesn't show up, that might be because its not a LoadableDetachableModel.
Is it possible to pass an instance of LoadableDetachableModel to Component class constructor?
I am getting the same error for the following code as well:
tree = new NestedTree<TreeItem>("tree", provider, state);

Where state is an instance of the following class:
private class TreeItemExpansionModel extends LoadableDetachableModel<Set<TreeItem>>
{
    private static final long serialVersionUID = 1L;
    private final String treePanelId;

    public TreeItemExpansionModel(String treePanelId) {
        this.treePanelId = treePanelId;
    }

    @Override
    protected Set<TreeItem> load() {
        return TreeItemExpansion.get(treePanelId);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof TreeItemExpansionModel) {
            return ((TreeItemExpansionModel) obj).treePanelId.equals(treePanelId);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return treePanelId.hashCode();
    }
}

And the error is as follows:
Caused by: org.apache.wicket.core.util.objects.checker.CheckingObjectOutputStream$ObjectCheckException: Not detached model found!
A problem occurred while checking object with type: com.test.web.components.TreeItemProvider$TreeItemModel
Field hierarchy is:
   [class=com.test.web.admin.pages.HomePage, path=0]
    private java.lang.Object org.apache.wicket.MarkupContainer.children [class=[Ljava.lang.Object;]
      java.util.List com.test.web.components.WhistlePanel.selectionList[2] [class=com.test.web.NavPanel, path=0:navPanel]
        private java.lang.Object org.apache.wicket.MarkupContainer.children [class=org.apache.wicket.extensions.markup.html.repeater.tree.NestedTree, path=0:navPanel:tree]
          private java.lang.Object org.apache.wicket.MarkupContainer.children [class=org.apache.wicket.extensions.markup.html.repeater.tree.nested.Subtree, path=0:navPanel:tree:subtree]
            private java.lang.Object org.apache.wicket.MarkupContainer.children [class=org.apache.wicket.markup.repeater.RefreshingView, path=0:navPanel:tree:subtree:branches]
              private java.lang.Object org.apache.wicket.MarkupContainer.children [class=[Ljava.lang.Object;]
                private java.lang.Object org.apache.wicket.MarkupContainer.children[0] [class=org.apache.wicket.extensions.markup.html.repeater.tree.nested.BranchItem, path=0:navPanel:tree:subtree:branches:1]
                  java.lang.Object org.apache.wicket.Component.data [class=com.test.web.components.TreeItemProvider$TreeItemModel] <----- field that is causing the problem

Thanks in advance.
Comment: I cannot spot the cause of the problem in the code you've posted, but the error message is clear: You're keeping an instance of CurrentUserModel in your component tree, which does not get detached, i.e. it is not the default model of the owning component.
Comment: @svenmeier Thanks for your reply, I have updated my question with additional info.
Answer: The problem is the combination of the Serialization checker and your managing of the lifecycle of models.
When you put a LoadableDetachableModel and you initialize the model that is NOT Serializable, Wicket checker throws an exception that you try to serialize data that is not Serializable. That behavior is correct.
The reason why it happen is

Authentication is not Serializable
You call getDefaultModel().get() that loads the model object even though it's a lazy loading model

See the NotDetachedModelChecker https://github.com/apache/wicket/blob/build/wicket-6.20.0/wicket-core/src/main/java/org/apache/wicket/core/util/objects/checker/NotDetachedModelChecker.java
Suggested Fix:
I. Use AbstractReadOnlyModel instead of LoadableDetachableModel
    public class CurrentUserModel extends AbstractReadOnlyModel<Authentication> {
       protected Authentication getObject() {
          return SecurityContextHolder.getContext().getAuthentication();
       }
    }

If you really need to keep the value (I think it is not required, because the Spring authentication context returs ever the same value at each attempt), wrapper the LoadableDetachbleModel with AbstractReadOnlyModel.
II. Detach the model: call authModel.detach(); before you return flow control back to Wicket
protected void onInitialize() {
    IModel<Authentication> authModel = (IModel<Authentication>) getDefaultModel();
    final Authentication auth = authModel.getObject();

    if (auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken))
    {
        Fragment fragment = new Fragment("frag", "loggedInFragment", this);
        Label status;
        fragment.add(status = new Label("status", "Logged in as "));
        fragment.add(new Label("userId", new PropertyModel<String>(authModel, "name")));
        add(fragment);
    }
    else
    {
        Fragment fragment = new Fragment("frag", "loggedOutFragment", this);
        fragment.add(new Label("status", "Logged out"));
        fragment.add(new ExternalLink("login", "/LoginPage", "Log In"));
        add(fragment);
    }
    authModel.detach();
    super.onInitialize();
}

Answer: I know that the information I have provided myself here is incomplete for anyone to give a proper solution.
I have posted the same query in another forum and got the solution. So I thought of share that link here so that it may be useful for people who visit this page.
Thanks

Error: Not detached model found


using TypeScript and Sails.js is giving issues, TypeError: object is not a function

Question: Converted my Sails.js app to using TypeScript and when I try to hit my previous routes I'm getting errors around "TypeError: object is not a function".
I created a controller using a Class and re-wrote my functions in TypeScript.  At the end I instantiated my new controller doing
var controller = new TestController();
export = controller;

I'm not understanding what I did wrong here.  I referenced the work done on http://alexclavelle.blogspot.com/2015/03/using-sailsjs-with-typescript.html?showComment=1435617822375
Still nothing...I'm guessing it is something with the es5 code that gets generated.
Answer: Based on:
var controller = new TestController();
export = controller;

the runtime cannot do controller().
Fix:
var controller = () => new TestController();
export = controller;

Comment: I think this got me farther...though now my routes are all messed up.  All of my routes are giving this error in console on sails.js/node.js startup

    error: Ignored attempt to bind route (/) to unknown controller.action :: index.findthis