Differentiability in $\mathbb{R}^n$: how to prove that $f'(a)v=g'(a)v$ for all $v \in \mathbb{R}^m$?

Question: Let $f,g:U\to\mathbb{R}^n$ be differentiable at point $a\in U$, where $U\subset\mathbb{R}^m$ is an open set. Suppose $f(a)=g(a)$. Prove that $$\lim_{v\to0}\frac{f(a+v)-g(a+v)}{|v|}=0\;\;\;\;[\#]$$ if, and only if, $$f'(a)=g'(a)\;\;\;\;[*]$$
I've proved that $[*]\Rightarrow[\#]$ and I need help for the converse.

Definition: Suppose $U$ is an open set in $\mathbb{R}^m$, $f$ maps $U$ into $\mathbb{R}^n$, and $a\in U$. If there exists a linear transformation $T:\mathbb{R}^m\to\mathbb{R}^n$ such that $$f(a+v)-f(a)=Ta+r(h), \;\text{where}\; \lim_{v\to 0}\frac{r(v)}{|v|},$$ then we say that $f$ is differentiable at $a$, and we write $T=f'(a)$.

Thanks.
Comment: Don't you mean $f(a+v) - f(a) = T(h) + r(h)$? I think if you just subtract these expressions for $f$ and $g$, it should be obvious.
Answer: If $f$ and $g$ are differentiable at $a$, with $f(a)=g(a)$, then
$$f(a+v)-f(a)=\nabla f(a)\cdot v+O(\|v\|^2), $$
$$g(a+v)-g(a)=\nabla g(a)\cdot v+O(\|v\|^2),  $$
and so
$$f(a+v)-g(a+v)=\left(\nabla f(a)-\nabla g(a)\right)\cdot v+O(\|v\|^2),  $$
for all $v\in\mathbb R^m$ s.t. $a+v\in U$ (the for all is the important  missing part in the OP). But then
$$0=\lim_{v\rightarrow 0}\frac{f(a+v)-g(a+v)}{\|v\|}=\lim_{v\rightarrow 0}
\frac{\left(\nabla f(a)-\nabla g(a)\right)\cdot v+O(\|v\|^2)  }{\|v\|}, ~~(*)
 $$
which implies
$$q(a):=\nabla f(a)-\nabla g(a)=0 $$
by arbitrariness of $v$. In fact, you can choose $v=te_i$ in $(*)$, for all $i=1,\dots m $ s.t.  $a+te_i\in U$ and prove that all components $q_i(a)$ of the vector $q(a)$ are equal to zero.
Comment: So, can we say that $0=\lim_{te_i\rightarrow 0}
\frac{\left(\nabla f(a)-\nabla g(a)\right)\cdot te_i+O(\|v\|^2)  }{\|te_i\|}=\lim_{te_i\rightarrow 0}
\frac{\left(\nabla f(a)-\nabla g(a)\right)\cdot e_i  }{\|e_i\|}=\left(\nabla f(a)-\nabla g(a)\right)\cdot e_i $?
Comment: @Perguntador: with $t>0$ small enough (i.e. such that $a+te_i\in U$) you have $0=\lim_{t\rightarrow 0}\frac{t(\nabla f(a)-\nabla g(a))_i+O(t^2)}{t}=(\nabla f(a)-\nabla g(a))_i$. Do it for all $i$'s and you get the answer. Btw, in my notation, $e_i=(0,...,0,1,0,...,0)$.


How best to setup an acoustic guitar for multiple tunings?

Question: I like playing compositions in various tunings, and retune the guitar frequently. I only have one guitar, so that leads to two problems:

Strings tend to break (much) faster when tuned up, e.g. D to E.
Strings tend to buzz when tuned down, e.g. low E to C.

I realize that perhaps solving this problem in a professional setting may indeed require multiple guitars, but as an amateur I can compromise on many parameters as long as I can practice without excessive grief. So, what ways are there to solve these two problems?
Thanks!
Answer: There are a few aspects of your guitars setup that make it not ideal to have to switch tunings. My personal instrument (bass) can take many tunings to a point as the strings are more robust, but you end up with a few issues around the action (the angle of the neck relative to the body, which causes the fret buzz), the nut width and possibly the bridge setup. It's not really ideal, and it's less important for me as chords aren't a concern. There's generally a way around whatever I'm trying to do. I play guitar less, but have run into the same problem.
My guitar strings are a lot more temperamental than my bass ones simply because they are thinner and have a lot lower tolerence for changes in tuning. I know you ruled out a second guitar, as ultimately that is the best solution, but you are trying to cover an awful lot of ground on one guitar. On guitar the only change I'll really do is low E->D as anything beyond that affects the tension and tonality too much. On bass I tend not to, but have been known to go down a semitone on the lowest string if I really feel I need the extra range.
I find changing the tuning too much can affect my playing as the patterns on the fretboard shift. If you're happy with moving the tunings to play then I would suggest:

I know you ruled it out, but for the large range you're trying to cover a really cheap second guitar would reduce the strain on strings constantly being retuned, provide a potentially better setup for a different tuning and save you time constantly retuning while practising. If you get two you can cover more ground and have strings specifically for higher or lower tunings. A professional musician will have loads obviously, but for £60 you can get a guitar just to practise on, with a more serious instrument if you need it. It won't be best quality, but may save you money long term with the strings you'll be buying constantly by increasing/decreasing tension.
Failing that I'd tend towards strings that are lighter than a middle ground. Whilst having strings too loose isn't ideal I would say it's more optimal than trying to increase the tension beyond what they are designed for. You do have to be careful of not damaging your current guitar as the neck won't be that happy with constantly changing tuning.
Without knowing the songs you're playing/writing it's hard to say, but possibly look at playing chords elsewhere on the neck and staying in one tuning. If you're covering songs they may sound different so that's your decision to make.

Ultimately, there's nothing wrong with retuning constantly, however in your case the amount of ground you are trying to cover is quite large, which is what will cause problems.
EDIT
Just a quick update as I checked what I have on my bass on the moment as an example. I have strings of gauge 35, 55, 70, 90 (If I remember rightly) tuned to EADG. I prefer really light strings for ease of bends (yes, on bass...) and slap bass, but it does mean I won't be able to drop the tuning too far. What I mean about the setup is that the action and such is set up for these very thin strings, and trying to drop the tuning will make them far too loose to play properly and will sound dreadful.
For comparison I also have a really old bass on BEAD tuning. The thicknesses there are something like 75, 95, 110, 130 (they're really old so can't remember exactly). I would not want to push them into higher tunings really as they are already pretty tight. I don't really play this one that much. I might change it to DADG or something instead as I rarely use C# or lower.
This means my two different basses have totally different actions, bridge settings and the second has an adjusted nut to accout for the thicker strings. Rather than trying to have one bass in the middle to try and cover both it's far easier to have two. The first is a (soon to be replaced) Fender P Bass and the second a cheap Ibanez BTB200, and realistically I never gig with the BTB.
This is quite a bass-heavy answer, so I texted my guitarist mates to see what they said. One generally doesn't change tuning, but has a cheap second guitar (his first one that got replaced recently) if he really needed to. Another doesn't go far enough from EADGBE to really need a second, but he does drop the low E to a D occasionally. He prefers to use a capo and find other ways of playing the chords. He said he would like to, but the second guitar would have to be gig-worthy. He often uses weird tunings on an accoustic to experiment though.
The basics of setup will carry over from bass, but I'm aware alot of these tunings are based on the open string notes, which I avoid at all costs on bass unless truly necessary, having lots of song specific tunings are perhaps unecessary. Hopefully there is some use to be found in all this.
Comment: Regarding gauge: lighter strings buzz less? But will break more easily? Or is it the other way around? Regarding tunings, I'm playing other people's compositions, so I'm stuck with very strange tunings like CFCGAE, or tunings that tune B to C, G to A and D to E (while the other strings will actually be tuned down). And then there's good ol' DADGAD.
Comment: Lighter strings won't want to be tuned as low as they will have to be insanely loose to get the pitch right - leading to more fret buzz. Overtightening them will causing them to break more easily. The issue isn't the amount of tunings, but the difference between the top end and bottom end. With a second guitar you would be putting less stress on the strings by having them closer to optimum tension, as well as having less variation from that.
Comment: So for tuning down I'd want thicker strings, and for tuning up - thinner strings?
Comment: Yup, that's exactly right. For the same tension a thinner string will produce a higher pitch (relation of thickness to frequency of oscillation).
Answer: As far as the strings breaking, that's just going to happen.  The strings we use are designed for a certain amount of tension and when they are tuned up the increased tension leads to easier breakage.  Heavier gauge strings will have higher tension also.  So a lighter gauge may be helpful for you if you've been playing heavy ones but it will change your tone, though lighter strings break easier so it may not help.
For the buzz you could try a few things.  If you adjust your truss rod to give you a little more action it could alleviate the buzz but you don't want to adjust to the point that the action is too high as it can affect intonation and playability.  If there are only certain strings that buzz (probably the lower ones) you could try to raise the bridge.  That would work better if you have individual bridge saddles as you can fix one string without it affecting all the others.  You could also try propping the string up at the bridge or the nut to gain the extra action on an individual string.
Answer: The best way is to obtain another guitar and have different gauge strings on each - lighter for the higher tunings and heavier for the lower. You are asking for a racehorse and a carthorse to do the same job. As you've already found out, it won't work.It will also be kinder to each guitar as the necks won't have to put up with differing tensions.Why you would want to tune up, I can't see. If you have a particular favourite non-standard tuning, you need to address the gauge of each individual string - if one is permanently lower, go up a gauge or two, and vice versa. This way, the tension across the neck will be similar to that of a standard tuned guitar.The instrument will thank you for this in the long run.
Comment: As to why would I want to tune up: Rylynn by Andy McKee is ECDGAD, for example. As for gauges: by "going up a gauge" do you mean having a lower gauge, i.e. thinner strings (just making sure I understand)?
Comment: A higher gauge = thicker string.Thinner string = lower gauge.
Answer: Adding to Folau's answer, I've heard that there are certain types of string that will last longer too.  By this I mean there's a difference between nickel/steel strings, and bronze strings.
Personally I use Earnie ball cobalts and love them, but someone else will be able to give a more detailed rundown of what types last better.
Comment: I'd have to ask my guitarist - as a bassist who has always used the same type I don't know, but it could easily be true based on tensile strengths of different compositions.
Answer: This is an area of much interest to me so if I may share my thoughts and experience which is a lot years of still trying to figure it out .
Multiple guitars would be the best answer and each would have to be set up a accordingly. I play acoustic and use many open tunings though not many on the high side .
A open C is what I am using as of right now on a Epiphone master built dr500 . fret buzz and intonation is always a battle . One thing I found is no one guitar is equal but build is everything.
You can set the action by controling the Nut and bridge heights fairly easily enough but neck set not so easy and very so important for the style of your music.
I had an old Yamaha 312fg 12 string when I had it set up neck set was part of it. fret buzz was minimal and action was .. best guess 3/32" at the 12th fret or less. hard to believe but true. It handled my open tunings like a dream but i wanted new , a thinner neck , electronics so I sold her.
Things you might also try , sting gauge, I believe one post said to up the gauge when you go low and lighter when higher . and that's dead on but what you might need is a custom set . I have 3 G strings tuned so I need to match the g string if I tune the B to open G its to floppy with a set 56's so by upping B the string to two G's It helps out . but the multi tuning will be a night mare if you change tunings across the board like you say. Also matched string gauges tend to loose character between each other ... See more stuff to figure out ! LOL
if your talking acoustics the best thing to right off is find the right guitar that can best handle your tunings and then work from there and also find a great Luthier not a good one a great one to talk about neck sets .. you'll be surprised how many guitars are not set right from the factory.
Good luck ,hope to hear what you find out in your search.
Ags
Answer: If anyone is familiar with Kevin Cadogan and his work on the debut self-titled album by Third Eye Blind, then you know that half of those songs are in alternate tunings (at least 3 variations of open d suspended, as well as tuning to different hz, i.e. semi charmed life is in A448 to sound brighter).
Kevin recorded most of those guitar tracks with his MusicMan guitar that was "set-up" for various tunings.  I don't know the details of what he or his techs did to achieve stability across the different tunings, but it is my understanding that he preferred that guitar so much that the set it up for a middle-ground setting, which accommodated the action/range parameters of detuned strings as well as the brighter standard set ups.
I imagine they changed the strings (type/gauge etc.) for each song, but the hardware of the guitar remained unchanged.  many of the overdubs were done with a different guitar (a gibson RD artist I think) but those lead-oriented overdubs were less concerned with open string harmonics and other intonation issues.
So there is some hope that you can achieve this with one guitar, but I personally tried it on my Strat and it was quite impressive how it remained intonated relatively well (the floating bridge helps with this neck flexibility).   But recently I was able to purchase some cheaper electrics and permanently set them for those open tuning songs, and it's much better that way, so work toward that.
If you'd like to research Cadogan's open tunings some more, check out GearSlutz page featuring producer Eric Valentine commentary on 3eb's debut album.  He is also generously responsive to facebook private messages, just try to be concise.
Good luck!
-michael


Edge browser support

Question: Any idea if we have an official support for Edge browser using watir-webdriver api? I am able to launch Edge browser with a sample script, but I am not able to interact with elements. I tried the following code and it's failing to set the text field.
<code>require 'watir-webdriver'
$browser = Watir::Browser.new 'edge'
$browser.goto('http://www.google.com')
$browser.text_field(:name => 'q').set "hello"

Error:
C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/response.rb:73:in `assert_ok': status code 501

(Selenium::WebDriver::Error::ServerError)
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/http/common.rb:78:in `new'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/http/common.rb:78:in `create_response'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/http/default.rb:90:in `request'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/http/common.rb:59:in `call'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/bridge.rb:664:in `raw_execute'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/bridge.rb:642:in `execute'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/bridge.rb:229:in `switchToDefaultContent'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/common/target_locator.rb:100:in `default_content'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/browser.rb:346:in `assert_exists'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/elements/element.rb:561:in `ensure_context'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/elements/element.rb:545:in `locate'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/elements/element.rb:505:in `assert_exists'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/user_editable.rb:32:in `clear'
        from C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/user_editable.rb:11:in `set'
        from test.rb:6:in `<main>'
</code>
Comment: `Any idea if we have an official support for Edge browser using watir-webdriver api.` - That seems more like a support question for the watir developers. It may be better to reword this as just a question asking why your code isn't working in Edge.
Answer: In Selenium 2.48, there is an issue using the Ruby bindings (which Watir does) with Edge via the remote server. This issue has been fixed, but won't be available until Selenium 2.49 is released.
It is also worth noting that Microsoft WebDriver for Edge is still a little buggy, so you would likely be getting various other errors if you were not getting the error you are currently getting. :)

