Removing horizontal scroll bar when there is zoom out done through transform scale

Question: You can observe there is a scrollbar when you run the below code when the html is scale down to 50% and increased width to fit in the window. This is not hapenning in firefox and only in chrome.
https://codepen.io/rohinikumar4073/pen/qBJbLqp
The content DOM  can be changed and not in my control. Hiding the scroll bar using overflow-x:hidden can cause to hide if there is actual need for the scrollbar. This can happen if the content DOM exceeds 100% width;

html {
  transform: scale(0.5);
  transform-origin: left top;
  width: 200%;
  height: 50%;
}

.parent {

  background: yellow;
}

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta fermentum leo ut rutrum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras nibh augue, viverra ut purus id, aliquet hendrerit dui. Class
  aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque suscipit feugiat neque, nec convallis felis viverra sed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras pulvinar pulvinar arcu id iaculis. Vestibulum
  ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Donec faucibus imperdiet leo, tincidunt consectetur ante. Donec accumsan mauris vitae velit lacinia molestie. Nunc quis porttitor odio. Aenean sit amet nisl sem. Etiam ultricies
  arcu ut orci condimentum tempus. Aliquam eget purus nulla. Nullam elementum neque ut elit consequat varius. Cras facilisis faucibus diam, ac venenatis augue porttitor laoreet. Donec tincidunt arcu vel porttitor consequat. Vestibulum molestie urna id
  ipsum molestie suscipit. Aenean id finibus ex, venenatis sagittis ipsum. Cras id nibh pretium, dictum justo vehicula, pellentesque nunc. In rutrum, tellus at posuere bibendum, eros sapien pellentesque nisi, eu blandit mi nisi a mi. Quisque vitae nunc
  sed quam varius tincidunt id eget libero. Nunc id risus eget nisi molestie fringilla sit amet eget elit. Duis nec dolor porta massa elementum finibus a et nunc. In a augue vitae orci tempor placerat. Suspendisse at tempor metus, pharetra sodales arcu.
  Cras placerat facilisis odio vitae condimentum. Aenean sodales dapibus fermentum. Donec sem sapien, finibus vel ultrices vitae, finibus fermentum velit. Fusce ante massa, pulvinar sed blandit tempus, rhoncus at justo. Fusce varius justo sed arcu malesuada,
  vitae aliquet felis gravida. Integer sit amet dolor vitae libero blandit hendrerit. Mauris rutrum erat nec molestie tincidunt. Sed libero diam, blandit eu nisl at, sollicitudin pellentesque nunc. Quisque ac laoreet nisi. Vestibulum eu posuere odio,
  iaculis scelerisque quam. Morbi facilisis tellus non pulvinar faucibus. Nulla fringilla, velit nec feugiat fringilla, turpis sem pretium lectus, nec auctor arcu nisl ut felis. Cras eleifend efficitur commodo. In elit est, semper ut mauris non, dignissim
  suscipit ex. Sed sodales ac ex a consectetur. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur eget diam at nisl luctus tempus pellentesque ut nulla.

Comment: why do you set `height: 100px;`
Comment: Removed height it is set arbitrarily
Answer: I agree with Jahangeer. Overflow-x is a good option. Although, I wanted to try it without using an overflow property. You will need to set scaling on the .parent div and then set the body element to a flex object while using positioning. Note that Firefox needs the flex object to display properly and Chrome doesn't (see fiddle).

html {
  position: relative;
  min-height: 100%;
  width: 100%;
  background-color: white;
}
body {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: red;
  display: flex;
  flex-direction: column;
}
.parent {
  background-color: yellow;
  transform: scale(0.5);
  transform-origin: left top;
  width: 200%;
}
.parent::after {
  background-color: white;
  content: "";
  display: block;
  height: 1rem;
  width: 100%;
}

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta fermentum leo ut rutrum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras nibh augue, viverra ut purus id, aliquet hendrerit dui. Class
  aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque suscipit feugiat neque, nec convallis felis viverra sed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras pulvinar pulvinar arcu id iaculis. Vestibulum
  ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Donec faucibus imperdiet leo, tincidunt consectetur ante. Donec accumsan mauris vitae velit lacinia molestie. Nunc quis porttitor odio. Aenean sit amet nisl sem. Etiam ultricies
  arcu ut orci condimentum tempus. Aliquam eget purus nulla. Nullam elementum neque ut elit consequat varius. Cras facilisis faucibus diam, ac venenatis augue porttitor laoreet. Donec tincidunt arcu vel porttitor consequat. Vestibulum molestie urna id
  ipsum molestie suscipit. Aenean id finibus ex, venenatis sagittis ipsum. Cras id nibh pretium, dictum justo vehicula, pellentesque nunc. In rutrum, tellus at posuere bibendum, eros sapien pellentesque nisi, eu blandit mi nisi a mi. Quisque vitae nunc
  sed quam varius tincidunt id eget libero. Nunc id risus eget nisi molestie fringilla sit amet eget elit. Duis nec dolor porta massa elementum finibus a et nunc. In a augue vitae orci tempor placerat. Suspendisse at tempor metus, pharetra sodales arcu.
  Cras placerat facilisis odio vitae condimentum. Aenean sodales dapibus fermentum. Donec sem sapien, finibus vel ultrices vitae, finibus fermentum velit. Fusce ante massa, pulvinar sed blandit tempus, rhoncus at justo. Fusce varius justo sed arcu malesuada,
  vitae aliquet felis gravida. Integer sit amet dolor vitae libero blandit hendrerit. Mauris rutrum erat nec molestie tincidunt. Sed libero diam, blandit eu nisl at, sollicitudin pellentesque nunc. Quisque ac laoreet nisi. Vestibulum eu posuere odio,
  iaculis scelerisque quam. Morbi facilisis tellus non pulvinar faucibus. Nulla fringilla, velit nec feugiat fringilla, turpis sem pretium lectus, nec auctor arcu nisl ut felis. Cras eleifend efficitur commodo. In elit est, semper ut mauris non, dignissim
  suscipit ex. Sed sodales ac ex a consectetur. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur eget diam at nisl luctus tempus pellentesque ut nulla.

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta fermentum leo ut rutrum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras nibh augue, viverra ut purus id, aliquet hendrerit dui. Class
  aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque suscipit feugiat neque, nec convallis felis viverra sed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras pulvinar pulvinar arcu id iaculis. Vestibulum
  ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Donec faucibus imperdiet leo, tincidunt consectetur ante. Donec accumsan mauris vitae velit lacinia molestie. Nunc quis porttitor odio. Aenean sit amet nisl sem. Etiam ultricies
  arcu ut orci condimentum tempus. Aliquam eget purus nulla. Nullam elementum neque ut elit consequat varius. Cras facilisis faucibus diam, ac venenatis augue porttitor laoreet. Donec tincidunt arcu vel porttitor consequat. Vestibulum molestie urna id
  ipsum molestie suscipit. Aenean id finibus ex, venenatis sagittis ipsum. Cras id nibh pretium, dictum justo vehicula, pellentesque nunc. In rutrum, tellus at posuere bibendum, eros sapien pellentesque nisi, eu blandit mi nisi a mi. Quisque vitae nunc
  sed quam varius tincidunt id eget libero. Nunc id risus eget nisi molestie fringilla sit amet eget elit. Duis nec dolor porta massa elementum finibus a et nunc. In a augue vitae orci tempor placerat. Suspendisse at tempor metus, pharetra sodales arcu.
  Cras placerat facilisis odio vitae condimentum. Aenean sodales dapibus fermentum. Donec sem sapien, finibus vel ultrices vitae, finibus fermentum velit. Fusce ante massa, pulvinar sed blandit tempus, rhoncus at justo. Fusce varius justo sed arcu malesuada,
  vitae aliquet felis gravida. Integer sit amet dolor vitae libero blandit hendrerit. Mauris rutrum erat nec molestie tincidunt. Sed libero diam, blandit eu nisl at, sollicitudin pellentesque nunc. Quisque ac laoreet nisi. Vestibulum eu posuere odio,
  iaculis scelerisque quam. Morbi facilisis tellus non pulvinar faucibus. Nulla fringilla, velit nec feugiat fringilla, turpis sem pretium lectus, nec auctor arcu nisl ut felis. Cras eleifend efficitur commodo. In elit est, semper ut mauris non, dignissim
  suscipit ex. Sed sodales ac ex a consectetur. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur eget diam at nisl luctus tempus pellentesque ut nulla.

Fiddle:
https://jsfiddle.net/pLhadzvr/
Comment: I am not able understand why does we need flex ?
Comment: Firefox displays empty space below the .parent div, essentially doubling the page height. Adding a flex object with a direction of column will prevent the extra white space at the bottom. Chrome renders it fine without flex, but it doesn't hurt to keep it in there.
Answer: When zooming out using the transform: scale() CSS property, if the content of an element becomes too wide for its container, a horizontal scroll bar may appear. To prevent this, you can apply the following CSS to the container element:
enter code here.container {

overflow-x: hidden;
}
This will hide the horizontal scroll bar and prevent the user from scrolling horizontally when zoomed out.
Alternatively, you could also set the min-width property of the container element to a value that is equal to or greater than the width of the content after it has been zoomed out. This would ensure that the container element is always wide enough to fit the content, even when it is zoomed out. However, this approach may not be practical in all cases, as the width of the content may vary depending on the viewport size and other factors
Answer: When using the CSS transform property on the html element, you can also add overflow: hidden to the html element to hide the scrollbar in Chrome:

html {
transform: scale(0.5);
    transform-origin: left top;
    width: 200%;
    height: 50%;
    overflow:hidden;
}
.parent{
/*   overflow:auto; */
/*   height:100px; */
  font-size: 25px;
  background:yellow;

}

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc porta fermentum leo ut rutrum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras nibh augue, viverra ut purus id, aliquet hendrerit dui. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque suscipit feugiat neque, nec convallis felis viverra sed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras pulvinar pulvinar arcu id iaculis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Donec faucibus imperdiet leo, tincidunt consectetur ante. Donec accumsan mauris vitae velit lacinia molestie. Nunc quis porttitor odio.

Aenean sit amet nisl sem. Etiam ultricies arcu ut orci condimentum tempus. Aliquam eget purus nulla. Nullam elementum neque ut elit consequat varius. Cras facilisis faucibus diam, ac venenatis augue porttitor laoreet. Donec tincidunt arcu vel porttitor consequat. Vestibulum molestie urna id ipsum molestie suscipit.

Aenean id finibus ex, venenatis sagittis ipsum. Cras id nibh pretium, dictum justo vehicula, pellentesque nunc. In rutrum, tellus at posuere bibendum, eros sapien pellentesque nisi, eu blandit mi nisi a mi. Quisque vitae nunc sed quam varius tincidunt id eget libero. Nunc id risus eget nisi molestie fringilla sit amet eget elit. Duis nec dolor porta massa elementum finibus a et nunc. In a augue vitae orci tempor placerat. Suspendisse at tempor metus, pharetra sodales arcu. Cras placerat facilisis odio vitae condimentum. Aenean sodales dapibus fermentum.