Edge browser support


Plotando circulos em diferentes planos

Question: Eu necessito plotar circulos nos planos zy e zx, mas só consigo no plano xy, pois ao trocar de lugar as variaveis x, y e z, perdo o formato de corculo. Como posso consertar isso?
import numpy as np
from matplotlib import pyplot as plt
import mpl_toolkits.mplot3d.axes3d

theta = np.linspace(0, 2.*np.pi, 100)
phi = np.linspace(0, 2*np.pi, 100)
theta, phi = np.meshgrid(theta, phi)
c, a = 1, 0.05
x = (c + a*np.cos(theta)) * np.cos(phi)
y = (c + a*np.cos(theta)) * np.sin(phi)
z = a * np.sin(theta)

fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
ax1.set_zlim(-10,10)
ax1.plot_surface(x, y, z, color='b', edgecolors='b')
ax1.view_init(36, 26)

plt.show()

Answer: Vc deve zerar a coordenada do eixo que não quer que apareça o circulo. Por exemplo, se vc deseja plotar o circulo no plano zy, então
ax1.plot_surface(xzero, y, z, color='b', edgecolors='b')
onde xzero é um vetor de zeros ([0,0,0,..]) com a mesma dimenssão de y e z.
A mesma coisa vc faz para os demais planos.
Comment: Deu certo, obrigada! agora só falta eu conseguir plotar na coordenada que eu determinar :)

Plotando circulos em diferentes planos


Genie effect ipad

Question: Does anyone know is there iPad implementation for Genie animation line on MAC OSx? I would like to create some list on the left side and on an action to make "like OSx" Genie animation to animate moving detail section into list item (like minimizing windows on MAC to the dock icon)
Thanks!
Comment: I've never heard of one. There's probably a way to do it, but it's not really in-line with Apple's normal design guidelines for iOS. And any from-scratch implementation will be pretty processor intensive or require something like openGL.
Answer: The simplest implementation I've found is BCGenieEffect (https://github.com/Ciechan/BCGenieEffect). Not only is the README extremely easy to understand, the actual implementation is just a few lines. Here's an example (found on their README) that displays how to do this simply:
<code>CGRect startRect = CGRectMake(30, 40, 50, 60);
[view genieOutTransitionWithDuration:0.7
                           startRect:startRect
                           startEdge:BCRectEdgeLeft
                          completion:nil];
</code>
I just used this in a project and it seems very reliable.
Answer: There is this option. There are many stackoverflow posts about this topic, the standard effect uses private API, but can be found here.

Genie effect ipad


Download Manager - setting file extension without hardcoding

Question: I want to download a file which can be of any extension, using a url which does not contain the file type. Hardcoding the file type will not work here.
Uri downloadUrl = Uri.parse(link);
DownloadManager.Request request = new DownloadManager.Request(downloadUrl);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(true);
request.setTitle(title);
request.setDescription(description);
request.setVisibleInDownloadsUi(true);
request.setMimeType("application/pdf");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subDirectory);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
if (downloadManager != null) {
    downloadManager.enqueue(request);
}

Answer: Try this:
File file=new File(getExternalFilesDir(null),"Dummy");
/*
Create a DownloadManager.Request with all the information necessary to start the download
*/
DownloadManager.Request request =
    new DownloadManager.Request(Uri.parse("YOUR URL"))
       .setTitle("Dummy File")// Title of the Download Notification
       .setDescription("Downloading")// Description of the Download Notification
       .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)// Visibility of the download Notification
       .setDestinationUri(Uri.fromFile(file))// Uri of the destination file
       .setRequiresCharging(false)// Set if charging is required to begin the download
       .setAllowedOverMetered(true)// Set if download is allowed on Mobile network
       .setAllowedOverRoaming(true);// Set if download is allowed on roaming network

then:
DownloadManager downloadManager=
    (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

// enqueue puts the download request in the queue.
downloadID = downloadManager.enqueue(request);

for complete example see the link.


login connection problem using SimpleTest

Question: I am using SimpleBrowser from SimpleTest (http://www.simpletest.org) to login a webmin (http://www.webmin.com/). This login uses https. I've tried two different ways, both fail.
<code>$browser = new SimpleBrowser();
$browser->useCookies();
$browser->useFrames();
//echoes the login page, where it should echo the landing page from a logged user
echo $browser->post('https://address/','user=User&pass=Secret'));
</code>
And also :
<code>$browser = new SimpleBrowser();
$browser->useCookies();
$browser->useFrames();
$browser->get('https://address/');
$browser->setField('user', 'User');
$browser->setField('pass', 'Secret');
//echoes the login page, where it should echo the landing page from a logged user
echo $browser->clickSubmit('Login');
</code>
Do you have any clue why it doesn't work ?
Comment: Correct user/pass values. The setField lines return true, hence these fields have been successfully field.
Comment: The login page (before login) and the logged page (after login) have the same address.
Answer: Make sure if you have installed php_openssl.dll extension in your PHP.


Qual a melhor forma de enviar dados action(formulario) ou submit do jquery?

Question: Existe hoje algum padrão para enviar dados de formulário? Usar jquery e eliminar o  action(formulario) ou validar com jquery e enviar os dados usando action(formulario).
Comment: Provavelmente essa pergunta será fechada, pelo fato de não está clara o suficiente e por ser ampla demais. Tente explicar melhor o problema em si, o que tentou e o que pretende fazer.
Comment: marconi, Eu quero enviar dados para outra pagina. qual a melhor forma de fazer? usando o jquery ou usando action do formulário.
Comment: Não existe a melhor forma. Isso pode varias de cada aplicação e necessidade. Eu por exemplo gosto muito de utilizar jQuery e passar os dados serializados. Mas se for necessário enviar de outra forma eu envio!
Answer: Não existe uma melhor forma mas no caso de envio de um formulário é prudente usar o action form porque se o usuário tiver qualquer erro em relação ao Javascript (ex: javascript desativado) será impossível enviar seu formulário.


What mode or scale does Hans Zimmer dwell on in Dune?

Question: I was listening to the Dune soundtrack just now as background music, and I noticed that it felt very modal. It keeps using the following series of intervals:
wholestep-halfstep-wholestep-halfstep-wholestep
This definitely isn't major, minor or any of the church modes, but I assume Hans Zimmer is not by any stretch the first person to do this. Is there a name for this arrangement of notes?
Comment: I haven't heard the soundtrack, but just looking at those intervals, they'd match part of the ascending harmonic minor scale, starting from the submediant. For example, in C minor that's A B C D Eb F.
Comment: Perhaps relevant: https://songexploder.net/dune
Comment: Good catch, gidds. He does them both upward and downward, if I remember correctly.
Answer: Maybe an answer to whole/half etc.:
The whole/half diminished scale. It uses eight notes in steps of alternating tone and semitone intervals. There is a sister to this - the half/whole diminished, which uses the obvious opposite.


AWS Glue & Crawler for Hierarchical Avro file

Question: We have a use case to read Hierarchical Avro file whose Schema would change dynamically during ingestion. I am aware that for flatten file we can use Crawler to read the metadata and create a schema out of it , however I would like to know whether crawler can read the schema out of a Hierarchical file and refresh the Glue ETL job. Please share you thoughts on this.
Thanks !!
Answer: Glue crawlers can read the hierarchical schema and can be used in Glue job dynamically


Retrieving JavaScript function's parameters of every webpage through addon

Question: I want to display javascript function's parameters of every webpage through my addon. the below javascript code is my addon code. i am using internal function hooking mechanism.
<code>hookEval = eval;
eval = function (str)
{
   console.log("evals "+str);
   return hookEval(str);
}

hookWrite = document.write;
document.write = function (str)
{
   console.log("write"+str);
   return hookWrite(str);
}
</code>
The above code is displaying the parameters of java script functions in firefox and opera console, but in IE, sometimes it is displaying and most of the times nothing its displaying.
Why the above code is not working in IE?
Edit:console.log is working fine in ie9. it is not the problem.
Answer: I'd say this provides some information.  Console.log is problematic in IE.  There is also the issue of overwriting a builtin javascript function.  Not sure IE likes that.  That's just a guess though.  I've not researched it.
Comment: Don't consider console issue. i am aware of console issue. and i am using ie9 with console.


Replicate distribution image kurtosis

Question: I am trying to replicate one of the images from this post.
In particular I want to plot something similar to this image in matlab:

I.e. I  want these three differently peaked distributions, where the tails are very clear. Can someone help me with such a plot?
Code as of now:
<code>y = normpdf(x,0,1);
plot(x,y)
y1 = tpdf(x,5);
hold on
plot(x,y1)
hold on
y2 = tpdf(x,1000)
</code>
Comment: It's always a good idea to explain what software you are using, here I think MATLAB,  A $t$ distribution with 1000 df will be hard to distinguish from a normal distribution and does not in any case have lower kurtosis. A more basic pitfall for e.g. a $t$ distribution with 5 df has variance 5/3 compared with your normal which has variance 1.  Hence a graph conflates different kurtosis and different variance, although that problem is soluble by scaling by SD.
Answer: The referenced post and graphic are misleading because they suggest that kurtosis somehow measures height and/or pointiness/flatness of the distribution, notions which have been thoroughly debunked. Rather, kurtosis is a measure of tailweight (or more specifically tail leverage), see https://stats.stackexchange.com/a/481022/102879 for a good place to start.
It is important to visualize the heaviness of the tails, but the standard histogram/density plot is inadequate for this purpose: The tails, even when heavy, are too close to zero to distinguish "light" from "heavy" in such graphs.  Instead, you can use the normal quantile-quantile plot. Tail heaviness is very easy to see in this plot, and there is a direct mathematical connection between the appearance of this plot and the kurtosis statistic.  See here: https://stats.stackexchange.com/a/354076/102879
Comment: A log scale for density can help too.

Replicate distribution image kurtosis


How to prevent "Mysql2::Error: This connection is in use by" with Sidekiq

Question: After running Sidekiq for a couple of hours, I see a bunch of jobs fail with Mysql2::Error: This connection is in use by: #<Celluloid::Thread:0x0000000d1b56e0 sleep>. Seems the Sidekiq threads are somehow conflicting over the MySQL connection pool.
concurrency is set to the default 25 in sidekiq.yml and the pool is 28 in database.yml. There are no long-lived queries and the exceptions happen in standard finder calls, nothing fancy.
How can I prevent this error to ensure jobs run smoothly?
Comment: what server are you using? unicorn? this is happening on development or production?
Comment: It's an independent Sidekiq processor server. Yes, production.
Comment: are you using this DB only for this workers? because if you are using the same DB for another process you'll need to see how many connections your DB is getting
Comment: No, it's used by the Rails app server too (which works fine), but I'm assuming the error is talking about another thread within the Sidekiq process.
Answer: Your problem is caused because sidekiq is getting all connections to your DB and at the same time the rails app is also requesting the connections.
You have 25 sidekiq workers but how much rails servers do you have?
e.g. if you have unicorn running 4 child workers you'll need 29 slots (at least)
Comment: The database.yml pool variable reflects connections per process, so each Unicorn also has 28 connections here. (Actually they only need 1, but it's not a problem in practice as they don't use more and don't live long.) Since Unicorns aren't having any DB problem, it's not because of contention with them. (They're also on a different machine.)
Comment: but they share the same DB, it doesn't matter about in which machine they are, and the pool is not per process is per DB
Comment: Say I have 4 Unicorns. That means there's actually (max) 125 connections. Not 28.
Comment: 4 unicorns + 25 sidekiq = 29 slots for you DB pool, they are slots for your DB, not for each process
Comment: The pool variable means how many connections per process, and there are 5 processes here, so that's 125 possible connections. (The 28 is arbitrary, it could have been 25, but I've left some excess just in case of race conditions and there's some hints at https://github.com/mperham/sidekiq/issues/503 that it should be about 1.5x the # of processors even though it should theoretically be identical.)
Comment: did some research, how much connections your DB can make? if the DB is set to accept less connections that you make then you'll have some problems
Answer: Finally fixed this by isolating all the workers. It came down to Typhoeus library apparently not being thread-safe. Replaced with Net/HTTP and it works again.
Some more details at https://github.com/mperham/sidekiq/issues/1400#issuecomment-45838886
Answer: In our case, we had a lot of these errors in a specific worker type. We identified that we were using Timeout.timeout() calls in one of the jobs running in these workers. We removed those calls and these errors went away after that. For some reference as to why Timeout.timeout() calls are dangerous, please look here and here.


What is the longest winning streak in tennis with a player not dropping a single game

Question: Saw these past few days that in the Australian Open 2013 Sharapova went two matches without dropping a single game. I'm wondering if there is any official record on the longest streak of sets/matches a player played without dropping a single game.
Comment: [What is the record for most consecutive games won?](http://www.menstennisforums.com/showthread.php?t=165570) at manstennisforums.
Comment: Wikipedia articla on [wiinning streaks](https://en.wikipedia.org/wiki/Winning_streak_(sports)#Tennis) lists this record:
Most consecutive game wins (men): 25 games - 1993 Sergi Bruguera,
However, no reference is given there. And no record for women's tennis is listed there.
Comment: Bill Tilden won 57 straight in 1925. Source: *A terrible Splendour,* p.128.
Answer: What better place to start looking than to find the one of the most dominant player in tennis ever - Esther VERGEER
:)
I found this link and just did a quick scan (there could be longer ones I was hasty) and found from

2009 Invacare World Team Cup - Women's Event    27 Jul - 02 Aug 2010(I am guessing it's 2009 not 2010 possible typo by the web admin part)

to

Mercedes Open  Utrecht, Netherlands  04 Aug - 09 Aug 2009

She went

eleven sets (five and half matches) without dropping a single game.

Of course this was only a quick search not an official one. Lets see how long this stand :)
Comment: If the field is limited to wheelchair women's singles then it's a pretty good opinion :)
Comment: @user1655072 She didn't loose a single match in more than 10 years. She retired this month, with 470 consecutive wins (see wiki page)
Comment: I'm sure Esther Vergeer, "the most dominant player in tennis ever," is merely an opinion (and not to say I disagree). Otherwise, good work with the research and let's see if anything else comes in.
Comment: If Vergeer's matches meet the criteria then I'd say that's the answer for sure. I'm positive nobody in professional men's or women's tennis has gone 11 sets without losing a game. No way.
Comment: Quora: [Which athlete dominated his or her sport for several years?](http://www.quora.com/Which-athlete-dominated-his-or-her-sport-for-several-years?share=1)
Answer: For questions like this, one possible approach is to make a community-wiki answer, where several users can contribute if they find some relevant records.
Grand Slams - Men

Sergi Bruguera won his second round match at 1993 French Open 6-0, 6-0, 6-0. He won also his first round match in straight sets and he won the third set 6-0. From these results alone we can see that he won at least 25 consecutive games. (Four bagel sets in a row and the last game in the preceding set.) Bruguera went on to win the tournament.
Karel Nováček won his second round game at 1987 French Open 6-0, 6-0, 6-0. He also won his first round match in the straight sets and he won the last set of that match 6-0. This means winning at least 25 games in a row.

Grand Slams - Women

Maria Sharapova won her first two matches at 2013 Australian Open 6-0, 6-0. In the third round she won the first four games in the match against Venus Williams. (Sources: 1.) Which makes it 28 consecutive games in total. (Australian Open was her first tournament in 2013. She lost her last match in 2012.) See also: Once In A Lifetime For Sharapova at WTA website; Australian Open 2013: Maria Sharapova hands out heavy defeat to hapless Venus Williams - The Telegraph.
Wendy Turnbull won 6-0, 6-0 in the first two rounds at 1985 French Open. She lost in the third round 3-6, 4-6 to Hana Mandlíková. This means at least 24 consecutive games and at most 27 consecutive games. (She lost her last match at the preceding tournament in Sydney. See here.)

Useful links

Wikipedia article Shortest tennis match records lists triple bagel games (double bagel for women) at Grand Slams. However, these lists may be incomplete.


Vuetify: How to set v-data-table row height manually?

Question: How to set <v-data-table> row height manually ?
Setting the table to dense is some small enough for my needs.
By default, $data-table-dense-row-height is set to 32px !default;
Answer: Check this codesandbox I made: https://codesandbox.io/s/stack-70697036-bo4yx?file=/src/components/TableExample.vue
If you don't want to mess with SASS variables, or modify the value globally you can use the item-class prop of the v-data-table like this:
<v-data-table
   :headers="headers"
   :items="desserts"
   :items-per-page="5"
   class="elevation-1"
   :item-class="setRowStyle"
>
</v-data-table>

You need to define a function to be able to apply css to the hole item row.
methods: {
   setRowStyle(item) {
      /* Here you can also do some validation
      in case you want to apply different css
      classes depending on item attributes
      values */
      return 'style-1'
   }
}

And then you simply defined the css you want to be apply to your data-table rows:

If you want to use a scoped css style block, you'll need to defined your css using deep selector to properly apply the height to td tags.

If you also want to modify the row headers height, you can use the class attribute in your headers array.


Increase performance inorder to refresh the whole page without using Ajax

Question: Is it possible to increase the performance inorder to refresh the whole page using  javascript without using Ajax ? Can we maintain some caching or other technique to speed up the page refresh process ?
Comment: Yes it is possible. Browsers do cache pages by default. Let us know what specific problem you are facing. Generic questions are unanswerable and no one pays heed to them here.
Answer: Not sure what exactly you mean by refreshing the page, but something like this can be achieved through JavaScript only without AJAX.
Assume you have two section in your page. Contents of second section are dependent on value selected in section one but the variation is definitive. In that case you may want to load all the variation of second section and keep them hidden in the page. Once done, then based on the events in first section, you can just show/hide corresponding details in second section.
One common example of this scenario could be: List of countries and List of States example. Say you want to display the list of states if country is selected as US/Canada etc. and for rest of the countries, you want to display a free text field. In this scenario, you may pre-load the list of US states and list of Canada states and keep them hidden. Once user select any country, your can display the related states list/field in the UI. All in client side.


Simple problem from category theory

Question: The problem is to prove that for given initial object $X$ and any object $Y$ there is exists canonical isomorphism of $X+Y$ with $Y$, where $X+Y$ means coproduct in category under consideration. It is clear that I just have to draw diagrams (universal property of coproduct), but I can't get the answer from it so far.
Answer: The only obvious morphisms you can think of are $id\colon Y\to Y$ and the unique morphism $X\to Y$. Now check that they satisfy the universal property of the coproduct $X\sqcup Y$.
Answer: The coproduct comes with inclusions $i_1\colon X\to X+Y$ and $i_2\colon Y\to X+Y$.
You also have distinguished morphisms from $X$ and $Y$ to $X$. By universal property of the coproduct they give a morphism $f$ from $X+Y$ to $X$.
Now you should compute the compositions of $i_1$ and $f$.

Simple problem from category theory


How many different structures of Jordan forms in $M(n,\mathbb{C})$?

Question: The possible Jordan forms  for $n \times n$ matrices in $\mathbb{C}$ can be found if we know  that the characteristic polynomial is:
$$
p(x)=(x-\lambda_1)^{k_1}(x-\lambda_2)^{k_2}\cdots (x-\lambda_m)^{k_m}
$$
for $1\le k_i\le n$ and
with $k_1+k_2+\cdots+k_m=n$.
So, taking all possible partitions of $n$ we have different normal forms with different possible Jordan blocks, whose structure depends on the minimal polynomial and from the dimension of the generalized eigenspaces.
My problem is to find the number of such different forms of Jordan matrices for a fixed $n$ (note that I'm not interested on the actual value of the eigenvalues but only whether the eigenvalues in two blocks are equal or not).
I found many questions  that asks essentially the same for special or general cases, but not a complete answer.
With a bit of work, using the possible forms of the characteristic and minimal polynomials, I foun $6$ possible forms for $n=3$ and $15$ forms for $n=4$ (if my work is correct), but  I don't see a method to extend this result to a general case and the work of count all possibilites becomes really tedious  if $n$ increase (clearly the result depends by the multiplicity of the eigenvalues in the characteristic and minimal polynomial).
There is some general result?

I found a possible answer here, but I don't agree with the result, so I submit my work to the scrutiny of Math-stackexchange.
The idea is that the number of different Jordan blocks is ''the partitions of the partitions''.
Fo $4\times 4$ matrices this means that we start from the paritions of  the integer $n=4$ that are the $p(4)=5$ partitions:
$$
4,\quad 3+1, \quad 2+2, \quad 2+1+1, \quad 1+1+1+1+1
$$
These are the possible factorizations of the characteristic polynomial:
the partition $4$ correspond to the polynomial $(x-a)^4$,
$3+1$ corresponds to the polynomial $(x-a)^3(x-b)$
$2+2$ correspond to $(x-a)^2(x-b)^2$
$2+1+1$ corresponds to $(x-a)^2(x-b)(x-c)$
$1+1+1+1$ corresponds to $(x-a)(x-b)(x-c)(x-d)$
Now we take a second partition for any of such partitions that indicate the possible dimensions of the generalized eigenspace corresponding to an eigenvalue. So:
for $(x-a)^4$ we have $p(4)=5$ possibilities, i.e. the eigenspaces of dimension $4, \quad 3+1,\quad 2+2,\quad 2+1+1,\quad 1+1+1+1$
these numbers are the dimension of the Jordan blocks and  correspond to the matrices:
$$
\begin{bmatrix}
a&1&0&0\\
0&a&1&0\\
0&0&a&1\\
0&0&0&a
\end{bmatrix}
\quad
\begin{bmatrix}
a&1&0&0\\
0&a&1&0\\
0&0&a&0\\
0&0&0&a
\end{bmatrix}
\quad
\begin{bmatrix}
a&1&0&0\\
0&a&0&0\\
0&0&a&1\\
0&0&0&a
\end{bmatrix}
\quad
\begin{bmatrix}
a&1&0&0\\
0&a&0&0\\
0&0&a&0\\
0&0&0&a
\end{bmatrix}
\quad
\begin{bmatrix}
a&0&0&0\\
0&a&0&0\\
0&0&a&0\\
0&0&0&a
\end{bmatrix}
\quad
$$
for $(x-a)^3(x-b)$ we have the $p(3)\cdot p(1)=3$ possibilities : $(3,1), \quad (2+1,1),  \quad (1+1+1,1)$ with the matrices:
$$
\begin{bmatrix}
a&1&0&0\\
0&a&1&0\\
0&0&a&0\\
0&0&0&b
\end{bmatrix}
\quad
\begin{bmatrix}
a&1&0&0\\
0&a&0&0\\
0&0&a&0\\
0&0&0&b
\end{bmatrix}
\quad
\begin{bmatrix}
a&0&0&0\\
0&a&0&0\\
0&0&a&0\\
0&0&0&b
\end{bmatrix}
$$
for $(x-a)^2(x-b)^2$ we have $p(2)\cdot p(2)=4$ possibilities: $(2,2),\quad (2,1+1),\quad (1+1,2),\quad (1+1,1+1)$,
with matrices
$$
\begin{bmatrix}
a&1&0&0\\
0&a&0&0\\
0&0&b&1\\
0&0&0&b
\end{bmatrix}
\quad
\begin{bmatrix}
a&1&0&0\\
0&a&0&0\\
0&0&b&0\\
0&0&0&b
\end{bmatrix}
\quad
\begin{bmatrix}
a&0&0&0\\
0&a&0&0\\
0&0&b&1\\
0&0&0&b
\end{bmatrix}
\quad
\begin{bmatrix}
a&0&0&0\\
0&a&0&0\\
0&0&b&0\\
0&0&0&b
\end{bmatrix}
\quad
$$
for $(x-a)^2(x-b)(x-c)$ we have $p(2)\cdot p(1) \cdot p(1)=2$ possibilities : $(2,1,1),\quad (1+1,1,1)$, with matrices
$$
\begin{bmatrix}
a&1&0&0\\
0&a&0&0\\
0&0&b&0\\
0&0&0&c
\end{bmatrix}
\quad
\begin{bmatrix}
a&0&0&0\\
0&a&0&0\\
0&0&b&0\\
0&0&0&c
\end{bmatrix}
$$
for $(x-a)(x-b)(x-c)(x-d)$ we have only one possible matrix
$$
\begin{bmatrix}
a&0&0&0\\
0&b&0&0\\
0&0&c&0\\
0&0&0&d
\end{bmatrix}
$$
So I find a total of $15$ possible Jordan block forms. And this is the problem, because the reference gives , for $n=4$ a total of $14$ forms, and this is the number indicated in the referred A001970 sequence.  Where is my mistake?
Comment: Are your $2,1+1$ and $1+1,2$ really different?
Comment: I think @ancient has it right. There's no way to distinguish $a$ from $b$, so those two are indistinguishable, so that's how to get 14.
Comment: I think it's one of these cases where one has to be very very careful about what counts as different. The way @EmilioNovati poses the question (the actual set of distinct ev is a given) perhaps leads to 15, but the canonical count (only worrying about ev being same or different) leads to 14.
Comment: If $a$ and $b$ are different, then the Jordan blocks $[a]$ and $[b]$ are not similar, so there's an uncountable infinity of Jordan forms for $n=1$. I don't think we want to go there, Emilio.
Comment: I hope that now the question is well posed.
Comment: To be absolutely clear, are the $\lambda_i$ assumed to be distinct?
Comment: No. If they are distinct the answer is simple. The question is interesting if the algebraic multiplicity of one or more eigenvalues is $>1$.
Comment: Sorry, I meant are $\lambda_1,\dots, \lambda_m$ distinct, not are the roots of the char ploy all distinct.
Comment: Yes, I suppose that we have $m\le n$ different  eigenvalues, each with its multiplicity.
Comment: You don't say so, though.
Comment: One more query: can you do the simpler problem, "Find all JCF's corresponding to a given characteristic polynomial" ?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/76059/discussion-between-emilio-novati-and-ancientmathematician).
Comment: Related to some degree https://math.stackexchange.com/questions/2705064/how-many-patterns-of-decreasing-matrix-rank-exist
Comment: Thank you @Widawensen. I added something to my question from  another related question.
Comment: @ancientmathematician: thank you for the comments. From a combinatorial point of view I can agree with the subtle difference from the two case, but if the two eigenvalues $a$ and $b$ are different, the two matrices with the Jordan block of dimension $2$ for $a$ and for $b$ are not similar, so, if  we  want to enumerate the different and not similar forms these are $15$.
Comment: So, what do you think, Emilio?
Comment: @ancient: Your comments was useful ! Now I understand and I agree that the correct sequence is A001970 . If someone write an answer, I suppose that can be useful also for other users (and I can accept).
Comment: @GerryMyerson: thank you .... and the same comment  for you help :)
Comment: Let me encourage you, Emilio, to write up and post an answer yourself, now that you've come to understand.
Answer: The short answer is that your counting is not really consistent. You distinguish the cases $(2,1+1)$ and $(1+1,2)$ but consider cases like $(3,1)$ and $(1,3)$ as the same. Because $4$ is so small this is the only "exception", but for larger dimensions it becomes a problem.
A slightly longer answer is this. There are at least two things which one can count.
(A) Given some $n$ and $k\leqslant n$, and distinct $\lambda_1,\dots,\lambda_k$
one can count how many conjugacy classes of $n\times n$ matrices there are which have eigenvalues $\lambda_1,\dots,\lambda_k$ (and no others).
I think this is close to your original question.
If one does this one has to distinguish in the $n=4$, $k=2$ case, between $(1+1,2)$ and $(2,1+1)$. But one also has to distinguish between $(3,1)$ and $(1,3)$, etc.
(B) More generally one can also count the number of "shapes" of Jordan forms. It's usually more useful, I think, and one can get the answers to (A) from this.
To make precise what it is that we are counting, again fix $n$, and consider the set $\mathcal{J}$ of all Jordan forms of $n\times n$ matrices. Now  $\text{Symm}(\mathbb{C})$, the group of all permutations of $\mathbb{C}$, acts on $\mathcal{J}$ in the obvious way, by acting on each diagonal element of a Jordan matrix. Formally what we count is the number of orbits of $\text{Symm}(\mathbb{C})$ on $\mathcal{J}$.
In this case, since we can swap any pair $a\not= b$, we must not distinguish between $(2,1+1)$ and $(1+1,2)$.