Donec sem sapien, finibus vel ultrices vitae, finibus fermentum velit. Fusce ante massa, pulvinar sed blandit tempus, rhoncus at justo. Fusce varius justo sed arcu malesuada, vitae aliquet felis gravida. Integer sit amet dolor vitae libero blandit hendrerit. Mauris rutrum erat nec molestie tincidunt. Sed libero diam, blandit eu nisl at, sollicitudin pellentesque nunc. Quisque ac laoreet nisi. Vestibulum eu posuere odio, iaculis scelerisque quam.

Morbi facilisis tellus non pulvinar faucibus. Nulla fringilla, velit nec feugiat fringilla, turpis sem pretium lectus, nec auctor arcu nisl ut felis. Cras eleifend efficitur commodo. In elit est, semper ut mauris non, dignissim suscipit ex. Sed sodales ac ex a consectetur. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Curabitur eget diam at nisl luctus tempus pellentesque ut nulla.

This prevents the scrollbar from appearing even if the content overflows due to scaling. Make sure that all of your content fits within the scaled-down viewport, as this may hide any content that overflows the viewport.
Comment: Yeah I don't have control over the width of the content that is shown and as you mentioned it might hide the scrollbars in case where there are scrollbars.
Comment: sir, as shown in your snippet code the scroll bar is displayed on the main container(HTML element), for that hidden property has to be given there only.


Ubuntu symbolic link going to source location when up folder

Question: The problem is the following - I`ve created a symbolic link to a folder /home/user1/folder1 in /home/user2/. When user2 follows this link, he comes to the /home/user1/folder1, but when he goes up folder he comes to /home/user1/ not /home/user2/. Is it possible to change this behavior?
Comment: I don't think so. Hardlinking a folder with `ln -d` or `ln -F` is not permitted on Ubuntu, even for sudo. There is a discussion about this [here](http://www.linuxforums.org/forum/newbie/149236-creating-hard-link-directory.html)
Answer: Thanks. Solved by mount --bind


why we use open interval in epsilon delta definition fot domain of function?

Question: In epsilon delta definition of limit we see : "Let f be a function defined on some open interval" .
why we use open interval ?
what happen if we use closed interval in definition ?
thanks a lot.
Comment: Also related: https://math.stackexchange.com/questions/1025226/why-is-an-open-interval-needed-in-this-definition-definition-of-a-limit-of-a-f
Comment: Some topological point of views needed for iit.
Comment: Related, but not $\epsilon-\delta$: https://math.stackexchange.com/questions/1008978/why-open-interval-in-formal-definition-of-limit-at-infinity
Comment: Any subset of $\Bbb R$ will do.
Comment: For classical definition - each point of open interval contain some delta neighborhood, while this is not so for closed one. In general limit case we have  neighborhoods with respect to domain i.e. intersection.
Comment: To talk about the limit in a point $a$ the variable $x$ need some space around $a$ to move to $a$. That's why we consider an open interval.
Comment: If you want someone to completely explain a definition, you should give the entire definition, not just a fragment of it. But it seems likely that this question is really the same as [why we require ƒ(x) be defined on an open interval about $x_0$?](https://math.stackexchange.com/q/1423728/139123) At least one answer to that question is: $f$ does **not** need to be defined only on an open interval for a good definition of a limit, but if you allow $f$ to have a different domain you will have a more complicated definition.
Answer: Here is an example of the difference. I assume you are referring to the definition

Let $f$ be defined on some open interval $(a,b)$ and $x_0 \in (a,b)$. Then $$\lim_{x \to x_0} f(x) = L$$ if and only if for every $\epsilon > 0$, there exists some $\delta > 0$ such that if $x \in (a,b)$ and $0<|x - x_0|<\delta$, then $|f(x) - L| < \epsilon$.

The requirement that $x \in (a,b)$ is needed because if $\delta$ is large enough, $|x - x_0| < \delta$ may include $x$ not in $(a,b)$, and therefore potentially for which $f(x)$ is not defined.
You are asking about changing it to

Let $f$ be defined on some closed interval $[a,b]$ and $x_0 \in [a,b]$. Then $$\lim_{x \to x_0} f(x) = L$$ if and only if for every $\epsilon > 0$, there exists some $\delta > 0$ such that if $x \in [a,b]$ and $0<|x - x_0|<\delta$, then $|f(x) - L| < \epsilon$.

Note that saying "$f$ is defined on an interval" does not preclude $f$ also being defined outside that interval. It may be defined, or it may not. Consider the Heaviside function
$$H(x) = \begin{cases}0&x < 0\\1&0 \le x\end{cases}.$$
This is defined on each of the intervals $(-1,1)$, $[-1,1]$, and $[0,1]$, and $x_0 = 0$ is a point in both intervals.

Using the open interval definition with $(-1,1)$ and $\epsilon <
   \frac 12$, we see that there is no $\delta$ that works. The limit of
$H(x)$ as $x \to 0$ does not converge.
Using the closed interval definition with $[-1,1]$ and $\epsilon <
   \frac 12$, we see again that there is no $\delta$ that works. The
limit does not converge.
But using the closed interval definition with $[0,1]$, and any
$\epsilon > 0$, just the requirement $x \in [0,1]$ is enough to ensure $|H(x) - 1| = 0 < \epsilon$, regardless of what $\delta$ we pick. Thus under this definition, and this particular closed interval, $\lim_{x \to x_0} H(x)$ converges to $1$.

You see the problem? The closed interval definition depends on the particular closed interval chosen. But you can show that the open interval version does not. If $(a,b)$ and $(c,d)$ are two open intervals with $x_0$ in both and $f$ defined on both. Then you will get the same limit behavior if you use $(c,d)$ as the interval as you did using $(a,b)$ as the interval. The limits for the two intervals will converge or diverge together, and if they converge, it will always be to the same value.
Given that the author is defining a two-sided limit here, the assumption that $f$ is defined on an open interval assures that $f$ is defined on both sides of $x_0$, and the values of $f$ on both sides must approach the limit. If you use closed intervals instead, you risk $f$ only approaching the limit on one side of $x_0$, and either not being defined, or doing something completely different on the other side.
Of course, there are also one-sided limits, where you specifically want exactly that. But that is not what is being defined at this time. The authors are starting with the most simple case first, and will define other cases in the future, once two-sided limits have been mastered.
Answer: If a function is defined on a interval that is not open (nor closed) you can get some curious functions that are still continuous.  For example: Let $$ f(x)  = \left\{
        \begin{array}{ll}
            1 & \quad n \textrm{  odd} \\
            2 & \quad \textrm{otherwise}
        \end{array}
    \right. $$
where the domain of $f$ is $ D=\{ \frac{n}{n+1}\}$ for all $n \in \mathbb{N}$.  This function is continuous on $D$ but not continuous on $\overline{D}$ for any value of $f$.  Put another way, continuous functions are better behaved on sets that contain at least some of their limit points, like open sets.


How to handle a great number of exceptions in java?

Question: I have some piece of code. In that there are chances to get many number of exceptions. My doubt is, to handle all those exceptions do i have to write catch blocks for each type of exception. Is it an efficient way or not. Except using throws keyword, If any other solutions are there please suggest me to do that. Any response will be appreciated.
Thanks in advance
Answer: It depends on what kind of exceptions you're trying to catch.  Everything that can be thrown implements Throwable, so you can catch everything with
} catch (Throwable t) {

including run time errors and all.  As Amjad mentions, you can narrow that a little with
} catch (Exception e) {

which just catches Exception and its subtypes.
The problem with both of these is that they catch too much; you can work around that but you risk catching an important problem and then not handling it.
If you have just a few different exceptions, you're probably best off with an exception comb
} catch (Exception1 e) { // do something
} catch (Exception2 e) { // do something else

You have one other option if these are your own exceptions: make a class hierarchy of your own exceptions
class MyExceptions extends Exception { /* ... */ }
class MyExceptionSubtypeA extends MyException { /* ... */ }
class MyExceptionSubtypeASubsub1 extends MyExceptionSubtypeA { /* ... */ }

Now you can pick any subtree of classes, as with
} catch (MyExceptionSubtypeA sa) {

which will catch both MyExceptionSubtypeA and MyExceptionSubtypeASubsub1.
Answer: Use the general kind of exception Exception
try{
//your code here
}
catch(Exception e){
//handle exception
}

However this is unrecommended http://source.android.com/source/code-style.html#exceptionsAll
Comment: I'd like to reiterate that this is unrecommended. How many exceptions do you need to handle?
Comment: This is bad practice. Would recommend against it.
Comment: Ya as I mentioned earlier it is highly unrecommended however it could be useful in development environment.


Project dependency in solution file lets build fail

Question: This repository reproduces a dotnet build issue we're facing.
We have a web application targeting netcoreapp2.1. and a class library targeting both netstandard2.0 and net47.
The web application provides a web API, and we're using NSwag to generate the corresponding C# client.
Therefore the build process must first build the web application, and the class library afterwards.
Because of this required order we have defined a Project Dependency in the solution:

However, while it builds fine in Visual Studio, it fails on the command line:
$ dotnet build dotnetBuildIssue.sln
Microsoft (R) Build Engine version 15.8.166+gd4e8d81a88 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 42.36 ms for C:\work\tmp\dotnetBuildIssue\ClassLib\ClassLib.csproj.
  Restore completed in 63.56 ms for C:\work\tmp\dotnetBuildIssue\WebApp\WebApp.csproj.
  WebApp -> C:\work\tmp\dotnetBuildIssue\WebApp\bin\Debug\netcoreapp2.1\WebApp.dll
C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.app\2.1.1\build\netcoreapp2.1\Microsoft.AspNetCore.App.targets(14,5): error : This version of Microsoft.AspNetCore.App is only compatible with the netcoreapp2.1 target framework. Please target netcoreapp2.1 or choose a version of Microsoft.AspNetCore.App compatible with netstandard2.0. [C:\work\tmp\dotnetBuildIssue\WebApp\WebApp.csproj]
C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.app\2.1.1\build\netcoreapp2.1\Microsoft.AspNetCore.App.targets(14,5): error : This version of Microsoft.AspNetCore.App is only compatible with the netcoreapp2.1 target framework. Please target netcoreapp2.1 or choose a version of Microsoft.AspNetCore.App compatible with net47. [C:\work\tmp\dotnetBuildIssue\WebApp\WebApp.csproj]

Build FAILED.

To me it looks like dotnet uses the class library's TargetFramework net47 to compile the web application, though we only set a project
dependency to enforce a specific build order.
Our real solutions contains more than 15 projects, so adding a build task
for each and every project in the VSTS Azure DevOps build pipeline
is less than optimal.
We would have preferred not having to define the dependency in the solution file, but we haven't found a working way to do it in the .csproj file.
Any hint how to enforce a specific order of the projects without a direct reference (we're targeting different frameworks) is welcome.
I have published a repro at GitHub.
Answer: Actually, some more research revealed that this issue is known and will be fixed in MSBuild 15.9.
A temporary fix is also mentioned in above thread: put a file Directory.Build.props next to your solution file with following content:
<?xml version="1.0" encoding="utf-8"?>
<Project>
  <PropertyGroup>

    <AddSyntheticProjectReferencesForSolutionDependencies>false</AddSyntheticProjectReferencesForSolutionDependencies>
  </PropertyGroup>
</Project>


In-ear monitoring on a budget, what gear should I look at?

Question: I'm playing in a band (drums, bass, guitar, keys + 2 singers), and we are considering putting together an in ear system.
The main problem is small venues, everyone is close to the drummer, and we can't really hear ourselves. Wedges are not always an option, the volume is also not great for our ears. This is the worst for singers as they need to "intonate themselves".
I spent the past few days exploring the options, and I can't really see a good solution without a copious amount of gear (not even just price, but sheer amount of stuff). To understand my frustration with this, I'm the guitarist, for now I go there with a modeller unit and my guitar, hand the output to the sound guy, and I'm set.
My goal is to allow everyone to listen to the mix of instruments they preferr in their monitors.
My understanding is, that to achieve this, we need:

A digital mixer with at least number of musicians + 1 (to front of house) outputs.
1 transmitter for each musician.
1 receiver for each musician.
1 pair of in-ears for each musician.

My question is, is there any way to simplify this? For people who are playing with in-ears, how would you get started with this?
Comment: You say "drums don't really need amplifying" and in some rooms they don't but if you go to in-ears the drums will also need to be miked at least for the purpose of monitoring or you will only be hearing them acoustically and very muffled leaking in through your ear buds.
Comment: You can mic a kit with one good omni
Comment: The main problem could be solved by getting a drummer who can play less loud. It's entirely possible - rutes are quieter than stick s, as a start.But quiet quality drummers are a rare breed. I just hope they keep on breeding... And- one transmitter for drums - asking for extra problems, unless they're electronic, in which case, there's no excuse anyway!
Comment: I assume you as guitarist, don't have a backline, so rely on foldback or simply listen to p.a., but what about everyone else at  the moment? (Including monitor for drums).
Comment: I either just listen directly to the PA or if the sound guy has wedges, I listen to that. Same for keys. The bassist uses an actual amp, which is mic-ed. Drums don't really need amplifying, and singers are in the most trouble :D A quiet drummer would be great but I gave up on that.
Comment: @JohnBelzaguy - very good point - and the drummer will need (want) at least four mics - maybe more! Which compounds what OP wants to do no end. And so will the rest of the band - snare and bass alone won't do.
Comment: @Tetsujin It's amazing, if you put one microphone directly in front of a drum set and listen it sounds exactly like a drum set!
Comment: @JohnBelzaguy very good point, haven't even thought of that lol.
Answer: Disclaimer: I'm an instrumentalist, not an audio engineer; I'm writing from my consumption of sound systems, not experience running them.
Let's agree that the ideal, if you had unlimited funds and unlimited time and space to transport and set up gear, would be in-ear monitoring with a system like Aviom that gives each performer direct individual control of their own mix, with their own personal unit to adjust the level they get of every signal. These are often paired with in-ear monitoring, but as far as I know there's no reason they can't be used with wedges, or that the "old way" can't be used with in-ear.
There are probably many other benefits of this kind of system, but as a performer, the main thing I experienced was "cutting out the middle man." In the days of wedges, I always had to bug the sound guy for "a little more of me... ok, a little more yet... well, maybe that's too much... Oh holy crap the guitarist just showed up late and plugged in and he's incredibly hot, can you pull him way down?... well, I didn't mean all the way out of the mix..." Multiply that times each person on stage, and it makes for a very long sound check, and invariably I'd wind up just shutting up and making do with something less than ideal. This issue, of control, is separate from the issues of in-ear monitoring vs wedges (you can't both get your mic hot enough, hear enough of yourself, and avoid feedback).
Now, as far as I know, there's no reason you couldn't use in-ear monitoring with the "bug the sound guy" model. As long as the mixing board has enough aux sends for everyone, you simply run those to the stage and plug in in-ears where you would have plugged in wedges. (Plus probably some consideration that's beyond my knowledge about accounting for impedance difference.) Price: difference in price between wedges and in-ears. Bulk of gear: reduced since you don't need wedges.
I have a feeling you're looking for even more creative solutions, though. "Get the drummer to play quieter" is good for a laugh. Jokes aside, sometimes this suggestion betrays an ignorance of genre (not looking at you, Tim, more at actual conversations I've had). Someone says "Well I know it's possible for a drummer to play quietly enough for the space and for the rest of the band; I was in a coffeeshop the other day and there was a jazz combo and the drummer was just using brushes, it was so delicate and tasteful!" And doesn't recognize that if you're working in a pop-rock, vaguely Blink-182 context, it's essentially a different instrument, just as much as the coffeshop's upright bass is from the electric.
I've always found that the solution that fits the room and the style best is to fully enclose the drummer in a drum shield—you know, Lexan around the front and sides, padded panels behind and on top. Then the drummer can wale away to their hearts content, the output can be miced, mixed, and balanced perfectly to suit the space, and the monitors can contain as much or as little of the drums as needed. These shields certainly cost something (and might mean buying more mics as well, which at some point might start meaning a mixing board with more channels), and they certainly take up some space and time to lug around and set up, but still less of both than an Aviom system.
Comment: One downside to drum shields, especially with tops, is they can put early reflections into the mikes and affect the sound quality of the drums. For lots of shows, the difference may not be big enough to matter. Just something to bear in mind before going through the trouble.
Comment: IMO there's something inherently wrong with wanting to play stadium rock in a coffee shop. We want to have the cake and eat it too, we're used to technology making everything possible... "making do with something less than ideal" should be the ideal, in my opinion. You're at a small venue, so play small-venue music. This probably doesn't help the OP though.
Comment: @BalázsÉdes: Aviom is (or rather used to be) the gold standard. Nowadays, there are competitors like the Behringer P16 system (or whatever the newer, more powerful one is called), where the entire system costs less than just the Aviom hub alone.
Comment: Thanks for the get-out. Having played with scores of drummers over time, pop/dance/jazz, most couldn't play quietly, so the rest had to come up to their level, which then made them play even harder. Only a handful could get a good balance, and still play in the pocket. I like the plexi-box idea - could they be made airtight - that would of course help keep the sound in too..!
Comment: I like the drum shield idea too. Going to check out the Aviom you mentioned, but you scared me with the price.


Replace content of property files when publishing application in Eclipse

Question: We have an .ear project with several dependent .jar projects and we are using Maven. Each project has its own property file, but the properties inside do not have specific values but placeholders, e.g.
database.url=${database.url}

The placeholder ${database.url} is replaced during Maven build process using the resources plugin. So for each stage (local, test, integration, production) we have a different Maven profile defining the filter, so if we build for the test stage we get something like
database.url=url.for.test.db

The application is running on WLS 12, and we want to deploy it on local WLS using the Eclipse server plugin (we are using Eclipse Kepler). However, when we add the application to the server in Eclipse and publish, it is not working since the placeholders in the property files are not replaced with specific values.
AFAIK, the content being deployed is located in the Eclipse workspace:
<workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\<ear-project-name>\beadep\<WLS domain name>\<ear-project-name>

Of course we could change the property files in that location, but whenever we publish in Eclipse, those changes are overwritten and we get again the original property file
database.url=${database.url}

which is useless when it is deployed to WLS.
Is there any mechanism or possibility to change the property files before they are deployed to WLS from Eclipse?
Thanks for your help.
Answer: Ok here is the solution I chose to solve this (I am not sure whether it is the best one, but at least it is working):
I added a new folder to the .ear project named "properties-local". This folder contains only those property files which are relevant for local deployment (without placeholders), e.g.

database.url=url.for.local.db

Wihtin the properties of the Eclipse project, there is a section "Deployment Assembly". I added the new folder "properties-local" to the deploy path APP-INF/classes, so this is the place where they will appear in the .ear which is used for local deployment.
The maven-ear-plugin, which is responsible to build .ear files for remote stages, is not aware of the directory properties-local.
So the drawback of the solution is, there are now two folders with property files: one for local Eclipse deployment, one for .ear files which are deployed on remote servers.


Cracking The Coding Interview - Circus Tower Problem (17.8)

Question: Question:
I'm working through Cracking the Coding Interview 6th ed, and I'm having trouble with the Circus Tower problem (number 17.8). I have a solution that I think runs in O(N logN) time, but the book's solution (which is different) says that the O(N logN) solution is very complex, but my code is not. I'd like some help figuring out if my solution is correct, and if it actually runs in O(N logN) time. I want to understand why I am wrong (or right), so any details would be helpful.
Here's the problem text:
A circus is designing a tower routine consisting of people standing atop one another's shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the heights and weights of each person in the circus, write a method to compute the largest possible number of people in such a tower.
My solution:
def circus_tower(people):

    # People is a list of tuples of length 2, where item[0] is their height, and item[1] is their weight.

    if len(people) == 0:
        return 0

    people = sorted(people, key=lambda x: x[0])  # Sort people by heights. O(P*logP).
    start = 0
    end = 0
    longest_sequence = 0

    for i in range(1, len(people)):  # O(P).
        if people[i][1] > people[i-1][1]:  # Weight check.
            end = i
        else:
            longest_sequence = end - start + 1
            start = i
            end = i

    return max(longest_sequence, end - start + 1)

Here are some sample inputs and what my code returns:
circus_tower([(65, 100), (70, 150), (56, 90), (75, 190), (60, 95), (68, 110)])
6

circus_tower([(65, 100), (70, 150), (56, 90), (75, 190), (65, 95), (68, 110)])
4

circus_tower([(56, 90), (65, 95), (72, 100), (68, 90), (70, 150), (75, 190)])
2

circus_tower([])
0

Comment: The call to `sorted` is already nlogn
Comment: Yes, and from what I can tell it has the highest time complexity in the code.
Comment: Your code is O(N logN) + O(N) = O(2N logN) so you code it is less efficient than the book O(N logN)
Comment: The book's solution is actually O(N^2), but they reference an O(N logN) solution as being too complex for an interview solution, or for the book. It just seemed odd to me that I wrote this in a time period that I would consider interview-appropriate. And it's not very complex.
Comment: O(N logN) + O(N) is not O(2N+logN). It doesn't work this way.
Answer: Your solution is wrong. If you run
circus_tower([[1,1],[1,7],[1,9],[2,2],[2,6],[3,3],[3,5],[4,4]])

it returns 2 while the longest subsequence ([1,1]<[2,2]<[3,3]<[4,4]) has length 4.
The problem with your code is that you only find contiguous subsequences.
Comment: After sorting, the problem is equivalent to finding a longest increasing subsequence in a sequence of integers. That is extensively described on [wikipedia](https://en.wikipedia.org/wiki/Longest_increasing_subsequence)
Comment: Thanks for pointing out that issue - I thought there was something missing in mine. I'm having trouble coming up with a fix that keeps the algorithm O(N logN), and a Google search isn't helping. I'll keep looking into it.
Answer: I also "found" a simple solution and can't understand where I'm wrong:
module CircusTower
  class Person
    include Comparable

    attr_reader :height, :weight

    def initialize(height, weight)
      @height = height
      @weight = weight
    end

    def <=>(other)
      res = height <=> other.height

      if res == 0
        weight <=> other.weight
      else
        res
      end
    end
  end

  # Time=O(n * log n) Mem=O(n)
  def solve_b(people)
    sorted = people.sort.reverse

    res = []

    sorted.each do |person|
      if res.size == 0
        res << person
      else
        if res.last.height > person.height && res.last.weight > person.weight
          res << person
        end
      end
    end

    res.size
  end

  RSpec.describe 'CircusTower' do
    include CircusTower

    subject { solve_b(people) }

    context 'book example' do
      let(:people) do
        [
          Person.new(65, 100),
          Person.new(70, 150),
          Person.new(56, 90),
          Person.new(75, 190),
          Person.new(60, 95),
          Person.new(68, 110),
        ]
      end

      it { is_expected.to eq 6 }
    end

    context 'tricky example' do
      let(:people) do
        [
          Person.new(1,1),
          Person.new(1,7),
          Person.new(1,9),
          Person.new(2,2),
          Person.new(2,6),
          Person.new(3,3),
          Person.new(3,5),
          Person.new(4,4),
        ]
      end

      it { is_expected.to eq 4 }
    end
  end
end

Comment: oh I see I found the counter example for my "simple" solution `(1, 1), (2, 2), (3, 3), (4,1)`
Answer: There is a correct solution
module CircusTowerSo
  class Person
    include Comparable

    attr_reader :height, :weight

    def initialize(height, weight)
      @height = height
      @weight = weight
    end

    def <=>(other)
      res = height <=> other.height

      if res == 0
        weight <=> other.weight
      else
        res
      end
    end

    def smaller?(other)
      height < other.height && weight < other.weight
    end

    def to_s
      "(#{height}, #{weight})"
    end

    def inspect
      to_s
    end
  end

  # Time=O(n * n) Mem=O(n * n)
  def solve_b(people)
    sorted = people.sort

    find_lis_by_weight(sorted).size
  end

  def find_lis_by_weight(people)
    longest_by_index_cache = people.each_with_index.map { |person, i| [i, [person]] }.to_h
    longest = []

    people.each_with_index do |person, index|
      res = longest_for_index(longest_by_index_cache, index, person)

      if res.size > longest.size
        longest = res
      end

      longest_by_index_cache[index] = res
    end

    longest
  end

  def longest_for_index(longest_by_index_cache, index, person)
    longest_prev_seq = []

    index.times do |i|
      prev_seq = longest_by_index_cache[i]

      if prev_seq.last.smaller?(person) && prev_seq.size > longest_prev_seq.size
        longest_prev_seq = prev_seq
      end
    end

    longest_prev_seq + [person]
  end

  RSpec.describe 'CircusTower' do
    include CircusTower

    subject { solve_b(people) }

    context 'book example' do
      let(:people) do
        [
          Person.new(65, 100),
          Person.new(70, 150),
          Person.new(56, 90),
          Person.new(75, 190),
          Person.new(60, 95),
          Person.new(68, 110),
        ]
      end

      it { is_expected.to eq 6 }
    end

    context 'tricky example' do
      let(:people) do
        [
          Person.new(1, 1),
          Person.new(1, 7),
          Person.new(1, 9),
          Person.new(2, 2),
          Person.new(2, 6),
          Person.new(3, 3),
          Person.new(3, 5),
          Person.new(4, 4),
        ]
      end

      it { is_expected.to eq 4 }
    end

    context 'more tricky example' do
      let(:people) do
        [
          Person.new(1, 1),
          Person.new(2, 2),
          Person.new(3, 3),
          Person.new(4, 1),
        ]
      end

      it { is_expected.to eq 3 }
    end
  end
end

see more solutions for CTCI on https://github.com/holyketzer/ctci_v6
Answer: I have divided the problem into three parts.

Insert the data HeightWeight object and then sort with height or width. I have sorted with height

After that insert the values into the map to get unique heights with minimum weight.

After that I have found the Longest Increasing subsequence for weight.
import java.util.*;
public class CircusTower {
private class HeightWeight implements Comparable<HeightWeight>{
    int height;
    int weight;
    HeightWeight(int height, int weight) {
        this.height = height;
        this.weight = weight;
    }
    @Override
    public int compareTo(HeightWeight other) {
        if(this.height == other.height){
            return this.weight - other.weight;
        }else{
            return this.height - other.height;
        }
    }
}
public static void main(String[] args) {
    int[][] arr = {{1,1},{1,7},{1,9},{2,2},{2,6},{3,3},{3,5},{4,4}};
    CircusTower ct = new CircusTower();
   System.out.println(ct.getMaxHeightTower(arr));
}

public int getMaxHeightTower(int[][] arr){
    List<HeightWeight> list = new ArrayList<>();
    int i =0;
    for(i =0; i<arr.length; i++){
        list.add(new HeightWeight(arr[i][0], arr[i][1]));
    }
    Collections.sort(list);
    Map<Integer, Integer> map = new HashMap<>();
    for(i =0; i<list.size(); i++){
        HeightWeight current = list.get(i);
        if(!map.containsKey(current.height)){
            map.put(current.height, current.weight);
        }
    }
    int[] nums = map.values().stream().mapToInt(Integer::intValue).toArray();
    return getLIS(nums);
}

public int getLIS(int[] nums){

    int _l = nums.length;
    int[] out = new int[_l];
    int mx = Integer.MIN_VALUE;

    /*
    we initialize the array with ones because
    a single character has a subsequence of length one
    */
    Arrays.fill(out, 1);

    for(int i = 0; i < _l; i++)

        for(int j = i + 1; j < _l; j++){
            /*
            every iteration, all we're doing is checking what is the longest
            increasing subsequence so far, till this point
            */
            if(nums[j] > nums[i])
                out[j] = Math.max(out[j], out[i] + 1);

            /*
            we keep checking for a max value because the longest
            subsequence could exist before the end of the string
            */
            mx = Math.max(out[j], mx);
        }

    return mx == Integer.MIN_VALUE ? 1 : mx;
}

}
Answer: I went through this thread and decided I can attempt to clarify this. Consider this as an example of those cases where a greedy approach does not work because we are not able to decide for sure if taking a particular element is invariably the better solution that not taking it. We have seen a similar problem with Knapsack 0/1 problem.
If you are given the weights: [1,2,3,4] and profits [80, 100, 20, 60] and your capacity is 5, then greedily you can choose 120 (100+20), but then you will realise that leaving out 100 was the better choice, since you could have got 140 (60+80).
To solve this problem, we need to assume a somewhat similar approach: first let's sort the array of people, because unlike in case of Knapsack, here the order of taking elements matters. But both of these approaches boils down to a similar idea: to optimize the output, should you take the nth element or leave it?
Here is my Java recursive solution which runs in O(2^n) complexity:
Approach-1: Recusrive/Backtracking solution
public static void makeTower(List<Person> list, List<Person> tower, int index)
{
    //Base case
    if(index==-1)
    {
        printTower(tower);
        return;
    }
    if(tower.get(tower.size()-1).height > list.get(index).height && tower.get(tower.size()-1).weight > list.get(index).weight) {
        tower.add(list.get(index));
        //if it is possible to add this person to the tower, add him
        makeTower(list, new ArrayList<>(tower), index - 1);
    }
        //OR, choose to exclude the person
        tower.remove(list.get(index));
        makeTower(list, new ArrayList<>(tower), index-1);

}

Where "Person" class is just the encapsulation of his height and weight
public class Person {
int height;
int weight;
public Person(int _h, int _w)
{
    this.height = _h;
    this.weight = _w;
}
}

And "printTower" method does nothing but just print the possible tower to you after every combination
public static void printTower(List<Person> t)
{
    for(Person p : t)
        System.out.println(p.height+" , "+p.weight);
    System.out.println("-----END-----");
}

Test input and output:
So if we consider this example:
The people (height, weight) : [20, 80] [10, 40] [80, 40]
First step, sort by heights -> [10, 40] [20, 80] [80, 40]
Then, we can possibly construct these towers:

[10, 40] on top of [20, 80]

This is the only tower possible from all the combinations.
So finally, the main (driver) method:
public static void main(String args[])
{
    List<Person> people = new ArrayList();
    people.add(new Person(20,80));
    people.add(new Person(10, 40));
    people.add(new Person(80, 40));
    Collections.sort(people, new Comparator<Person>()
    {
        @Override
        public int compare(Person one, Person two)
        {
            return (one.height-two.height);
        }
    });

    List<Person> t = new ArrayList<>();
    t.add(new Person(1000,1000));
    makeTower(people, t, people.size()-1);
}

As mentioned, the runtime complexity of this algorithm is exponential, but it turns out that there is a better method for this which suits only this problem. This solution is explained in Cracking the coding interview.
Approach 2 - Dynamic Programming
The second approach runs in O(n^2) complexity, not pretty but definitely a lot of improvement over exponential. The approach is that we will take turns to consider each person as the last person in the tower. How long will the tower run if person-0 is the last person? And so on till person-n. In our case,
length of tower(given person-0 is at base) : 2 (highest)
length of tower(given person-1 is at base) : 1
length of tower(given person-2 is at base) : 1
So 2 is our answer (maximum tower size). Bam! That's our answer. Much less fuss, but  as with most DP approaches, the problem with this approach is that its a much more specific type of solution that may/may not suit other similar types of problems, and hence a tad bit more difficult to come up with.
Since this post has already run so long, let me know if anyone would need the code for approach-2 with explanation, would be glad to help! :)


Trying to explain the unknotting number of $7_5$

Question: I am trying to proof that the unknotting number of prime knot $7_5$ is $2$.
For this purpose, I am studying  the minimal number of crossings that need to be changed in the knot in order to get a diagram of the trivial knot.
However, I am stuck when I change the following crossing (circled in red):

I know that I get a knot with five crossings, but I am not capable of distinguish which of the following is:

How do I proceed?
Thank you in advance!
Answer: We can cheat by using a computer tool. I'm using KnotFolio.  I took your drawing of the knot and input it:

It recognizes this as $7_5$ by calculating some knot invariants and using the fact that no other knot with at most 7 crossings has the same invariants.
Flipping the crossing in question,

by a similar process it recognizes it as $5_2$. Unfortunately, KnotFolio doesn't have any Reidemeister move tool yet, so you have to edit the diagram manually, but after applying Reidemeister II we get this:

It's still recognized as $5_2$. The "Beautify" tool smooths out the knot diagram (an isotopy of the diagram -- note that it does this isotopy on a sphere, so it might choose a different face to be the outer face). In this form, it's more obvious that it's $5_2$.

By the way, with two flipped crossings we can get the unknot:

I'm guessing you already know this and that you're systematically checking that flipping each individual crossing in your diagram of $7_5$ doesn't give the unknot. Beware that this alone is not sufficient in proving that the knot $7_5$ has unknotting number $2$ -- you'd only be showing that the diagram in question has unknotting number $2$. There might still be some diagram for $7_5$ that has unknotting number $1$!
Answer: Do the obvious Reidemeister move. Now treat it as a planar graph (with the crossings as vertices of valency $4$). Label each region with the number of edges that surround it.
Which of the knots with $5$ crossings has the same "region structure" ?


How to run HTML project from github?

Question: Sorry for the noob questions but I can't figure this particular case out. I want to try out https://github.com/albertobeta/AffectiveSlider. So decided to import the project into Eclipse.
Q1) In general how and where can I open and run thing GitHub project?
Q2) I tried importing the project in Eclipse but could not run anything or any file JS file to run.
Comment: THIS IS NOT JAVA CODE
Comment: Q1) In a thing called [qualtrics](https://github.com/albertobeta/AffectiveSlider/tree/master/code_implementations/qualtrics) Q2) There's JS in the [qualtrics](https://github.com/albertobeta/AffectiveSlider/tree/master/code_implementations/qualtrics) folder. BTW, JS is not Java.
Comment: There's no one-size-fits-all for this sort of thing. The code you're looking at is mainly HTML with some Javascript mixed in. Eclipse is a Java editor (different, unrelated language to Javascript) and is very unlikely to be able to do anything of use. I don't see any of the usual build tools I'm used to (autoconf, makefiles, some sort of `manage.py` or indicator of what webservice is intended, etc.), so it's not something I immediately know how to run.
Comment: @SilvioMayolo Technically [Eclipse can be used for web dev](https://www.eclipse.org/downloads/packages/release/indigo/sr2/eclipse-ide-javascript-web-developers), though I don't know anyone that would voluntarily do so. Furthermore, it looks like it's just a static HTML site, so you could presumably host it with any server that supports static file hosting (eg. nginx, `python -m http.server`, etc)
Answer: I would suggest opening the project in VS Code using the live server extension. You can open the repo in VS Code start the live server and open the project in <code>/code_implementations/html5</code>.
I don't know about Eclipse so I cant help you there.
Took two minutes and I have it running.

How to run HTML project from github?


Como posso criar um banco de dados dinamico no pyhton

Question: Alguem poderia me auxiliar em como criar um banco de dados dinamico, onde posso adcionar e remover itens? Na linguagem Python, se possivel com o Sqlite
Comment: Comece estudando a [documentação oficial da `sqlite3`](https://docs.python.org/3.6/library/sqlite3.html).
Answer: No exemplo abaixo, o banco de dados SQLite é criado no arquivo foobar.db, onde uma tabela chamada tb_fruta é criada e seus itens manipulados (inclusão, alteração e exclusão) por meio de comandos SQL:
import sqlite3

conn = sqlite3.connect('foobar.db')

c = conn.cursor()

c.execute("CREATE TABLE tb_fruta ( id integer, nome text );")

c.execute("INSERT INTO tb_fruta ( id, nome ) VALUES ( 1, 'BANANA' );");
c.execute("INSERT INTO tb_fruta ( id, nome ) VALUES ( 2, 'LARANJA' );");
c.execute("INSERT INTO tb_fruta ( id, nome ) VALUES ( 3, 'MELANCIA' );");
c.execute("INSERT INTO tb_fruta ( id, nome ) VALUES ( 4, 'MACA' );");
c.execute("INSERT INTO tb_fruta ( id, nome ) VALUES ( 5, 'UVA' );");
c.execute("INSERT INTO tb_fruta ( id, nome ) VALUES ( 6, 'MORANGO' );");

c.execute("UPDATE tb_fruta SET nome = 'LIMAO' WHERE id = 2;");
c.execute("UPDATE tb_fruta SET nome = 'ABACAXI' WHERE id = 6;");

c.execute("DELETE FROM tb_fruta WHERE id = 3;");
c.execute("DELETE FROM tb_fruta WHERE nome = 'UVA';");

conn.commit()
conn.close()

Testando:
$ sqlite3 foobar.db
SQLite version 3.7.17 2013-05-20 00:56:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> SELECT * FROM tb_fruta;
1|BANANA
2|LIMAO
4|MACA
6|ABACAXI
sqlite>


Clear data stored with drupal_static() and cache_set()

Question: I have a custom module in Drupal 7 where I am caching data from REST calls using drupal_static() and cache_set().
function _mymodule_call() {
  $data = &drupal_static(__FUNCTION__);
  if ( ! isset($data) ) {
    if ($cache = cache_get(__FUNCTION__)) {
      $data = $cache->data;
    }
    else {
      $data = my_api_call();

      if ( is_object($lists) ) {
        // cache for one hour
        cache_set(__FUNCTION__, $data, 'cache', time() + 3600);
      }
    }
  }
  return $data;
}

I want to make an admin feature where we can specifically clear these cached values. I suppose the cache key would be _mymodule_call. How do I clear them from the cache?
Comment: I do not have the time to write a complete answer, but there is a good tutorial here: https://www.lullabot.com/articles/a-beginners-guide-to-caching-data-in-drupal-7
Answer: The Drupal way is to have a $reset parameter to your function.  It would look something like:
function _mymodule_call($reset = FALSE) {
  if ($reset) {
    // do stuff
  }
  // ...
}

node_load() is probably the best example of this.
In your specific case, you can pass the $reset parameter to drupal_static() or explicitly call drupal_static_reset().  For the cache backend, you need to think whether you want to just rework the logic and just do the cache_set() or explicitly call cache_clear_all($cid) (my guess is the former).
And remember, that drupal_static() is only effective when you need the value multiple times during the same request.  This does not persist between page loads (or any other HTTP request that get handled by Drupal).
Comment: `cache_clear_all($cid)` -- in my case, would that be `cache_clear_all('_mymodule_call')`?
Comment: @user1359 Looks like it would be `cache_set(__FUNCTION__, 'cache')`; the `$bin` needs to be specified when you use the `$cid`.  Check out the API page.
Answer: I made a test script, and it turns out that in my code above, _mymodule_call is the $cid, because I created my cache in the _mymodule_call function like so: cache_set(__FUNCTION__, $data, 'cache', time() + 3600);.
Thanks to mpdonadio for noting that you have to specify the $bin argument when you use cache_clear_all(). In my case, since I wasn't specifying it in cache_set(), it defaults to 'cache'.
Here's my script:
$> cat cache_test.php
<?php
// set the cache
cache_set('test_key', 'hello there ' . mt_rand(), 'cache');
$data = cache_get('test_key');
// display it
print_r($data);
// clear it
cache_clear_all('test_key', 'cache');
// retrieve it (should be empty)
$data = cache_get('test_key');
// display the emptied(?) cache
var_dump($data);
print_r($data);

And here's its output:
$> drush scr cache_test.php
stdClass Object
(
    [cid] => test_key
    [data] => hello there 1718114879
    [created] => 1482938803
    [expire] => 0
    [serialized] => 0
)
bool(false)


How do I remove the [object HTMLCollection] line at the end of my web page?

Question: My code is displaying the expected result, except that at the end, a line displays saying, "[object HTMLCollection]". How do I remove this extra snippet?
I searched for an answer but although there are questions like: "How to remove an item from HTMLCollection?", none is about why these words ([object HTMLCollection]) display and how to remove them. Here's my code:

This bed is too small.

This bed is too big.

This bed is just right.

I want to remove the last line from the result:
This bed is too small.
This SUV is too big.
This bed is just right.
[object HTMLCollection]
Comment: par is not a string. Par is a collection of elements. Thus, when you document.write(par) the toString() on par gets called, resulting in "[object HTMLCOllection]"
Comment: Remove the line `document.write(par + "");`
Comment: The short answer is that using a collection of HTML elements as a string -- concatenating it with a string, for instance, which is what you're doing with `par + ""`, or even passing it as-is with `document.write(par)` -- does not produce the result you would expect. The `toString` method on the collection, which is called automatically to get you the string variant of the object, does not amount to representation of contents of its elements, it amounts to `"[object HTMLCollection]"`, which is why you get that at the end of your document.
Comment: Thanks everyone. Yes, you are right Roland Starke, removing the line solved the problem. I guess all HTML elements are objects then?
Answer: Removing the line "document.write(par + "");" solved the problem. It appears that javascript considers HTML elements as objects and not as strings.
I wasn't necessary to write the line in the first place as the text in  tags already displays as strings. I didn't notice this at first.


Is there any other way to authenticate Azure Devops CLI than access token (PAT)?

Question: Context
I am trying to manage my Azure Devops projects and repositories in automated way using VSTS CLI. Maybe I am missing something, but it seems that the only way is access token. I would not use tokens, instead I prefer some more integrated auth method similar how Git Credential Manager integrates with Azure Devops. I prefer use "enterpise grade" (as MS calls it).
Question
What am I missing, how can I accomplish the simple task, like creating a repo on Azure Devops without messing wit PATs?
About auth methods MS writes:

Azure DevOps Services and TFS use enterprise-grade authentication to help protect and secure your data. Clients like Visual Studio and Eclipse (with the Team Explorer Everywhere plug-in) also support Microsoft account and Azure AD authentication.
  For non-Microsoft tools that integrate into Azure DevOps but don't support Microsoft account or Azure AD authentication, you must use PATs.
Comment: Git Credential Manager, of course, creates and uses PATs for you.
Answer: It seems that VSTS CLI has been deprecated and will no longer be receiving new features. As time of this writing the VSTS CLI documentation does not seem to mention this movement though.
Azure DevOps Extension for Azure CLI has replaced the VSTS CLI. Azure CLI supports the "enterprise grade" authentication, and Azure DevOps Extension commands are map to the depreciated VSTS CLI commands. Here is the mapping for the commands
Answer: With the latest Azure DevOps CLI (https://learn.microsoft.com/en-us/azure/devops/cli/index?view=azure-devops), you can now access Azure DevOps by using az login where you can authenticate using o-auth flow. Check it out.
However, for non-interactive automation use case, PAT is the only method.


Does "\root" do anything in /etc/aliases?

Question: I've found on a couple servers that have the following entry in /etc/aliases:
root: \root,firstname.lastname@example.com

You can send mail to /dev/null like this:
root: /dev/null

I can't find \root used in any documentation.

Does \root do anything?
Could it be a syntax error?
Comment: You seem to be right that the backslash syntax does not appear to be documented in "man 5 aliases" where one would expect it to be mentioned (or at least I cannot find it in my section 5 aliases man page) but this is a longstanding feature of the mail aliases file.
Answer:  but I can't find what the \ does

The backslash "escapes" the token following, preventing further interpretation.
It's an important mechanism in defining aliases like the example in your post, where "root" is aliased to include both the account of that name AND other addresses.  Without the \ a loop would be created when the program interpreting the alias tried to dereference "root", which includes as a member "root" (which includes as a member "root", and so on..)
Comment: Just to be clear: it is used when an account forwards to itself, as root does above? (And the purpose is to prevent a loop?)
Answer: I believe that \root prevents that id from being passed through aliases again and (instead is) delivered to the LOCAL root account.
Answer: \root will save the message to (for example) /var/mail/root and forward it to firstname.lastname@example.com. Without it, only email@example.com will receive the message. The \user, other@address notation is very common for users that use ~/.forward files.
Answer: Putting a backslash (\) in front of the username in the first recipient is a special syntax for delivering mail to the local mail spool with no further aliasing.
root: \root,email@example.com

Here, user root is forwarding mails to two different places:

One copy of the message goes to the mail spool
The second recipient, firstname.lastname@example.com, sends another copy of message to MX servers of example.com

Please find details here.


How to derive a generating function for the following series

Question: Given an integer n how would derive a function fn that is without conditional statements, does not use floor or ceiling functions and returns an integer which has the following relationship to n:
    n = {1,  2,  3,  4,  5,  6, ...}
fn(n) = {0, +1, -1, +2, -2, +3, ...}

I know the answer (I didn't want to pollute your answers by sharing it), but I can't seem to derive it myself logically - so, this question is about how to derive the function, not how the function looks like.
Answer: Clearly a factor of $(-1)^n$ gets you the right algebraic sign, so the real problem is getting the absolute value of $f(n)$ to come out right. You want it to be $\frac{n}2$ when $n$ is even and $\frac{n-1}2$ when $n$ is odd; you can get this easily if you can find a function $g(n)$ that returns $0$ when $n$ is even and $-1$ when $n$ is odd. The function $g(n)=(-1)^n$ gives two different constant values depending on the parity of $n$, so we try to modify it: $g(n)=(-1)^n-1$ produces $0$ when $n$ is even and $-2$ when $n$ is odd, so dividing that by $2$ does the trick. Now put the pieces together:
$$f(n)=\frac{(-1)^n}2\left(n+\frac{(-1)^n-1}2\right)\;,$$
which can of course be simplified, e.g., to
$$f(n)=\frac{(-1)^n(2n-1)+1}4\;.$$
Comment: Brilliant! Thank you.
Comment: @DanG: You're welcome.


Minimum variance of $k_1X+k_2Y$ where $X,Y$ are independent Poisson

Question: I have the following question for homework:

Suppose that $X$ and $Y$ are independent Poisson distributed values with means $\theta$ and $2\theta$, respectively. Consider the combined estimator of $\theta$
$$
\tilde\theta = k_1 X + k_2Y
$$
  where $k_1$ and $k_2$ are arbitrary constants.

(a) Find the condition on $k_1$ and $k_2$ such that $\tilde \theta$ is an unbiased estimator of $\theta$.
(b) For $\tilde \theta$ unbiased, show that the variance of the estimator is minimized by taking $k_1 = 1/3$ and $k_2 = 1/3$.
(c) Given observations $x$ and $y$ find the maximum likelihood estimate of $\theta$, and hence show that $\tilde\theta$ is also the maximum likelihood estimator.

I know the answer for part a) is $$k_1+ 2k_2 = 1$$
I don't know where to go with part b). So far I have as far as
$$Var(\hat\theta)= (k_1)^2Var(X) + (k_2)^2Var(Y)$$
Any help would be appreciated thanks in advance!
Comment: https://math.stackexchange.com/q/2156682/321264
Answer: $\newcommand{\Var}{\mathrm{Var}}$Hints: You effectively need to minimise the function $$f(k_1, k_2):= \Var(X)k_1^2 + \Var(Y)k_2^2$$ subject to the constraint $$k_1 + 2k_2 =1.$$ To do this, you can eliminate one of the variables from $f(k_1, k_2)$ by using the constraint $k_1+2k_2=1$. This will leave you with a single variable quadratic, which you should know how to minimise.
Also, note that $\Var(X)$ and $\Var(Y)$ are just constants that you can express in terms of $\theta$.


Can I skip constants in this limit?

Question: It would help me a lot, since L'Hospital would be very fast in that case. The Limit is approaching infinity and numbers 1 and -1 do not seem to be too significant. Would it be legit move? Or is there any smarter way to solve this limit?
Comment: the limit is not approaching anything. it either exists or it doesn't
Comment: (a) Yes, you can; (b) L'Hopital is **really** overkill here. Do you know how to prove $$\lim_{x\to\infty}\frac{x^2+1}{x^2} = 1,$$ $$\lim_{x\to\infty}\frac{4x^2}{4x^2-1} = 1,$$ and $$\lim_{x\to\infty}\frac{x\sqrt{x^2}}{4x^2} = \frac{1}{4}$$?
Answer: Hint:
Set $1/x=h\implies h\to0^+$
$\sqrt{1+x^2}=\dfrac{\sqrt{h^2+1}}{|h|}$
And for $h>0,|h|=+h$
Answer: $$\lim_{x\to\infty}\frac{x\sqrt{x^2+1}}{4x^2-1} = \lim_{x\to\infty}\frac{\sqrt{1+1/x^2}}{4-1/x^2} = \frac14 $$
Comment: Given the question, it does seem that the OP needs a lot more pedagogy than this. You basically sweep under the rug, in your last equality, the core confusion the OP is having.
Comment: @ClementC. Point taken.  But there is a difference between OP's question and my last equality.  I'm discarding infinitesimal quantities while OP's question is about discarding finite quantities (against a infinity, nevertheless).  I was hoping the former is a bit easier to be accepted by OP.
Comment: @Guangliang Could you please explain how exactly was the second limit made? I don't seem be intuitively able to figure out.
Comment: @JohnSmith Divide both the numerator and denominator by $x^2$.
Comment: projectilemotion Dumb me, thanks.

Can I skip constants in this limit?


alternative way to DISTINCT

Question: i have sql statement like this
SELECT DISTINCT results_sp_08.material_number FROM results_sp_08
        INNER JOIN courses ON results_sp_08.material_number = courses.material_number
        INNER JOIN users ON results_sp_08.id = users.id
        AND results_sp_08.doctor = 'xx260'

i need alternative way to DISTINCT in to use it in MySQL version: 4.1.22 ?
is there another way or trick?
Answer: Like Joel, your best bet is to add the GROUP BY clause. In your case
GROUP BY results_sp_08.material_number

Answer: DISTINCT is functionally equivalent to GROUP BY <all the columns in your select list>
Comment: @d03boy: No, DISTINCT applies to all columns in the select-list.
Comment: Had to downvote because your description is not clear. Distinct can be used on a single column in a Selection.
Answer: I usually use a double-join strategy on these:
JOIN tablex AS x1 ON whatever
LEFT JOIN tablex AS x2 ON whatever
    AND x2.pkid < x1.pkid AND x2.somefield IS NULL

which guarantees I get at most 1 record on all my joins.
Answer: I've successfully eliminated DISTINCT by adding more clauses to my WHERE in the past. You need to look at what fields in your JOINs are causing multiple rows to come back. A subquery may work as well.
Answer: Without knowing the tables structure it is hard to tell.
You need to say in words what you are trying to do.
Assuming that the result_sp_08 contains only unique "material_number"s, and
you are trying to get all the unique material_number that had at least one row in courses and users tables:
SELECT results\_sp\_08.material\_number
FROM results\_sp\_08
WHERE results\_sp\_08.doctor = 'xx260' and
EXISTS(select * from courses
    where results\_sp\_08.material\_number = courses.material\_number) and
EXISTS(select * from users
    where results\_sp\_08.id = users.id)

See the documentation: http://dev.mysql.com/doc/refman/4.1/en/exists-and-not-exists-subqueries.html
Comment: Exists doesn't exist in his MySQL version.
Answer: SELECT results_sp_08.material_number FROM results_sp_08
       INNER JOIN courses AS c ON
       results_sp_08.material_number = c.material_number
       INNER JOIN users AS u ON results_sp_08.id = u.id
       AND results_sp_08.doctor = 'xx260'
GROUP BY results_sp_08.material_number.

Added group by clause and removed distinct. And one of the best practices: Always use aliases when using JOIN.

alternative way to DISTINCT


Store values from dataset to a list

Question: I have created a Dataset from my database icluding two columns and I want to store all the rows of the second column(containing strings) to a list. How can I do that?
Comment: Take a look at Entity Framework. It makes working with databases much easier
Comment: Actually I heard alot of good things about Entity Framework but it seems complicated to me. I think for small project like the one I'm doing, ADO.NET is just sufficient.
Answer: Use Select?
 var myStrings = myDataSet.Tables[0].AsEnumerable()
                          .Select(x => x.StringColumn).ToList;

You could also use a loop:
var list = new List<string>();
foreach(DataRow row in myDataSet.Tables[0].Rows)
{
    list.Add((string)row["StringColumn"]);
}

Comment: Thanks Dave. Can I use a for loop to do this task?
Comment: What does ["StringColumn"] specify? I want to get all rows of the second column so what should I put here instead of ["StringColumn"]?
Comment: @MinhNguyen That's the name of the column you want to get values from.

Store values from dataset to a list


Transversality and the hessian of critical ponint of a function

Question: I am trying to do the following exercise:
Let $f\in C(\mathbb{R^n,\mathbb{R}})$. Consider the gradient vector field $\nabla f=(\frac{\partial f}{\partial x_1},...,\frac{\partial f}{\partial x_n})$. Let $\Gamma_{\nabla f}\subset $ be it's graph, and let $\mathbb{R}^n $ be embedded in $\mathbb{R}^{2n}$ by $x\rightarrow (x,0)$. Show that $\Gamma_{\nabla f} \pitchfork \mathbb{R}^n$ if and only if and the critical points of $f$ are non-degenarate.
Now first for we need to figure out what is the tangent space of $\Gamma_{\nabla f}$. Well this will be a submanifold in $\mathbb{R}^{2n}$ by considering the function $G(x,y):\mathbb{R}^{2n}\rightarrow \mathbb{R}^n $ , $(x,y)\rightarrow y-\nabla_f$ and checking that $0$ is a regular value for this map. Now we know from the regular value theorem that $T_p (\Gamma_{\nabla f})=\ker d_pG $. Now the $\ker$ of this map will be the vectors in $\mathbb{R}^{2n}, (v_1,...,v_{2n}) $ such that $H_f(p)(v_1,...,v_n)=(v_{n+1},...,v_{2n})$.
Now I still need to finish the problem but is this the right way to be thinking about this ? Thanks in advance.
Comment: why are you considering $y-\nabla f$ for G? Other than that, yes your reasoning is the right way to approach the problem.
Comment: It seemed to be the best way to see what the tangent space of $\Gamma _{\nabla f}$ would be .@DanielH.Hartman, But yeah I guess I can also use that parametrization to see the tangent space. I just didn't want to be working with maps because I was trying to use the definition of transversality of two submanifolds.
Answer: Consider $\Gamma_{\nabla f} : \mathbb{R}^{n}\rightarrow \mathbb{R}^{2n}$, defined by
$$\Gamma_{\nabla f} (x) = \big(x_{1},...,x_{n},\frac{\partial f}{\partial x_{1}}(x),\frac{\partial f}{\partial x_{2}}(x),...,\frac{\partial f}{\partial x_{n}}(x)\big)$$
Notice that when $p\in \mathbb{R}^{n}$ is a critical point for $f$, $\Gamma_{\nabla f}$ intersects the plane $\mathbb{R}^{n}\times \{0\}$ at $(x,0)$. Then $\Gamma_{\nabla f}\pitchfork(\mathbb{R}^{n}\times \{0\})$ if and only if $0$ is a regular value for the map $g\circ \Gamma_{\nabla f}:\mathbb{R}^{n}\rightarrow \mathbb{R}^{n}$ where $g:\mathbb{R}^{2n}\rightarrow \mathbb{R}^{n}$ given by $g(x,y)=y$. The only way a value of map from n dimensional space to n dimensional space is a regular value is if the derivative map is invertible. Computing the derivative we get the Hessian matrix at $x$:
$$
\begin{pmatrix}
\frac{\partial ^{2} f}{\partial x_{i} \partial x_{j}}(x)
\end{pmatrix}.
$$
The Hessian invertible at a critical point is the definition of a critical point being nondegenerate.
Comment: @moonknight No, it's only relevant at critical points. At noncritical points, you can have a Hessian be singular (what is the Hessian of the projection map $\pi(x,y) = x$?) More over, if you are at a point where the differential isn't singular, then transversality is satisfied trivially since that point isn't in the intersection.
Comment: It seems to me that your answer only deals with critical points. Shouldn't you prove the invertibility for every point (critical and non-critical for $f$)? Otherwise, how can you prove "critical points of $f$ are non-degenerate" $\Rightarrow$ "$\Gamma_{\nabla f} \pitchfork \mathbb{R}^n$"?


Escrever Html usando javascript

Question: Estava estudando alguns plugins jquery e percebi que para criar o html, o programador escreveu cada linha em um array e ao final usou o join:

var tpl = [
  '
',
   '

',
   '
',
    '',
    ' : ',
    '',
    '',
   '
',
   '
',
    '
',
     '

',
     '

',
     '

',
    '
',
    '',
    '',
   '
',
  '
'
 ].join('');

Alguém, com experiência, sabe porque escrever dessa forma, ou seja, sem usar uma string e concatenar cada linha?

var tpl = '
'+
   '

'+
   '
'+
    ''+
    ' : '+
    ''+
    ''+
   '
'+
   '
'+
    '
'+
     '

'+
     '

'+
     '

'+
    '
'+
    ''+
    ''+
   '
'+
  '
';
Comment: Defina "melhor".
Comment: Template strings do ECMA6 no quesito "programar" é muito bom, porém não sei quanto ao desempenho e compatibilidade ainda não é tão amplo.
Comment: A dúvida é quanto ao desempenho mesmo, corrigir o "melhor"
Comment: No Ecma6 tem o template string segue link: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/template_strings
Comment: Não conhecia este template string.
Answer: Entre usar join ou concatenação, concatenar apresenta um melhor desempenho, porém a escrita do código pode ser mais massante, principalmente ao se usar ' com " e quando há muitas linhas.
Nesse teste, localmente, a concatenção correu 12.497 vezes em 0.083 segundos contra 11.144 em 0.087 segundos com join.
Nesse outro, localmente, a concatenção correu 12.703 vezes em 0.086 segundos contra 12.875 em 0.080 segundos com Template strings.
Particularmente estou preferindo usar template string quando preciso escrever HTML no javascript. Subjetivamente ele se parece melhor e mais fácil de se ler, justamente para strings multi-linhas e string contendo ' e ". E o mais interessante sobre ele são as Tagged template, que da esse poder:
let conta = {numero: '9999-9'};
tag `Minha conta é ${conta.numero}.`

Compatibilidade com navegadores
Comment: Obrigado pela resposta.

Escrever Html usando javascript


Not understanding this cover version

Question: let's take this song:

I can hear a progression of Em-G-D-C-G-D
but when I look at this cover:

(obviously the guitar is tuned down)
I can see him play F5-G5#-G5-C5#-G5#-G5
if you account for the tuning, that would work out to:
E5-G5-F5#-C5-G5-F5#
so he's playing a F# where I hear a D; assuming we forget about the 3rd, the only difference is that he has a C# where I have a D, in the 5th.
now, when I try to play it with a F# chord it really doesn't sound good but that's what I see in the video.
can anyone clarify this? :) I feel confused.
Answer: Yes, I agree in the original there is D with F# in the bass. It's similar to a regular power chord with 1 fret wider fretting hand stretch.
The cover sounds OK because:

The guitar is rather quiet in comparison to the original track
In the verse only root notes are played, not full chords
F#5 might be interpreted as third and major seventh of D, so kind of fits

Note there are some other details omitted in the cover version as well.

Not understanding this cover version


Swap Images With jQuery hover

Question: I have an img tag with following details: id="hover1" src="hello.png"

Using two separate buttons, I'm able to swap images with following jQuery:
$('#button1').click(function(){
$('#hover1').attr('src', 'hello_hover.png');
});

$('#button2').click(function(){
$('#hover1').attr('src', 'hello.png');
});

However, when I try to swap images with the following code nothing seems to happen.
$('#hover1').hover(function(){
$(this).attr('src', 'hello_out.png');
}, function(){
$(this).attr('src', 'hello.png');
});

The code looks ok to me. What is causing it to fail? Please help me out.
I'm using jQuery 2.1.0 , Mozilla 26.0, Windows7.
Thanks.
Comment: seems correct, can you provide a jsfiddle please ?
Comment: you most likely didnt wait till DOM is fully loaded and atatch the handlers to non existent elements. open developer console and see if you get errors for elements being undefined. if yes, put your code in a function that runs after DOM load
Comment: looks good to me, only difference i see is, that you use two different image-paths in your two examples...
Comment: @Banana I'm using code right at the bottom in body tag. There are no errors in the developer console. Other code works fine; only this one is acting up for some unknown reason. Still stuck.
Comment: Ok, found the culprit.I had set up a custom function to trap errors. In order to test its validity, I also made a call to an undefined function. This call was somewhere in the middle of the file. All the code before that call was working fine. Only the code that was after that call was not working. I've shifted that call to the bottom. Sanity restored.
Answer: $(function () {
    $('a img').hover( function () {
        $(this).attr('src', $(this).attr('src').replace(/\.jpg/, 'yourImageName.jpg') );
    });

let see this ..Thank you
Answer: Works well for me here... try using this JQuery code, and waiting to run it until the document is done loading :
$(document).ready(function(){
    $('#hover1').hover(function(){
        $(this).attr('src', 'hello_hover.png');
    }, function(){
        $(this).attr('src', 'hello.png');
    });
});

Working Fiddle :
http://jsfiddle.net/st7sM/1/
Answer: Probably it's not what are you looking for but maybe it could help
Why you don't only use CSS?
Here the fiddle
#hover1{
    background-image: url('http://lorempixel.com/400/200/sports/4');
    height:200px;
    width:400px;
}
#hover1:hover{
    background-image: url('http://lorempixel.com/400/200/sports/1/');
}

Comment: Thanks for your input. But as you can see its a very simple function. It's supposed to work. Right now I'm just testing and learning. Pretty soon I'm gonna need to use it some where. What am I gonna do then? Thanks again for taking time to answer.
Answer: To swap images easily, you can use the open source library bootstrap-spacer via NPM
npm install swapimagesonhover

or you can visit the github page:
https://github.com/chigozieorunta/swapimagesonhover

Using the above library, the data-img attribute is used to attach the second image of your choice you would want swapped. Once this is done, simply add your swim class to the image element and you're good to go (make sure jQuery script is included, it requires it to work properly).
Here's a sample below:
<!DOCTYPE html>

    <link href="swapimagesonhover.css" rel="stylesheet" type="text/css"/>

Swap Images With jQuery hover


What causes this dependency error in Rails 3?

Question: I now get the following:
`dependencies.rb:239:in `require': no such file to load -- require_relative (LoadError`)