How to solve npm "UNMET PEER DEPENDENCY"

Question: I am having issues with my package.json file.
It should work fine as as I use most of the node modules in other projects, but I have this package.json below:
"dependencies": {
   "@angular/common": "^2.0.0-rc.1",
   "@angular/compiler": "^2.0.0-rc.1",
   "@angular/core": "^2.0.0-rc.1",
   "@angular/platform-browser": "^2.0.0-rc.1",
   "@angular/platform-browser-dynamic": "^2.0.0-rc.1",
   "@angular/router": "^2.0.0-rc.1",
   "angular2-in-memory-web-api": "0.0.7",
   "bootstrap": "^3.3.6",
   "es6-shim": "^0.35.0",
   "reflect-metadata": "^0.1.3",
   "rxjs": "^5.0.0-beta.6",
   "systemjs": "^0.19.27",
   "zone.js": "^0.6.12"
 },
  "devDependencies": {
    "body-parser": "^1.15.1",
    "express": "^4.13.4",
    "jsonwebtoken": "^6.2.0",
    "mongoose": "^4.4.15"
  }

and they should all run fine as all dependencies exist as angular is now in rc.4 and rxjs is on 5.0.0-beta.10.
But I get 3 unmet dependencies on
npm install
'firstname.lastname@example.com'
'firstname.lastname@example.com'
'@email@example.com'

I get these warnings too:
npm WARN @email@example.com requires a peer of email@example.com but none was installed.
npm WARN @email@example.com requires a peer of firstname.lastname@example.com but none was installed.
npm WARN @firstname.lastname@example.com requires a peer of @firstname.lastname@example.com but none was installed.

I have also done:
npm cache clean
npm update registry > with the registry link
npm update -g

node is on latest version and still same issue... so just wondering if there is something wrong?
Comment: remove everything, start installing rxjs first, then other packages
Comment: @MedetTleukabiluly i will try that soon thanks
Answer: I think its because the dependency resolution is a bit broken, see https://github.com/isaacs/npm/issues/1341#issuecomment-20634338
You may need to manually install top-level modules that have unmet dependencies:
npm install email@example.com
Or structure your package.json such that any top-level modules that are also dependencies of other modules are listed lower down.
Your problem could also be that npm failed to download the package, timed-out or whatnot. Sometimes re-running npm install remedies it.
You can also install the failed packages manually as well using npm install
Other steps that may help before attempting npm install again are:
Removing node_modules using:
rm -rf node_modules/
then
npm cache clean
To explain why removing node_modules sometimes is necessary:
Apparently if a nested module fails to install during npm install, subsequent npm install won't detect those missing nested dependencies. If that's the case, sometimes it's sufficient to remove the top-level dependency of those missing nested modules, and running npm install again.
See https://github.com/npm/npm/issues/1336


Integrate Mockito with CDI

Question: I'm currently thinking about expanding unit tests for a server and a client application. Mockito is already in use and - I think - very well suited for the task at hand. However, as the Mockito documentation itself admits:

Mockito is not an dependency injection framework, don't expect [the @InjectMocks annotation] to inject a complex graph of objects be it mocks/spies or real objects.

The server-side of course already has CDI via annotations at some places, the client will probably be extended in some place to use CDI for JavaSE in the near future. There is/will be a wild mix of field- and constructor-injection + @postconstruct methods, which is already too complicated for Mockito. So I'm looking for something that will allow me to easily use CDI annotations to inject Mockito's mocks/spies/real objects where needed.
Can Mockito's functionality be expanded via plugins or something similar to enable a dependency resolution closer to what is specified by CDI (I don't think I need the full spec, but something closer to it)? Is there another library that integrates with Mockito and JUnit5 that does that?
Comment: Actual CDI has no place in unit tests. You can use CDI for a more integrated test (eg Spring Integration Tests), but then you start the full context as far as possible in order to test the interaction between the real components. At the "border" of the system, you can use `@MockBean`s.
Comment: CDI can have a place. Of course not for injecting the true dependencies production code would use. That has no place in unit tests as you rightly said. But what I want is different: I want mostly mocks and spies injected (and very rarely actual objects, but those I could do by hand if I need to). Mockito does this to some extend on its own, but it's not very flexible in doing that, e.g. it can't mix constructor injection and field injection. Doing it by hand can require writing a lot of boiler plate code (for example package-private setters for injected fields that are only used in tests)
Comment: If you need to inject a lot, you should reconsider your design, as it's a sign of too many dependencies. As a side note, you should not need to use spies (["real spies should be used carefully and occasionally, for example when dealing with legacy code"](https://www.javadoc.io/doc/org.mockito/mockito-core/1.10.19/org/mockito/Mockito.html#13)). If you have an example where you need to inject and Mockito falls short, post it.
Comment: Well, yes, "my" design leaves a lot to be desired. It's a couple of million lines of legacy code that has very poor coverage by the existing tests. It would be nice if I could write tests without too many rewrites of the production code and without endlessly adding boilerplate code to the test classes so that I can write more tests for the existing code. The less time I need for each individual test, the more tests I can write during the little breaks between bigger issues. Making a massive refactoring effort will honestly be necessary in the future, but for now it's not feasible.
Comment: "_Making a massive refactoring effort will honestly be necessary in the future, but for now ..._". Also known as _St. Nimmerleinstag_ in German. ;)
Answer: weld supports this out of the box, specifically by weld-junit. It supports both junit4 and junit5. In both cases one can define producer methods for the required injection points in which one can freely use mockito or powermock or any other mocking mechanism to create mocks which weld then injects into the test object.
Answer: If you wish to mock EJB/CDI beans with OpenEJB, you can do it very easily:
http://tomee.apache.org/master/examples/rest-applicationcomposer-mockito.html
Answer: cdi-unit and ioc-unit have modules which support that.
Just add
<code>@Produces
@Mock
ClassName mockedObject;
</code>
and the framework will make it an injectable Bean.

Integrate Mockito with CDI


Could anyone help me check my gibbs sampling code?

Question: I am now trying to write a Gibbs Sampling code based on the posteriors from a paper "Bayesian Regularization via Graph Laplacian", writer: Fei Liu, et.
When I run the code, it always show the error:
Error in eta_ii[i] = rinvgauss(n = 1, mean = mu_eta_ii, shape = a^2) :
object of type 'closure' is not subsettable

Does anyone know why? Or does anyone do this paper's gibbs sampling before?
Thank you very much!
Here is my code:
 library(pscl)
  library(MASS)
  library(statmod)
p=ncol(x)
n=nrow(x)
In=diag(1,nrow=n,ncol=n)

#STEP1. generate variance from the posterior distribution
      #p(var|lamda,D)~Inverse Gamma(n/2,y'(In-X(X'X+rlamda)^-1X')y/2)
variance=function(lamda,X,Y){
var=rigamma(n,n/2,t(Y)%*%(In-X%*%solve(t(X)%*%X+r*lamda)%*%t(X))%*%Y/2)
mvar=mean(var)
return(mvar)
}

#STEP2. generate beta from the multivariate normal distribution
 #here I am not very sure about the meanninng of y_tuter
beta=function(var,lamda,X,Y){
mu_beta=solve(t(X)%*%X+r*lamda)%*%t(X)%*%Y
sg_beta=var*solve(t(X)%*%X+r*lamda)
beta=mvrnorm(n=n,mu_beta,sg_beta)
mbeta=colMeans(beta)
return(mbeta)
}