But I don't have enough information to figure out what is causing it or how to debug it.
What can I do?
Comment: What version of Ruby are you on?
Comment: I am not sure what caused it...all of the sudden, with some minor changes, I started to get this and I have no idea where to begin to fix it....when I create a brand new rails app instance, it starts fine, but I don't want to start from scratch.... :(
Answer: It probably comes from linecache gem version 0.45 which was released yesterday. Rolling back to 0.43 will get you around this for now. I'm not sure if they intentionally broke support with Ruby 1.8.7 or not.
This is a dependency of ruby-debug-base.
Add something similar to the following in your Gemfile.
group :development, :test, :cucumber do
  gem "linecache", "0.43"
  gem "ruby-debug-base", "0.10.4.0"
  gem "ruby-debug", "0.10.4"
end

Comment: ah, you are genius, that sounds like what it was, but am trying it now!  if this works, you saved my life
Comment: wow we just got this and i had a feeling it was linecache mucking up. i just didn'w know how to fix it. thanks for this! you saved two lives today
Comment: had the same problem this morning, and the above helped me, thanks
Answer: Alternatively, add
gem 'require_relative'

to your Gemfile. It looks like linecache 0.45 needs it, but 0.43 doesn't, which is why downgrading linecache works.
Comment: I left this out of my answer, because I'm not sure what the intention of the 0.45 release of linecache is. It should have this dependency listed, or at least a note that it's broken with 1.8.7. For that reason, I don't trust this release and would rather wait for clarification or 0.46.
Comment: [Release 0.46](https://rubygems.org/gems/linecache) is available and now has a dependency for require_relative. Sorry for the omission.


Most widely accepted method of SVM model validation?

Question: I am building an SVM based classifier (libsvm) for two distinct balanced classes which are non-linear but separable with an RBF kernel.  Both classes have 175 instances each, which must be utilized for training and testing.
What is the most accepted scientific method for validation of the model, showing the probable predictive accuracy?

Is it k-fold where k=10 repeated k times?
Is it leave-one-out?
Is it a different method?

Additionally:

Should the hyper-parameters be re-tuned for each round of k-fold cross validation?
In leave-one-out cross validation should one instance be left out from one class at a time, or both classes at the same time?
Answer:
<code>Is it k-fold where k=10 repeated k times?
Is it leave-one-out?
Is it a different method?
</code>

The crucial point here is less k-fold vs. LOO (though I'd usually recommend k-fold over LOO) but whether you split into independent sets of cases or not. If not, you can be subject to large overoptimistic bias, i.e. you then get a very bad estimation procedure.

Should the hyper-parameters be re-tuned for each round of k-fold cross validation?

Typically: yes. That is, as soon as any optimization driven by the data at hand is done, this must be re-done for every surrogate training set. It is actually part of the full training procedure.
Exception: if you fix the hyperparameters by knowledge that is entirely external to the data set at hand. E.g. if from analyzing, say, previous runs of experimental data, and decide to go with those hyperparameters without re-optimizing on the data at hand, you just use them and that's it.

In leave-one-out cross validation should one instance be left out from one class at a time, or both classes at the same time?

The term leave-one-out is normally defined to mean that in total one case is left out. However, you can use a "stratified leave-two-out" validation where from each class one case is left out. Whether or not I'd recommend one or the other depends on further circumstances. E.g.

How sensitive do you expect the model to be wrt. relative class frequencies? Then a stratified approach that strives to keep the relative frequencies correct may be better.
Are the relative frequencies of your classes representative for the application?
Are you in a situation where measuring model stability is crucial? This is not possible with LOO, but it becomes possible with iterated/repeated leave-2-out (or iterated/repeated k-fold CV)


Code into function with parameters

Question: I have a code
jQuery(function() {
  jQuery(".class1").each(function() {
    jQuery(".class2").hide("fast");
    jQuery(this).children("input").click(
      function() {
        if (jQuery(this).parent().hasClass('class3')) {
          jQuery(".class2").toggle("slow");
        } else {
          jQuery(".class2").hide("slow");
        }
      });
  });
});

How I can change it into a reusable function with parameters class1, class2, class3 to many usage ?
Comment: Do you need to learn how to make a function? I don't get it
Comment: Just make a function and pass the three _class_ as parameters.
Comment: I've tried do something to use this code like a function: inputshow('class1','class2','class3')  , where 'class1' etc. would be a real class for example, and code above use in many cases.
Answer: You can create a function where you make the class names parameters like so:
var exampleFunction = function(class1, class2, class3) {
  jQuery(class1).each(function() {
    jQuery(class2).hide("fast");
    jQuery(this).children("input").click(
      function() {
        if (jQuery(this).parent().hasClass(class3)) {
          jQuery(class2).toggle("slow");
        } else {
          jQuery(class2).hide("slow");
        }
      });
  });
}

and then call it like this:
exampleFunction('.class1','.class2','class3');

Answer: I would simply wrap your relevant code in a function like the below doSomething function, then from your wherever you want to call your function, you can do the following:
jQuery(function(){
    var class1 = jQuery(".class1"),
        class2 = jQuery(".class2"),
        class3 = "class3";

    // Reusable function doSomething
    doSomething(class1, class2, class3name);
});

function doSomething(class1, class2, class3name){
    class1.each(function() {
    class2.hide("fast");
    jQuery(this).children("input").click(
      function() {
        if (jQuery(this).parent().hasClass(class3)) {
          class2.toggle(slow);
        } else {
          class2.hide("slow");
        }
      });
  });
}

I used var in order to give the classes more meaning, however if you wanted something shorter you can call the function like so:
doSomething(jQuery(".class1"), jQuery(".class2"), "class3");

Answer: jQuery(function(){
    jQuery(".' + class1 + '").each(
    function() {
    jQuery(".' + Class1 + '").hide("fast");
        jQuery(this).children("input").click(
            function(){
                if (jQuery(this).parent().hasClass('class3')) {
                    jQuery(".' + Class2 +'").toggle("slow");
                } else {
                    jQuery(".' + Class2 +'").hide("slow");
                }
            });
    });
});

Code into function with parameters


Structured references: Keep names through copy-past

Question: So I'm using structured references for user data. Eventually we'll have a proper import procedure, but I was hoping to push that back to later and instead use copy-past of their raw data for now.
So I have a table, say tData, that contains a a copy of raw data output. That output already comes with headers, which are actually used in the structured references to the data throughout the workbook.
My problem is that the raw output isn't 100% stable - e.g. some columns may appear & go. Those aren't used in calculations, but it does affect slightly the table structure (position of columns). I can't control the raw output.
I was hoping to instruct them for now to copy-past directly. As I am working with the headers & not position, I thought the formulas would still work.
Summarize in the images below: =tTest[Column2] is the formula set for the box on the right. It should refer to the content of column2 (so 2). If I copy-past different headers, with "Column0" that shifts everything to the right, you can see that a positional reference is actually used by excel to refer to your data. It now returns "1" and Excel even changed the formula to "=tTest[Column1].

Seems wrong to me - e.g. if you reference something by name you don't expect it to actually be referenced by position.
I already tried tTest[[header]:[header]] and it doesn work either.
Comment: You could use INDIRECT I guess, =INDIRECT("tTest[@Column2]")
Comment: Interesting proposal - I was actually trying to make the reference a text but hadn't thought of INDIRECT.

I'll just check first to make sure I wouldn't loose flexibility - as this is more of a hack while waiting to have a proper import procedure. I'll get back to see what I do.
Answer: So, in the end, better write a proper import procedure I think. I won't post here because it's somewhat involved and there are various checks to perform. But overall steps are:

File picker to select the data to input
Copy everything into ThisWorkbook, close input file
Match the column headers from input data with mytable.HeaderRowRange
Copy the raw data into the appropriate column if match if found

So basically write a script to do a match on column headers, which is was I thought Excel would be doing. And still think it should do. However thinking about it, it is probably a lot simpler to code it this way than to have it actually dynamically adapt named references and not positions....
As mentioned by Bob Phillips, you can use INDIRECT. However that does involve adding an extra INDIRECT(reference_to_table_here) to, well, all references. Excel worksheet formulas are clunky enough I think without have to make them any clunkier.
Even though you write the formulas using column names, in the background Excel actually uses position of the column within your table for its calculations. Whenever you change the layout of the workbook, it updates the position for you.


php collect all the values that match a regular expression

Question: I tried to load a html file with values to replace, but first i want to get all of them... but preg_match_all always return NULL.
The result of "var_dump($htmlcontent);" :
string(643) "

        <input type="checkbox" name="solved" value="1" onchange="...">

    {{description}}
    {{solved}}

[...]
And:
$bla = preg_match_all( '\{\{(\w+)\}\}', 'bla {{ble}}', $dataToFill);

var_dump($bla); // bool(false)
var_dump($dataToFill); //NULL

and I don't know by. The regular expression works in all the online testers I tried, so, what's happends?
Comment: http://stackoverflow.com/questions/5589807/preg-match-unknown-modifier. You just need regex delimiters.
Comment: one hour looking for an answer and it was answered. But maybe with two similar questions the next find the answer faster. Thanks
Answer: You forgot to add delimiters to your regex.
$bla = preg_match_all('/\{\{(\w+)\}\}/', 'bla {{ble}}', $dataToFill);


Ukulele: G major chord with partial barre

Question: I am playing on a gCEA concert ukulele. As a relic of probably incorrect self-taught guitar playing (D major), I am faster to a G major chord by playing a partial barre chord. That's index finger on fret 2 across strings 2-3-4, and ring finger on fret 3 of string 3. The left thumb supports the partial bar on the backside of the neck.
Current fingering:

Since I'm pretty fast to get to this chord, and the tone is good, I'm finding it tough to break the habit and re-train myself with the proper fingering.
Correct fingering:

But my question is - will my current fingering inhibit my play in the future?
--
Similar to this question, but yet another fingering.
Comment: thanks @Tim. Switching to a partial barre means shifting the thumb behind the fretboard to support the chord, so although for my basic strumming it's ok, as I progress, I may want to break the habit now.
Comment: Who says what the 'correct' fingering is? What authority do they have? Play it how you like - if it doesn't inhibit the sound or moving from/to other chords, who's going to put you in the naughty corner?
Comment: That pretty well answers your question then.
Comment: Why would you need to shift your thumb?  It belongs behind the fretboard anyway, IMO.  I play a lot of bar chords on ukulele, and my thumb just stays back there, whether barring or not.
Comment: @BiscuitTaylor see, for example, tip1 here: https://ukuleletricks.com/improve-barre-chords-on-ukulele/ `To get the most leverage, ensure that the ball of your thumb is pressed firmly into the neck of the ukulele.`
Comment: Yes, but that tip doesn't just apply to barre chords.  I can't see any reason to ever put your thumb anywhere else.
Answer: It is probably a good idea to get confident with one fingering first. As you progress you can learn other variants. Your fingering of the G chord is for example practical, if you change from a G to a Gmaj7, you only need to lift the ring finger. If a song has a change from G to G6, the 3-finger-variant would allow you to lift only one finger to make the change.
I think it is beneficial to learn different fingerings and not restrict yourself to one. There is certainly not one right way to play a chord and the most important thing is that it sounds good.
Answer: Actually, this is a pretty good fingering option, all things considered!
The main reason why ukulele chord diagrams will almost always show the three-fingered grip is, practically speaking, tradition. Almost all ukulele players will learn the G chord in this way, so it's the logical default choice when one needs to demonstrate a universal way to play the chord.
With the traditional three-fingered grip, the player has more control over each individual note as a result of each finger fretting just one note. This can be used to play an open string momentarily by lifting one of the fingers, to apply the necessary force on the strings more efficiently (this makes it great for first-timers), and even to possibly leverage a bit of vibrato. This chord grip has the fingers angled back a bit rather than straight-on.
By partially barring at the second fret, one can keep that angle straight-on, which might be preferable in some circumstances. The remaining fingers can stretch farther down the fretboard than would otherwise be possible with the traditional grip as a result. Trills from the root to the major seventh are now possible, and going from G to Gmaj7 is now a breeze as pointed out in another answer. G7 and G6 still necessitate a full reposition of the hand, however.
One other thing speaking for the trad grip is that it forces one to play with three fingers. Not all chord grips can be played with two fingers or fewer, and at some point it will be necessary to learn chords that do require the sort of twist shape that the three-finger G uses. If you ever want to play a diminished seventh chord, for example, this muscle memory is going to be helpful.

Other options for a good G chord exist, even down in roughly the same hand position. One of my favourites is the barre-chord version 4232, which is a lot like the partial-barre. Fully barring the 2nd fret, use the fourth finger on the G string and the third finger on the E string. This shape is actually moveable, meaning it can be played anywhere on the neck, and it moves naturally to all sorts of notes and other common chords. Leave off the ring finger to turn it into a beautiful Gadd2 chord, for example.
Another famous option is the pinky G fingering, which is still 0232 but using different fingers: 3rd finger on the C string, 4th finger on the A string, and 5th finger (pinky) on the E string. This facilitates chord changes to G7 and E7, which can now be done without repositioning the rest of the hand. It's also good practice for more difficult chords which will use the pinky finger, and done higher on the neck it forms part of another moveable triad grip (as a demo, 1343 makes this an Ab chord).

I wouldn't go so far as to say that this particular chord fingering is going to inhibit one's playing in the future, unless one refuses to learn to use the third finger or something like that. However, I think it's worth taking some time to practice doing it the normal way even if one ends up sticking to the partial barre - you never know when it may come in handy, and it's good to have that kind of twisty chord under one's belt.


Best way to have bundled In App Purchases on IOS

Question: I'm working on an application had will have multiple In App purchases.  Lets say for example that we have items1 - items10 for sale, all non consumable.  We would also like to have "Bundles" of these items so Bundle1 has items1 - items5 in it. We want to have each item 1.99 but 5.99 for the group.  I looked around but I haven't seen if there is any protocol for handling this.  Is it even allowed?
What if the user has bought items2, are they still allowed to buy a bundle which also contains that item even though it would be cheaper than buying the rest individually?
If we had a separate IAP for the bundle it would make restoring more difficult, if they had bought a bundle, then try to re-buy one of the items individually, instead of apple telling them they already bought it, it would treat it as a new purchase.
Thanks for any insight.
Comment: Any followup on this? I'm in the same situation now.
Answer: I have implemented bundles in several apps and in all of them we have created a separate IAP productID for the bundles in addition to the individual item productIDs. This allows you full control over prices.
Then we just handle the activate/restore in the "provideContent:(NSString )productId receipt:(NSData)receipt" method. It is no more difficult to unlock multiple items as it is a single item.
We have not really worried to much about whether the user has already purchased an item that is in the bundle, or if they try to purchase something they already own. We pretty much leave it up to the user to keep that straight. If they want to spend their money, we let them.
You could always run a check before you submit the transaction to Apple to see if they already own the item and let them know.
Comment: Thanks, I guess if I handle all the restoring correctly then there shouldn't be much to worry about.