#STEP3. generate the sign of the lamda:c, based on the binomial dist
 signC=function(beta,var,X,Y){
   P=matrix(1,ncol=p,nrow=p)
   C=matrix(1,ncol=p,nrow=p)
   for (i in 1:p){
     for(j in 1:i){
       P[i,j]=1/(1+exp(-r*b*(abs(beta[i]-beta[j]-abs(beta[i]+beta[j]))/2*var))
       C[i,j]=rbinom(1, 1, P[i,j])
       if (C[i,j]==0){
         C[i,j]=-1
       }
       C[j,i]=C[i,j]
       if(i==j){
         C[i,i]=1
       }
     }
   }
   return(C)

 }

  #STEP4. generate the eta which is from the product of independent inverse

  Gaussian dists
 #1. for the eta_ii
 eta_ii=function(var,beta){
 mu_eta_ii<-c()
 for(i in 1:p){
  mu_eta_ii=a*var*(abs(r^0.5*beta[i]))^(-1)
  eta_ii[i]=rinvgauss(n=1,mean= mu_eta_ii, shape=a^2)
  }
 return(eta_ii)
 }

#2. for the eta_ij
 eta_ij=function(C,var,beta){
   eta_ij=matrix(1,ncol=p,nrow=p)
   for(i in 1:p){
     for(j in 1:i){
       mu_eta_ij=b*var*(abs(r^0.5*(beta[i]+C[i,j]*beta[j])))^(-1)
       eta_ij[i,j]=rinvgauss(n=1,mean= mu_eta_ij, shape=b^2)
       eta_ij[j,i]=eta_ij[i,j]
       if (i==j){
         eta_ij[i,j]=1
       }
     }
   }
  return(eta_ij)
 }

  #STEP5. get the new lamda
 new_lamda=function(C,eta_ii,eta_ij){
   lamda=matrix(1,ncol=p,nrow=p)
   for (i in 1:p){
     for (j in 1:i){
       lamda[i,j]=C[i,j]*eta_ij[i,j]
       lamda[j,i]=lamda[i,j]
       if(i==j){
         lamda[i,j]=eta_ii[i]
       }
     }
   }
   return(lamda)
 }

 #After generate new parameters, we can replace the hyperparameters:r,a,b
 #set the value for gz,hr,gb
 ga=0.01
 hr=0.01
 gb=0.01

 #get the new r:GAMMA dist
 hyper_r=function(a,b,C,beta,var){
  shape=p/2+hr
  rate_p3=matrix(0,nrow=p*(p-1)/2,ncol=1)
  for (j in 1:p){
   for (i in 1:j){
      if(i<j){
          rate_p3[j-1]=(b/(2*var^0.5))*abs(beta[i]+C[i,j]*beta[j])
             }

                  }
               }

     rate=sum(beta*beta)/(2*var)+a*sum(abs(beta))/(2*var^0.5)+sum(rate_p3)

     r=rgamma(1,shape=shape,rate=rate)
      return(r)
       }

       #get the new a:exponential
       hyper_a=function(r,beta,var){
       rate=r*sum(abs(beta))/(2*var^0.5)
      a=rexp(1,rate=ga+rate)
       return(a)
        }

     #get the new b:exponential
     hyper_b=function(r,beta,var,C){
    rate_p2=matrix(0,nrow=p*(p-1)/2,ncol=1)
    for (j in 1:p){
      for (i in 1:j){
       if(i<j){
        rate_p2[j-1]=(r/(2*var^0.5))*abs(beta[i]+C[i,j]*beta[j])
        }

        }
      }
     b=rexp(1,rate=gb+rate_p2)
     return(b)
      }

       #start the Gibbs Sampler
      ga=0.01
      hr=0.01
     gb=0.01

       r=1
       a=1
       b=1
   sigma=diag(1,nrow=8,ncol=8)
    for (i in 1:8){
        for (j in 1:8){
          sigma[i,j]=0.7^abs(i-j)
                     }
                   }
      x<-mvrnorm(n=20, rep(0, 8),sigma)
      error<-rnorm(20,mean=0,sd=3)
      y<-3*x[1]+2*x[2]+1.5*x[3]+error

    lamda<-solve(cor(x))

    p=ncol(x)
    n=nrow(x)
     In=diag(1,nrow=n,ncol=n)

     VAR<-c()
       BETA<-matrix(0,ncol=p,nrow=2)

    burnIn=20
    for (m in 1:2){

  var<-variance(lamda,x,y)
  VAR[m]<-var
  beta<-beta(var,lamda,x,y)
  BETA[m,]<-beta
  C<-signC(beta,var,x,y)
  eta_ii<-eta_ii(var,beta)
  eta_ij<-eta_ij(C,var,beta)
  lamda<-new_lamda(C,eta_ii,eta_ij)
  r<-hyper_r(a,b,C,beta,var)
  a<-hyper_a(r,beta,var)
  b<-hyper_b(r,beta,var,C)

}

Comment: This is off topic here. It belongs on [codereview.SE].
Comment: @gung Code Review requires code that works (as far as the asker knows), so this does not belong there, either.
Answer: In the function eta_ii, you attempt to use the value eta_ii as a vector by using the bracket notation to assign values to its entries.  Essentially you do this:
f <- function(x) {
  for(i in 1:x) {
    f[i] <- i
  }
  return(f)
}

If I call this function, I get the same problem:
> f(2)
Error in f[i] <- i : object of type 'closure' is not subsettable

Breaking down this error message:
object of type 'closure': "closure" is a synonym for "function" in R error messages.  So this is referring to f.
is not subsettable: Subsetting is what you are doing when you use a [.
So altogether this is saying I don't know how to use a [ on f.  Are you sure that's what you want?.  It's probably not what you want.
Reusing variable names in the way your code does is a very bad practice.  R is quite permissive in this aspect, but it probably shouldn't be, because the practice is confusing and unpredictable.  I would take some time to think hard about what you are naming things, you will thank yourself for doing so in the future.  You also have many issues with indentation and formatting, though that may be an artifact of copying and pasting.  Again, I would advise care and caution with your code formatting, it will help you immensely when you enter debugging mode.


SQL clustering without WSFC (Windows Server Failover Clustering)

Question: Is it possible to cluster, or make SQL "highly available" without having to pay the huge enterprise prices?
By the looks of it, any type of SQL clustering requires enterprise edition Windows Server. We have a small mom and pop shop that just wants the database to automatically fail over if any issues arise, without any user intervention required, as the IT company is about an hour away.
I know you can use SQL Standard edition for a 2-node cluster, but do you need Windows Server Enterprise to get WSFC?
Answer: I believe the latest versions of Windows Server to support Failover Clustering on Standard Edition - namely Windows Server 2012, and Windows Server 2012 R2.


Likelihood Function is Minimal Sufficient

Question: What does it mean to say that "Likelihood Function is Minimal Sufficient"? Is this a general statement, or does it apply to only exponential family of distributions?
I think I understand the concept of sufficient statistics, and minimal sufficient statistics.
Likelihood Function on the other hand is a function of the parameter with data plugged-in. We cannot calculate its value without knowing the parameter. It is different than say "sample mean" statistic for the mean parameter of a Normal distribution, which yields a concrete number. How is this a statistic then?
Then there is this lecture note, on section 2
http://www.stat.cmu.edu/~larry/=stat705/Lecture6.pdf
where Prof. Wasserman gets philosophical about the issue which confused me even more.
Comment: For some reason, the link takes you to the wrong lecture notes.  The current links for notes on sufficiency and the likelihood function can be found: https://www.stat.cmu.edu/~larry/=stat705/Lecture10.pdf and https://www.stat.cmu.edu/~larry/=stat705/Lecture11a.pdf
Answer: Consider an observable data vector $\mathbf{x} = (x_1,...,x_n) \in \mathscr{X}$ with a joint-distribution that is indexed by the parameter $\theta \in \Theta$.  It is possible to establish that "the likelihood function is minimal sufficient" in a sense described more specifically below.
Your misgivings here occur because you say that the likelihood is a function that depends on the parameter, and so we cannot calculate its value without the parameter.  (This presumably means that it is not even a statistic, let alone a minimal sufficient statistic!)  What you point out is true, but it misses the point, because the result asserted in your question is not that the value of the likelihood function at a particular point is minimal sufficient, but that the function is minimal sufficient.  We will see below that when we talk about minimal sufficiency of "the likelihood function" we are really referring to the latter in its broadest sense, as a function of the data vector and the parameter.

Some preliminary notes on what a function is and is not: Before we get to the likelihood function, it is worth noting some general mathematical aspects of functions that are glossed over in early schooling, but which become important once you begin to study higher mathematics.  In general, a function $f$ is a mapping from a domain $\mathscr{X}$ to a codomain $\mathscr{Y}$.  To stress this meaning, we sometimes write the function as $f: \mathscr{X} \rightarrow \mathscr{Y}$.  If we take any point $x \in \mathscr{X}$ then we can obtain the corresponding value of the function $f(x) \in \mathscr{Y}$ at this point.  Nonetheless, there is a difference between the value $f(x)$ and the function $f$ --- they are not the same mathematical object.
In fact, it is possible to consider the function itself as a point in a larger function-space.  Specifically, we can form the space $\mathscr{Y}^\mathscr{X}$ which contains all possible functions from the domain $\mathscr{X}$ to the codomain $\mathscr{Y}$, and we then have $f \in \mathscr{Y}^\mathscr{X}$ --- i.e., the function $f$ is a point in the function-space $\mathscr{Y}^\mathscr{X}$.  Since the function can be considered as a point and the function value at a particular input can also be considered as a point, you can now see the distinction in these things more clearly --- for any $x \in \mathscr{X}$ the value $f(x)$ is a point in the space $\mathscr{Y}$ but the function $f$ is a point in the function-space $\mathscr{Y}^\mathscr{X}$ (which is typically a much larger space).
In high school mathematics, this distinction is sometimes glossed over with an abuse of notation by introducing functions with like this: "Let $f(x)$ be a function of $x$ with such-and-such properties...".  In that context, the $x$ is treated as "generic" and so the object $f(x)$ is treated as a notation for the entire function, and not just its value at a particular point.  Most mathematics textbooks used in high schools use this kind of notation/terminology, so there is no notational effort made to distinguish the function itself from its value at a particular point (though these are sometimes distinguished in the prose).  At university level (undergraduate and postgraduate) most mathematics textbooks now begin to bring this distinction into the notation --- they start saying things like "Let $f$ be a function..." instead of "Let $f(x)$ be a function...".  This is to get you used to the idea of distinguishing a function from its value at a particular input point, which becomes an important distinction in various higher mathematical results.

The mapping from the support of the data to the likelihood function is a sufficient statistic: For a particular observed instance of the data vector $\mathbf{x}$, the likelihood function is the mapping $L_\mathbf{x}: \Theta \rightarrow [0, \infty)$.  It is a mapping that maps each value of $\theta$ to a real output, but the function itself is fixed by the specified value of $\mathbf{x}$ and the domain $\Theta$.  (This is just an instance where we have to be careful to distinguish a function from its value at a specific argument value.)  Now, let $\mathscr{T} \equiv [0, \infty)^\Theta$ be the space of all mappings from the parameter space $\Theta$ to the non-negative real numbers.  For each data vector $\mathbf{x} \in \mathscr{X}$ there is a corresponding likelihood function $L_\mathbf{x} \in \mathscr{T}$, and so we may consider that there is a mapping $T: \mathscr{X} \rightarrow \mathscr{T}$ that maps each possible observable data vector onto its corresponding likelihood function (i.e., we have $T(\mathbf{x}) = L_\mathbf{x}$).  This mapping is "the likelihood function" in its broadest sense, where we have not yet specified the observed data vector.
You can see that this function $T$ is a mapping from the domain of possible data vectors to a fixed codomain, so it is a statistic.  This is the sense in which we can consider the "likelihood function" to be a statistic.  That is, the "likelihood function" can be considered as a statistic, if we have not yet specified the observed data vector (so that it is a function of this data vector), and we are looking at the object as a function of the parameter, rather than looking at an outcome value that accrues from a particular parameter value.  With this elaboration, we now understand that the function $T$ is "the likelihood function" in this broadest sense.

Theorem 1: The function $T$ is sufficient for $\theta$.
Proof: For all $\theta \in \Theta$ we define the function $g_\theta : \mathscr{T} \rightarrow \mathbb{R}$ by $g_\theta(f) = f(\theta)$.  Using the fact that the likelihood function is proportional to the sampling density, we can write the sampling density as:
$$\begin{equation} \begin{aligned}
f_\theta(\mathbf{x})
&= h(\mathbf{x}) L_\mathbf{x}(\theta) \\[6pt]
&= h(\mathbf{x}) g_\theta(L_\mathbf{x}) \\[6pt]
&= h(\mathbf{x}) g_\theta(T(\mathbf{x})). \\[6pt]
\end{aligned} \end{equation}$$
This establishes the Fisher-Neyman factorisation, which establishes the theorem.  $\blacksquare$

Demonstrating minimal sufficiency: The above mapping $T$ is a sufficient statistic, but it is not generally minimal sufficient for $\theta$.  To ensure minimal sufficiency, we need to narrow things down further than this, since the likelihood function is defined non-arbitrarily only up to proportionality.  For this reason, if we want to get minimal sufficiency, we will need to consider two proportionate likelihood functions $L_\mathbf{x}$ and $L_{\mathbf{x}'}$ to be "the same" function.  In the linked lecture notes, you will see that this is done by defining an equivalence relation $\sim$ as follows:
$$\mathbf{x} \sim \mathbf{x}'
\quad \quad \quad \quad\iff \quad \quad \quad \quad
L_\mathbf{x} \propto L_{\mathbf{x}'}.$$
This equivalence relation says that two likelihood functions $L_\mathbf{x}$ and $L_{\mathbf{x}'}$ are "the same" when proportionate.  It induces a corresponding partition on $\mathscr{X}$ that separates the observable data vectors into sets that yield "the same" likelihood function (in the sense of proportionality).

Theorem 2: The partition $\sim$ is the minimal sufficient partition for $\theta$.

This theorem is left as an exercise in the linked lecture notes.  Proof can be done by first establishing the sufficiency of the partition (which is assured by Theorem 1 above), and then showing that if you coarsen the partition, sufficiency is lost.  Since this is set as an exercise in the notes for the current question, I will not prove the result here.  Hopefully the above information gets you started, and more clearly establishes the statistic that you are dealing with.
The fact that the likelihood function (conceived as a statistic) is minimal sufficient, really should not be surprising.  Indeed, it is practically a tautology, since sufficiency can be framed as a condition in terms of the likelihood function.  Sufficiency means that the statistic captures all the required information about the indexing parameter.  Since the likelihood is proportional to the sampling density, it is hardly surprising that it does this.  Minimal sufficiency means that it does so without additional information, which is easily achieved by partitioning down to a level where the statistic/partition of interest is set by proportionality to the likelihood function.
The reason for the importance of minimal sufficiency is that every minimal sufficient statistic induces the same partition induced by the equivalence relation on the likelihood function.  This means that every minimal sufficient statistic is a stand-in for the equivalence relation induced by proportionality of the likelihood function.
Comment: Since the minimal sufficient partition is unique, it means that every minimal sufficient statistic induces the same partition induced by the equivalence relation on the likelihood function.  In short, every minimal sufficient statistic is a stand-in for the equivalence relation induced by proportionality of the likelihood function.
Comment: Nice answer. Is there a particular importance of the fact that likelihood function is minimal sufficient?
Answer: There's an unobservable parameter, or a tuple of such parameters. Call it $\theta.$ The value of the likelihood function $L$ at $\theta$ is $L(\theta)$ and is similarly unobservable. It is not a statistic, let alone a sufficient statistic.
When it is said that the likelihood function $L$ is a minimal sufficient statistic, what is meant is not that the unobservable value $L(\theta)$ of the likelihood function at some unobservable value $\theta$ of the parameter is a minimal sufficient statistic, but rather that the function $L$ as a whole is a minimial sufficient statistic. The function $L$ is observable, in that you know which function it is, after computing it based on the data.
That it is a sufficient statistic means that for any two values $U,$ $V$ of the data, if the likelihood function given observations $U$ is the same as that given $V,$ then the conditional distribution of the data given which function $L$ is, is the same if the observed data are $V$ as if they are $U.$
Comment: @Xi'an : For a family of distributions parametrized by finitely many scalar parameters, there is only a finite-dimensional space of possible likelihood functions.
Comment: @CowboyTrader : You're not using the word "sample" correctly. You should write of the size of the sample, which is the number of observations in the sample, rather than of the "number of samples".
Comment: With my limited knowledge of mathematics, I would say a function is some sort of infinite dimensional vector. From this perspective how is it a minimal sufficient statistic, when obviously we have in many cases finite dimensional sufficient statistic at hand?
Comment: @CowboyTrader : To say that a sufficient statistic $S$ is minimal means that for every sufficient statistic $T,$ the value of $S$ is determined by the value of $T$. It's not a matter of dimension.
Comment: Don Fraser (Toronto) has been arguing since 1960 that indeed the likelihood function is sufficient but I have the same issue with a _function_ being an infinite dimensional object.
Comment: I see. With this definition it makes sense. I was confused because in some texts they talk about reduction rate from the total number of samples(which is sufficient by default) to the dimension of minimal sufficient statistics. Can you also elaborate on Wasserman's criticism?
Comment: @CowboyTrader : Which parts of the linked document by Wasserman are you asking me to elaborate on? I'm a bit surprised that he seemingly recommends the estimator $$ \frac {\sum_{j=1}^N c_j S_j}{N\pi}$$ instead of $$ \frac{\sum_{j1}^N c_j S_j}{\sum_{j=1}^n S_j},$$ since the latter has a smaller variance.
Comment: The discussion about likelihood not containing information, and being unable to use it to estimate this parameter. I mean if it is sufficient statistic why can't we build an estimator with it?
Comment: @CowboyTrader : I think the part about the likelihood function in the survey sampling problem is not explained very well, and after looking at it more closely I am somewhat suspicious of that part. The observed data are $(c_1 S_1, \ldots, c_N S_n).$ The unobservable parameters are $(c_1,\ldots,c_N).$ The likelihood function is therefore $$ \begin{align} (c_1,\ldots, c_N) \mapsto L(c_1, \ldots, c_N) & = \Pr(X_1=c_1S_1\ \&\ \cdots\ \&\ X_N=c_NS_N) \\ \\ & = \pi^{S_1} (1-\pi)^{1-S_1} \cdots \pi^{S_N} (1-\pi)^{1-S_N} \end{align} $$
Comment: Well yes he concludes that the parameters(c_i or a function of them theta)  are not in the likelihood function. So how do you estimate their average from this likelihood now?
Comment: @CowboyTrader : I suppose I'd better mention this: I said I'd use $\dfrac{\sum_{j1}^N c_j S_j}{\sum_{j=1}^n S_j}$ rather than $\dfrac{\sum_{j1}^N c_j S_j}{N\pi}$ because it has a smaller variance. But the probability that the numerator and denominator are both $0$ is positive. I've never thought about defining "variance" in such a case. But I'd still probably use that estimator instead.


Logic Based Mathematical Teaser

Question: Every professor in the math department is a truthteller (always tells the truth) or a
liar (always says false statements). Five professors make the following statements:
•Alice: "If I am a liar, then so is Bob".
•Bob: "If I am a liar, then so is Carol."
•Carol: "If I am a liar, then so is Dave."
•Dave: "If I am a liar, then so is Eve."
•Eve: "If I am a liar, then so is Alice."
What is the largest number of them that could possibly be liars?
I am really having trouble with this problem and can't seem to get anywhere. I would appreciate some help.
Comment: Hint: you can't have consecutive liars.
Comment: This kind of situation comes up all the time in my department... it's annoying... :)
Comment: Hint: Assume that one of them is a liar. Then assume the other, and the other, and so on.
Comment: Write $A$ for "Alice tells the truth" (so $\neg A$ means "Alice is a liar"), and similarly for $B, C, D$ and $E$. The five statements are equivalent to: $A \lor \neg B $,  $B \lor\neg C $ ,  $C \lor\neg D $ ,  $D \lor\neg E $ and  $E \lor\neg A $. Then, for example, if Alice is a liar then $A \lor\neg B $ is false so Bob tells the truth, and then Carol **could** be also a liar, etc.
Answer: Since we can't have two consecutive liars because then the first liar's statement would actually be true, so the maximum number of possible liars is two. Since Alice and Carol being liars makes it work, the maximum number of liars is two.
Comment: Because Dave and Eve are telling the truth, their statements are true vacuously.
Comment: So it is possible to have two consecutive truth tellers? Wouldn't one of them need to be lying?

Logic Based Mathematical Teaser


Unit Vectors Problem

Question: Not sure how to solve this at all...

If $\widehat{a}, \widehat{b}, \widehat{c}$ are 3 unit vectors such that the measure of the angle between $\widehat{a}, \widehat{b}$ equals that between $(\overrightarrow{a}\times \overrightarrow{b}) , \overrightarrow{c} = \theta$ . Prove that $$(\overrightarrow{a}\times \overrightarrow{b}) \cdot \overrightarrow{c} = \frac{1}{2}\sin (2\theta )$$
Comment: Do you know any trig identities with $\sin(2\theta)$ in them?
Answer: You have $$(a\times b)\cdot c=|a\times b||c|\cos \theta=|a||b|\sin\theta|c|\cos\theta=\sin\theta\cos\theta=\frac 12\sin2\theta$$

Unit Vectors Problem


Problems installing composer on 1and1 shared hosting

Question: I t's my first time to a laravel web application on 1and1. For my dependances i need composer but i can't install it.
This is what i made.
    I create the following folders bin/composer
    then i install composercurl -sS https://getcomposer.org/installer | php7.1

Result: `X-Powered-By: PHP/7.1.12
Content-type: text/html; charset=UTF-8
All settings correct for using Composer
Downloading...
Composer (version 1.6.2) successfully installed to: /homepages/11/d715566175/htdocs/bin/composer/composer.phar
Use it: php composer.phar

    When i usephp composer.phari got these errors:
X-Powered-By: PHP/4.4.9
Content-type: text/html

Parse error:  syntax error, unexpected T_STRING in /homepages/11/d715566175/htdocs/bin/composer/composer.phar on line 95

Even php -v returns4.4.9`
Need your helps
Thanks
Comment: Try to upgrade php
Answer: Your default PHP which you call with php refers to an old version of PHP . Try php7.1 composer.phar.
Answer: For me it was
/usr/bin/php7.4-cli composer.phar -v


UIWebView ignores inline anchor/link

Question: I'm using a UIWebViewthat loads HTML from a database string using webView.loadHTMLString(self.htmlContent, baseURL: nil)
The htmlContent contains the following:

    1. Inline Test Link

    2. Inline Test Link

  ...

... and later in the HTML:
...

...

However, whenever I click the inline link in the webView nothing happens.
What I've tried so far:

Changing the anchor tag to 'real' valid W3C HTML. E.g. Test
Saving the HTML to a file in the temp directory and loading it using loadRequest(). E.g. let path = tempDirectory.URLByAppendingPathComponent("content.html") and webView.loadRequest(NSURLRequest(URL: path))
Intercepting the loadRequest method by implementing the func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool delegate. The request.URL says something strange like: "applewebdata://1D9D74C2-BBB4-422F-97A7-554BCCD0055A#parsys_47728"

I don't have any idea anymore how to achieve this. I know from previous projects that local HTML files in the bundle work with inline links. I just cannot figure out why this doesn't work.
Help much appreciated! Thank you!
Comment: Could you recheck that `webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool` returns `true` for your request? If yes you could change URL scheme from `applewebdata` to `file` just for debugging and test it.
Answer: If there's a fragment (e.g., #anchorName), then use JavaScript to scroll.  Otherwise, assume it's a link without a fragment and use openURL.
// UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType == UIWebViewNavigationTypeLinkClicked ) {
        // NSLog(@"request.URL  %@",request.URL); // e.g., file:///.../myApp.app/#anchorName
        NSString *anchorName = request.URL.fragment; // e,g, "anchorName"
        if ( anchorName ) {
            [webView stringByEvaluatingJavaScriptFromString:[NSString swf:@"window.location.hash='%@';",anchorName]];
            return NO;

        } else { // assume http://
            [[UIApplication sharedApplication] openURL:[request URL]];
            return NO;
        }
    }
    return YES;
}

I'm still looking for a way to have the scroll position change smoothly (animated) rather than jumping.
Comment: fragments can exist on internal or external links. If it is external you probably want to attempt to follow the link instead of using javascript to find the corresponding anchor tag. How do you tell if the link is external if the baseURL basically doesn't exist because the scheme is "applewebdata://" followed by a guid referencing a local file?

UIWebView ignores inline anchor/link


How to use a Perl global hash

Question: I'm having a problem with Perl. It's giving me an error that I don't understand.
This is my program
our $neighbor = {};

$$neighbor{'a'} = 'b';

print Dumper($vizinho);

sub keyboard{
    my ($a,$b) = @_;
    return 4 if ($a eq $b);
    return 2 if $neighbor{$a}{$b};
    return -1;
}

And my error is
Variable "%vizinho" is not imported at t/DistStr.t line 30.
Global symbol "%vizinho" requires explicit package name at t/DistStr.t line 30.
Execution of t/DistStr.t aborted due to compilation errors.
# Looks like your test exited with 255 just after 1.

What I want to do is
use Alinhamento;

$neighbor = ... # Something which will create an hash where
                # $neighbor{$x}{$y} exists if the letter $x is neighbour of $y

sub keyboard {
    my ($a, $b) = @_;
    return 4 if ($a eq $b);
    return 2 if $neighbor{$a}{$b};  #And use that $neighbor on that function
    return -1;
}

But I don't know how to make that. May I have some advice please?
Answer: There are a number of approaches, depending on specifics that are not apparent in the context provided. Here is one simple approach loosely based on your original posting:
use Data::Dumper;

our %neighbor;

$neighbor{'a'}{'b'} = 1;

print Dumper(\%neighbor);

sub keyboard{
    my ($a, $b) = @_;
    return  4 if ($a eq $b);
    return  2 if $neighbor{$a}{$b};
    return -1;
}

EDIT: Renamed $vizinho to %neighbor. Thanks @Borodin.
Note $a and $b are a little special in Perl. See the documentation for sort.
Comment: *vizinho* is Portuguese for *neighbour*
Comment: Ah, so it was never meant to be a hash reference! Good call
Answer: You must start  every Perl program with
use strict;
use warnings;

and many problems will resolve themselves.
You use package (global) variables in the same way as any other variable. In fact, if you have been used to not using strict, then all of your variables have probably been package variables.

Update
To set element x, y of your hash so that it exists and is true, you should write
$vizinho->{$x}{$y} = 1;

Your problem seems to be with how to use references. You declare
our $vizinho = {}

and then try to assign to it using
$$vizinho{'a'} = 'b'

which is wrong. You could write
${$vizinho}{'a'} = 'b'

or, much better
$vizinho->{a} = 'b'

You also shouldn't ever use $a or $b. Your code should look like this
use strict;
use warnings;

our $vizinho = {};

$vizinho->{a} = 'b';

sub keyboard {
  my ($meu_a, $meu_b) = @_;
  return 4 if $meu_a eq $meu_b;
  return 2 if $vizinho->{$meu_a} eq $meu_b;
  return -1;
}

Comment: `$$vizinho{'a'} = 'b'` is correct and equivalent to `$vizinho->{a} = 'b'`, although I discourage the first form.
Answer: With the below line you create a scalar to a hash reference:
our $neighbor = {};

What I suspect you want is just a hash
our %neighbor = (
    'foo' => {
        'bar' => 1,
    },
    'biz' => {
        'baz' => 1,
    },
);

sub keyboard {
    my ($key1, $key2) = @_;
    return 4 if ($key1 eq $key2);
    return 2 if $neighbor{$key1}{$key2};  #And use that $neighbor on that function
    return -1;
}

Also note that $a and $b are special variables used by perl's sort function, so it's probably best to use another variable name for clarity.
Comment: You're correct in a way, I was careless in setting up my example data structure.  Tiz fixed now.  Thanks

How to use a Perl global hash


how to display external image in android?

Question: I want to display external image like:
"http://abc.com/image.jpg"
in my android phone application.
can any one guide me how to achieve this?
Answer: There are many ways to achieve your request. Basically you have to download the image with an urlrequest and then using the InputStream to create a Bitmap object.
Just a sample code:
URL url = new URL("http://asd.jpg");
        URLConnection conn = url.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();

        BufferedInputStream bis = new BufferedInputStream(is);

        Bitmap bm = BitmapFactory.decodeStream(bis);

        bis.close();
        is.close();

After you obtain the Bitmap object you can use it on  your ImageView for instance
Answer: Just another approach to download the image from a url
try {
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://abc.com/image.jpg").getContent());
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}


how to filter and show fields of content types in custom page tpl.php file

Question: I have the following fields in content type 'Articles'
Year:
Volume:
Issue:
Title:
Description:
Upload file:
Now I want to create a custom pages tpl.php and categorized based on Year, Volume, Issue. So the output should be like below.
On clicking issues, it should display the all the posts.  (2013/volume 3/Issue 1)
2013
Volume3 – Issue1, Issue 2
2012
Volume 2 – Issue1, Issue 2, Issue 3
2011
Volume 1 – Issue1
Answer: Instead of modifying any template files, you should most probably be looking into the Views module, a module that, per its project page, is useful for a variety of tasks, one of which seems particularly on point here:

You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.
Answer: I could be misreading your question, but it sounds like what you want is a view. To do this you will need the Views Module. Once it is installed (Modules > Install New Module), you will create a new view (go to Structure > Views > Add New View); you can choose to display it as a page, a block, or both. Then, choose to return fields, pick the fields you want from your Article content type, and apply the proper sorting and grouping to get what you need.
If you want to use a tpl.php file to change the markup of your view results, check out this page on views template files.
Hope that helps!


Perfect Pitch vs Relative Pitch, which is Considered Better

Question: I have a question here about Perfect and Relative pitch.
So basically, my friends have been arguing about which of Perfect and Relative pitch is better, but I cannot decide.
Perfect Pitch can make you sing or play an instrument in tune, and also can make you tell notes with different pitches apart - even things like F#4 and F semisharp 4.
Relative Pitch is quite different, it is like knowing what a chord is, but not knowing the key if you do not have Perfect Pitch (or in some cases, you do recognise the key but you do not have Perfect Pitch).
So could someone please help me and tell me which type is better and more useful to the majority of people, as in whole communities? Thank you! (Note: I think I have both, but I am not exactly sure about the relative pitch)
Comment: I disagree that perfect pitch means you sing in tune.  It just means that when you hear an "A", you say "that's an A".  That has nothing to do with whether that's A440 or A435 or somewhere in between.  And even if an "A" was A440, what good is know that what an A440 is when the band is tuned to A435?
Comment: This is probably a dupe. Aaron..?
Comment: @DarrelHoffman As someone who has absolute pitch (also known as perfect pitch) but not relative pitch, I disagree with you completely.  I can't tell what an interval is, other than by calculating - that is, I hear a C and an E, and I can calculate that they're a major third apart, but I can't recognise an interval of a major third without calculating.
Comment: One is necessarily a subset of the other - If you have Perfect Pitch, you must also have Relative Pitch.  If you can tell exactly what 2 notes are, you by definition know how far apart they are.
Comment: @DarrelHoffman - absolutely not.
Comment: @DarrelHoffman Technically yes, but like if you don't know theory, that's just painful.
Comment: @Tim I don't think it's a dup (surprisingly), but I do think it's highly unlikely to be answered with anything other than opinions, speculation, and anecdotes.
Answer: This topic is often very difficult because of terms that have vague or conflicting definitions, and a certain amount of misinformation or myth. I would recommend you throw out your working definitions and start from scratch.

All of these skills are basically about "identifying things." "Perfect pitch" (also called absolute pitch) is about hearing a single note and being able to say that it's, say, an A, or possibly being able to sing an A without anyone giving you a note to hear first. "Relative pitch" is about identifying intervals, or the distances between notes. It means someone might play you an A and a D, and you would say, "I have no idea what those notes are, but they're a fifth apart." Or that, perhaps, someone could play you a note, and you could then sing that note plus another a fifth away, without knowing what their names are.
These skills exist in a continuum. If we use the superhero ability of flight as an analogy, then some can soar through space like Superman or Captain Marvel, some can fly short distances if you give them a boost first, and some can hover a few feet in the air for a few seconds. They're all part of the same conversation. Some people can tell the difference between A 440 and 441 (I mean, I guess they can; I don't personally know anyone who really could with accuracy); others can just tell that a note is closer to being an A than a B. Some might identify intervals with 75% accuracy, or have trouble with fourths and fifths.
Importantly to your point, the ability to identify and the ability to recreate can be separate. You could maybe tell that an A is an A but still not be able to sing in tune. You might be able to identify a major 7th but not sing it accurately. The skills are related, of course, but not guaranteed to go hand-in-hand.
There is a certain degree of learning or acquisition involved with all these skills. They are often talked about in a pseudoscientific, rather superstitious way, as if they are X-Men-style mutations, bestowed by fate, that presage marvelous musical abilities. "The kid sang a note in tune! He has perfect pitch! Quick, get him music lessons!" "Nature vs nurture" questions are terribly hard to research. Yes, there is some evidence that some of these abilities can be innate. But no one ever came out of the womb knowing that a note was A 440 Hz—because they have no idea yet what "A" means. You might recognize thirds and fifths without yet knowing their names, just as a toddler might distinguish between red and green, but will later learn to talk about scarlet, magenta, kelly green, and forest green.
These skills can also be "acquired" through regular and prolonged musical activity. If you listen to a certain song every day for years, and especially if you sing along with it, eventually your ear and your larynx will get familiar enough with the starting note that you can probably imagine or sing it with reasonable accuracy. If you live with thirds and fifths and sevenths, hearing them and playing or singing them while thinking about them and knowing them by name, you will increase your ability to recognize them.

So which is most useful? Well, relative pitch means that you can hear the contours of a melody and the way this note relates to the previous note and the next one. That's pretty important. Meanwhile, absolute pitch sort of "contains" relative pitch. If I can tell that this note is a G and the previous one was a C, then of course I can also tell you that the interval was a fifth. It's hard to imagine having absolute pitch with no awareness of relative pitch ("I can work out that it's a fifth, but I have no 'feeling' for the fifthiness of it"). If that situation could be imagined, it could be fairly useless; naming pitches, after all, is of little value in performance; it's a party trick. But barring some kind of brain injury, it's hard to imagine spending much time with intervals, knowing their labels, and not acquiring some degree of relative pitch.
Meanwhile, one is seldom asked to produce a pitch without the benefit of a reference pitch. Relative pitch can help you through the task of transcription as long as you can have a piano at hand. No acapella choir is expected to start singing without hearing a pitch pipe first, and then you can calculate your starting pitch by interval from it.
So ultimately, "which is more useful" is an unwinnable argument, especially as they rarely exist in pure, separate, and perfect forms.
Comment: I've read about the case multiple times on this website of the person with absolute pitch whose relative pitch is so poor that they no longer recognize a song after someone transposes it to a different key.
Comment: @StefanH That's a different skill, really, "pitch-matching." But an important one: "Playing in tune" (or singing in tune) is really just pitch-matching with a high degree of precision. As you compare the sound you're making to the reference sound you hear, the first question is "Are they the same," then "am I higher or lower," then "by a lot, or a little"? All these are learned skills—sometimes you find people who have no idea whether a pitch is higher or lower than another. Eventually you associate "a lot" or "a little" with more precise terms—a seventh, a half step.
Comment: Andy Boomer, what would you say? What degree of absolute pitch do you possess?
Comment: @StefanH As a violinist, I've acquired some degree of absolute pitch, but especially within violin range; I can't identify notes lower than violin range as accurately. I have trouble with certain timbres; I can identify piano or flute pitches quite easily, but saxophone or human voice with less accuracy. I might be able to sing a named pitch without a reference note, but maybe like 60% reliability. In the process of the years of music-making that led to this pitch recognition, I've also developed relative pitch; even if I'm unable to identify the absolute pitch, I can always identify intervals
Comment: @StefanH And I certainly am not a "human tuner" that can tell the difference between 440 and 441 Hz. (In fact, I sometimes get confused since I spend a lot of time playing baroque music at 415, one half step lower, so that I spend all day associating "A" with what sounds like A flat at modern concert pitch; sometimes I can come out of that a little miscalibrated.)
Comment: @StefanH Lol I cannot identify notes below Bb0, because like, that is Way too low :(.
Comment: Thank you for the answer! I am not good at this stuff, but I also noticed that identifiying notes, or playing tunes by ear, is way easier for me for guitar pieces (I play guitar). PS: By identifying notes I do not mean that I can name them instantly, but that it does not take long to find them on the fretboard with an "trial and error"-approach.
Answer: Firstly, I disagree that possessing perfect (absolute) pitch 'can make you sing or play an instrument in tune'. That pre-supposes you can actually sing, or play that instrument well, and may even hinder that, if it's not tuned perfectly.
Absolute pitch is often described as a mixed blessing - both being able to identify pitches and suffering when a well-known piece is played in a different key - so I'm told. It's possibly more of a party piece than useful in a musical setting, although it comes in useful when tuning an instrument - but - how accurate to you want that A note to be - 440 or 435Hz?
Relative pitch is possessed by probably a majority of musos - that being >50%. It's far more useful, and even if one doesn't realise one possesses it, it will be apparent when singing or playing the same piece in different keys. So, a great asset to have as a muso.
So, the two are very different, even though they're sort of, but not very, related. And, although it's opinion - disliked on this site - absolute pitch comes second.