Highchart throws errors when zoom out and hover point

Question: I'm trying to send x point from chart to a map so it can synchronize when hover the point. And it works properly when I don't zoom out and hover the point.

But when zoom out and hover the points, it throws error

Reproduce code: https://codesandbox.io/s/little-river-l1d3g?file=/package.json
I need to get x point so I can pass to my map component. That's why I set currentMarker to x point
Comment: Could you reproduce your case on some online editor?
Comment: hi @SebastianWędzel, I've attached a reproduce code
Answer: I reproduced your code with some minor changes - chart config is defined in the state (as it is recommended to use the React Wrapper) and it seems that everything works fine.
Demo: https://stackblitz.com/edit/react-imzhv3?file=index.js
API: https://github.com/highcharts/highcharts-react#optimal-way-to-update
Comment: thanks, the solution works. However, I have a question. Some trips work fine as the way I did before and a few throw errors although they use the same script. Do you have any ideas?
Comment: @jasonB without reproduction of the issue and debugging the code it's hard to say what could have an impact on it.


Rails multiple views accessing controller with conditionals

Question: I have a user model that includes shipping information in addition to the standard account information.
I have three different views that can update the user's information:

Wizard
Settings
Account

I know that I should be using the REST model, so I'm attempting to run all of these updates through the Update action. The one catch is that in the Wizard view, I need to make a call to the Stripe API. So I have that Stripe call in the Update controller. But now when the user tried to update their account on the Settings or Account views, the update controller is calling the Stripe API, which obviously is not what I'm going for.
So what I've attempted to do, is to insert a conditional to check if one of the Wizard parameters(:total_value) is being passed in, and if it is, to charge to Stripe. If it's not, then just update the user data. But I haven't been able to get that to work, it's just updating the user and not charging to Stripe.
Is this the right direction to be separating these updates? Or should I be creating custom actions within the Users controller? How does this work?
users_controller
def update
  if !params[:total_value].nil?
    if @user.update_attributes(params[:user])
      # flash[:success] = "Profile updated"
      sign_in @user
      # Value input by the user (in dollars)
      @userPrice = params[:user][:total_value]
      # Send full price in cents to Stripe
      @stripePrice = @userPrice.to_i * 100

      Stripe::Charge.create(
        :amount => @stripePrice,
        :currency => "usd",
        :card => params[:user][:stripe_card_token],
        :description => "Charge for service"
      )
      redirect_to success_path
      flash[:success] = "Hurray!"
    else
      flash.now[:notice] = "Can not be saved, please enter information."
      render :new
    end
  elsif
    if @user.update_attributes(params[:user])
      sign_in @user
      flash[:success] = "Profile updated"
      redirect_to account_path
    else
      flash[:error] = "Error"
    end
  end
 end

wizard/show.html.erb
  <%= form_for(@user) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
        <%= f.text_field :total_value, placeholder: "0", :class => 'amount' %>

        <%= f.label :name %>
        <%= f.text_field :name, required: "required" %>

        <%= f.label :address_1, "Address" %>
        <%= f.text_field :address_1, required: "required" %>

        <%= f.label :address_2, "Address line 2" %>
        <%= f.text_field :address_2 %>

        <%= f.label :city, "City" %>
        <%= f.text_field :city, required: "required" %>

        <%= f.label :state, "State" %>
        <%= f.text_field :state, required: "required" %>

        <%= f.label :zip, "Zip code" %>
        <%= f.text_field :zip, required: "required" %>

        <%= f.hidden_field :stripe_card_token %>

        <%= label_tag :card_number, "Credit Card Number " %>
        <%= text_field_tag :card_number, nil, name: nil %>

        <%= label_tag :card_code, "Security Code on Card (CVV)" %>
        <%= text_field_tag :card_code, nil, name: nil %>
       <%= label_tag :card_month, "Card Expiration" %>
        <%= select_month nil, {add_month_numbers_true: true}, {name: nil, id: "card_month"}%>
        <%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"}%>
        <%= f.submit "Update your shipping information", class: "btn btn-large btn-primary" %>

    <% end %>

users/shipping.html.erb
      <%= form_for(@user) do |f| %>
        <%= render 'shared/error_messages', object: f.object %>
            <%= f.label :name %>
            <%= f.text_field :name %>

            <%= f.label :address_1, "Address" %>
            <%= f.text_field :address_1 %>

            <%= f.label :address_2, "Address line 2" %>
            <%= f.text_field :address_2 %>

            <%= f.label :city, "City" %>
            <%= f.text_field :city %>

            <%= f.label :state, "State" %>
            <%= f.text_field :state %>

            <%= f.label :zip, "Zip code" %>
            <%= f.text_field :zip %>

            <%= f.submit "Update your shipping information", class: "btn btn-large btn-primary" %>
      <% end %>

users/account.html.erb
  <%= form_for(@user) do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
        <%= f.label :name %>
        <%= f.text_field :name %>

        <%= f.label :email %>
        <%= f.text_field :email %>

        <%= f.label :password %>
        <%= f.password_field :password %>

        <%= f.label :password_confirmation, "Confirm Password" %>
        <%= f.password_field :password_confirmation %>

        <%= f.submit "Save changes", class: "btn btn-large btn-primary" %>

  <% end %>

Comment: In controller, you are checking for  if `!params[:total_value].nil?` . But should it not be `!params[:user][:total_value].nil?`
Comment: Yep. That did it! Thanks so much! I guess I'm misunderstanding how parameters work. (I'm new to this) Are you able to point me anywhere to learn more?
Answer: I see two problems. First is that your:
if !params[:total_value].nil?
should be
unless params[:user][:total_value].nil?  (I personally prefer unless to if !...)
as stated in the comments by Nishant.  Second you have an elsif and the end of that condition, without it checking anything.  Just an else would suffice.


`inspect.trace()` vs `traceback`

Question: I am confused about the difference between two objects:

the list of frames returned by inspect.trace() while an exception is being handled
the traceback returned by sys.exc_info()[2] (or passed in the call to sys.excepthook)

Do the two objects contain the same information, just organized into a different data structure? If not, what one has that the other doesn't?
Comment: I tried, but they don't print themselves out (just ).. So I couldn't figure out how to do this test.
Comment: Why not **test it** by raising and catching an exception, and displaying the results of each?
Comment: Did you consider using `dir()` on the results? or `help()`?
Comment: No. I didn't think of this.... :( I will in the future!!
Comment: Performance benchmark: https://gist.github.com/JettJones/c236494013f22723c1822126df944b12
Answer: From the documentation of inspect.trace:

inspect.trace([context])
Return a list of frame records for the stack between the current frame and the frame in which an exception currently being handled was raised in. The first entry in the list represents the caller; the last entry represents where the exception was raised.

which suggests that it provides a nice way to slice and dice which frames from sys.exc_info()[2] you get.
Which, if you look at the source:
def trace(context=1):
    """Return a list of records for the stack below the current exception."""
    return getinnerframes(sys.exc_info()[2], context)

(identical for 3.2 or 2.7), is exactly what it does, but it passes it through getinnerframes, which annotates it with some useful information, per the docstring:

Get a list of records for a traceback's frame and all lower frames.
Each record contains a frame object, filename, line number, function
  name, a list of lines of context, and index within the context.

And, since I'm curious about what that actually means:
import sys
import inspect
from pprint import pprint

def errorer():
    raise Exception('foo')

def syser():
    try:
        errorer()
    except Exception, e:
        tb = sys.exc_info()[2]
        print tb.tb_frame
        print tb.tb_lasti
        print tb.tb_lineno
        print tb.tb_next

def inspecter():
    try:
        errorer()
    except Exception, e:
        pprint(inspect.trace())

Which, when called from the prompt, while recalling that many of those fields and objects have easy-to-find definitions:
>>> syser()
<frame object at 0x1441240>
6
10
<traceback object at 0x13eb3b0>
>>> inspecter()
[(<frame object at 0x14a5590>,
  '/tmp/errors.py',
  22,
  'inspecter',
  None,
  None),
 (<frame object at 0x14a21b0>,
  '/tmp/errors.py',
  8,
  'errorer',
  None,
  None)]

(line numbers jumped around because I messed with formatting)
inspect.trace() is obviously a bit nicer.

`inspect.trace()` vs `traceback`


How do I read this posterior distribution?

Question: This might be a very strange question, but I am having a bit of trouble. Here is a posterior distribution.

If I am reading this passage out loud, when I get near the end to π(δ1), do I read it as pi delta one? Or function of delta one? Or pi of delta one? Or something else entirely?
Comment: Please provide reference to the citation.
Comment: I encountered these kinds of questions all the time when reading mathematical physics textbooks for blind people. The two extremes of the spectrum of strategies are (1) read the notation literally, as in "pi open parenthesis delta sub one close parenthesis" and (2) read the notation as it would be spoken in a lecture, as "pi of delta one" or "pi of delta sub one".  Which is right, or even acceptable, will depend on your audience.
Answer: This is a loose notation where $\pi$ means several things related to priors and posteriors:

$\pi(p_1,\ldots,p_m,\delta_1|y_1,\ldots,y_m,y)$ denotes the posterior density of the entire collection of (unknown?) parameters $(p_1,\ldots,p_k,\delta_1)$ given the data $(y_1,\ldots,y_m,y)$
$\pi(p_1)\cdots\pi(p_m)$ denotes the prior density of the vector $(p_1,\ldots,p_k)$ and indicates that they are a priori iid (although one cannot tell for sure about the "identically distributed" from the loose notations)
$\pi(\delta_1)$ denotes the prior density on the parameter (?) $\delta_1$ and indicates that it is independent from the $p_i$'s
Comment: Oh okay, so it is not read as 'pi' at all. Would I read it as simply the prior of delta 1? Or would I say the prior distribution of delta 1, or prior pdf of delta 1, or prior density of delta 1? Thanks!
Comment: As clearly written in my answer, $\pi$ stands for density.


matplotlib Help using python 2.7

Question: Hi I am trying to make a scatter plot and annotate data points with real value of each point
but just the yLabel value
it mean take real value of the point and plot it near to the point
python code
import serial # import Serial Library
import time #import time
import numpy  # Import numpy
import matplotlib.pyplot as plt #import matplotlib library
from drawnow import *

temperature= []
vitesse= []
charge= []
current= []

arduinoData = serial.Serial('com5', 9600) #Creating our serial object named       arduinoData
plt.ion() #Tell matplotlib you want interactive mode to plot live data
cnt=0

def makeFig(): #Create a function that makes our desired plot

plt.subplot(2,2,1)
plt.title('Live Streaming Temperature Sensor Data')
plt.ylabel('Temperature C')
plt.grid(True)
plt.plot(temperature, 'ro-')

plt.subplot(2,2,2)
plt.title('Live Streaming Speed Sensor Data')
plt.ylabel('Speed KM/H')
plt.grid(True)
plt.plot(vitesse, 'bo-')

plt.subplot(2,2,3)
plt.title('Live Streaming SOC Sensor Data')
plt.ylabel('Battery Charge %')
plt.grid(True)
plt.plot(charge, 'go-')

plt.subplot(2,2,4)
plt.title('Live Streaming Current Sensor Data')
plt.ylabel('Current A')
plt.grid(True)
plt.plot(current, 'yo-')

while True: # While loop that loops forever
while (arduinoData.inWaiting()==0): #Wait here until there is data
    pass #do nothing
arduinoString = arduinoData.readline() #read the line of text from the  serial port
dataArray = arduinoString.split(';')   #Split it into an array called  dataArray
temp = float (dataArray[0])
vite = float (dataArray[1])
char = float (dataArray[2])
curr = float (dataArray[3])
temperature.append(temp)                     #Build our temperature array by  appending temp readings
vitesse.append(vite)                     #Build our vitesse array by appending temp readings
charge.append(char)                     #Build our charge array by appending temp readings
current.append(curr)                     #Build our current array by appending temp readings
drawnow(makeFig)                       #Call drawnow to update our live graph
plt.pause(0.00001)
cnt=cnt+1
if(cnt>50):
    temperature.pop(0)
    vitesse.pop(0)
    charge.pop(0)
    current.pop(0)

any ideas ?????
Answer: use the annotate() function to create labels attached to specific points in your plot.
see http://matplotlib.org/users/annotations_intro.html
and http://matplotlib.org/examples/pylab_examples/annotation_demo2.html
Comment: please give me an exemple because im new with python
Comment: because it's a live plot
Comment: I can't because you haven't provide your entire code. the `annotate()` should go in your `drawnow()` function
Answer: If I understood what you were looking for, you should use plt.ticklabel_format(useOffset=False) at the end of every subplot. So that, you are going to fix the y scale. Use plt.ylim(m,n) to set the limits of the y axe, where "m" is the beggining of the axe and "n" is the end.

matplotlib Help using python 2.7


Displaying popup

Question: I have a string in a masterpage which I have to display as a pop up in my application. Any suggestions?
Comment: possible duplicate of [How do I build a popup dialog in asp.net](http://stackoverflow.com/questions/1088918/how-do-i-build-a-popup-dialog-in-asp-net)
Answer: You can try http://www.javascript-coder.com/window-popup/javascript-popup-window.phtml or go with Built in AJAX capabilities.
Answer: This a pretty vague question. There is a lot of possibilities.
You can do that in Javascript. I use some jQuery to do this kind of stuff, there is a lot of possibilities using jQuery

jQueryPopup
Top 10 of jQuery popups
Another top 15 for
modal popups

Displaying popup


Missing Enumerator in Foreach Loop Editor

Question: I'm on a new laptop, working in Visual Studio 2015 on a SQL Server Integration Services package.
In previous versions of Visual Studio there are several options in the Enumerator configuration section, like this...

In VS 2015, that section is blank and I cannot populate it with a data set.

I have updated SSDT and rebooted.
Answer: The problem was with the Target Server Version in the Project Properties. The new installation of Visual Studio 2015 had it defaulting to vNext. Switching it to SQL Server 2012 caused the configuration to show up.
Answer: I had the same issue and I resolved the problem by selecting Foreach File Enumerator option under collection. By default under Collections >> Foreach Loop Editor >>> Enumerator was set to foreach Item Enumerator as shown below
Default Config for Foreach Loop Container
Instead of "Foreach Item Container" aka the default value, I clicked on it and selected Foreach File Enumerator option and that resolved my problem. Please see snapshot below
Corrected configuration for Foreach Loop Editor
Answer: You have a problem is your visual studio. (below a screenshot of ADo enumerator from my computer , using visual studio 2015)

Try running visual studio in safe mode so if this was caused by an add-on it will be fixed. just run this command
<code>devenv.exe /safemode
</code>
If not working Try repairing your SQL Server Data Tools installation or Download the Latest release
Comment: Thanks Hadi, safemode is throwing some new and interesting errors I'll go check out and that link you posted is the same one as in my question.
Comment: @TimPeters waiting for ur reply
Comment: Neither /safemode nor the link I posted to SSDT have fixed the issue. I have also tried uninstalling/reinstalling Visual Studio 2015 and got the same results. Oddly enough, when I downloaded a project from https://code.msdn.microsoft.com/Execute-SQL-Task-and-4aaea562 and opened it in VS2015 I could see the Enumerator Configuration if I switched to ForEach ADO.


Deleting Arraylist Items by Index?

Question: So I'm new at coding and i'm trying to practice working with arraylists. Basically in this a user just enters a letter and the program just displays a numbered list of those letters. I'm struggling to figure out how to remove a letter by it's index. Here's a sample of the code:
String letter = letterInput.getText();

for (int i = 0; i < lettersList.size(); i++)
    {
        String letterListIndex = lettersList.get(i);
        if (letterListIndex.contains(letter));
        {
            lettersList.remove(letter);
        }
    }

This code seems to just delete every second letter, without delete the inputted number. The tests I've been doing are inputting:
"1. H
2. B
3. K
4. L
5. J"
And if i try to delete L by typing in 4, it deletes 1. H, 3. K, and 5. J. I'm hoping that make sense.
Overall, I'd like to know how to delete a list item by it's index number. Can anyone help me out?
Comment: Pay attention that String is not an ArrayList
Comment: Can you clarify what your expected input/output is? You say the user enters a letter, but then say you entered `4`. That's not a letter.
Comment: Sorry for the confusion. The 4 was the index of the letter i was trying to remove. So on the example list, the 4th number was L. So I was trying to remove L
Comment: So why are you reading in a `String letter`? Should the user enter `L` or `4` to delete `L`?
Comment: The user should have the option to delete by L or by 4. I've got searching by the letter working, but not by the index.
Comment: @quinny see my answer. All you need to do is call `remove(index)` on the list.
Answer: You are passing remove a String. It takes an int if you want to remove by index.
Scrap your first entire for loop and simply do:
int letterIndex = Integer.parseInt(letterInput.getText());
lettersList.remove(letterIndex);

This is all the code you need

If I have a lettersList: {"H", "B", "K", "L", "J"}
All I need to do is call lettersList.remove(4-1) (-1 for 1 indexing) and lettersList will now be: {"H", "B", "K", "J"}
Comment: The OP isn't calling `remove` on a `String`, but a `List`.
Comment: @Shashwat the parameter is a String. I admit "calling on" is not super precise language.
Comment: Thank you! How would I be able to search for the int in the letters list now? When I put in (letterListIndex.contains(letter), it gave me an error saying the int can't be converted to char qsequence
Comment: @quinny why are you searching for the `int`? I thought your list was all letters.
Comment: The int was searching for the index
Comment: @quinny you *don't need to search for it*. See my updated answer. `remove` removes whatever item is at the given index. It looks like your list is 1-indexed whereas in Java lists are 0-indexed, but you can get around this by just doing `remove(index-1)`
Comment: ahhh okay i got it working! Thank you for your help and patience, I really appreciate it
Comment: @quinny No problem at all.
Answer: try this:
public static void main(String[] args) {
    int index = 4;
    String str = "abcdef";
    String result;
    if (str.length()>index);
    {
        result = str.substring(0, index) + str.substring(index+1);
    }
    System.out.println(result);
}

the index var is the input, and it is 0 based. So if you want to be 1 based, you can set index = index+1
Comment: The OP wants to operate on an `ArrayList`, not a `String`

Deleting Arraylist Items by Index?


Surface Area of unit n-sphere covered by rotating a unit vector around a fixed unit vector such that angle between the two vectors is always fixed.

Question: Consider an n-dimensional unit sphere and unit vector from the origin with its tip lying on the surface of sphere. Consider another vector which makes some angle say $\epsilon$ with unit vector. From a 3-dimensional analogy, if we rotate this vector around fixed vector so that angle between two vectors is always constant, we'll get some portion of the area of the sphere covered.
I want to know if there exists some explicit formula for computing such area given $\epsilon$ for an n-dimensional sphere. If not then how should we go about calculating this.
Comment: See this [answer](http://math.stackexchange.com/a/1305399/59379). For the unit $d$-sphere embedded in $\mathbb{R}^{d+1}$, the "surface area" you seek (i.e the "area" of the union of circular arc segments when you change one of the endpoint) is $\frac{2\pi^{d/2}}{\Gamma(\frac{d}{2})} \int_0^\epsilon (\sin\phi)^{d-1} d\phi$.
Comment: Well thanks a lot @achillehui for your valuable comment and thanks Samrat for the tag.
Answer: The "area" you are looking for is in fact an $n-1$ dimensional object, as a sphere in $n$ space is an $n-1$ dimensional shell and you are cutting off a piece of it.    If you mean to imply that $\epsilon$ is very small, the piece will be an $n-1$ dimensional ball.  The analogy with a sphere in 3D is applicable-the piece you cut off is almost a circle because you can't see the curvature of the original sphere.  If your fixed vector is along the $x$ axis, the boundary of the cut off piece will be $y^2+z^2+w^2+\dots = \epsilon^2$, with $n-1$ terms on the left.  The $n-1$ dimensional volume is then  $\frac {\pi^{(n-1)/2}}{\Gamma(\frac n2-1)}\epsilon^{n-1}$
Comment: Thanks @Ross Millikan. Your answer really helped !


Analytic geometry and calculus question

Question: The tangent to the curve  $ x^{0.5} + y^{0.5} = a^{0.5}$  ,$(a>0)$  intersects the $x$ axis in point $M_1$ , and the $y$ axis in point $M_2$.  Prove that for any point on the curve $|OM_1|+|OM_2| = a$ , where $O$ is the point of the beginning of axis, and $|OM_1| ,|OM_2|$ lengths of the segments. Is there a particular method for this kind of proof? I did found the tangent equation but it didn't help much.
Comment: If you have the equation of the tangent line for a point (X, Y) on this curve , you can find the $ \ x-$ and $ \ y-$ intercepts.  That will tell you the lengths of $ \ OM_1 \ $ and $ \ OM_2 \ $ .
Answer: Implicit differentiation of the curve equation yields:
$$
\frac1{2\sqrt{x}}+\frac1{2\sqrt{y}}\times y^\prime=0 \\
y^\prime =−\frac{\frac1{2\sqrt{x}}}{\frac1{2\sqrt{y}}}=-\frac{\sqrt{y}}{\sqrt{x}}
$$
So for the tangent to the curve at a point $(x_0, y_0)$ on the curve, we get:
$$
y−y_0= -\frac{\sqrt{y_0}}{\sqrt{x_0}} (x−x_0 ) \\
\frac{y}{\sqrt{y_0}}−\sqrt{y_0 }=−\frac{x}{\sqrt{x_0}}+\sqrt{x_0} \\
\frac{x}{\sqrt{x_0}}+\frac{y}{\sqrt{y_0}}=\sqrt{x_0}+\sqrt{y_0}=\sqrt{a}
$$
Now, to find $M_1$ and $M_2$ we substitute $y=0$ and $x=0$ respectively.
With $y=0$:
$$
\frac{x}{\sqrt{x_0} }=\sqrt{a} \\
x=\sqrt{ax_0} \\
M_1 (\sqrt{ax_0},0)
$$
With $x=0$:
$$
\frac{y}{\sqrt{y_0 }}=\sqrt{a} \\
y=\sqrt{ay_0} \\
M_2 (0,\sqrt{ay_0}) \\
\therefore \left|OM_1 \right|+\left|OM_2 \right|=\sqrt{ax_0 }+\sqrt{ay_0 }=\sqrt{a} (\sqrt{x_0 }+\sqrt{y_0 })=\sqrt{a} \times \sqrt{a}=a
$$

Analytic geometry and calculus question


ESXi hosted on public IP without firewall

Question: So I've got an interesting problem.
I currently rent a couple of servers from Hetzner (a German hosting provider). Each server has a soft firewall and does something like web hosting / database.
I would like to rent a beefier server and setup a hypervisor like ESXi on it with a vSwitch connected to physical NIC and a pfSense VM, and another vSwitch from the pfSense VM to other VMs. Unfortunately, Hetzner does not appear to provide a hardware firewall in between the public interface and your server (leaving soft firewall as the only option).
What are the security implications of running ESXi (v5.5) out in public like that? Quick research suggested this thread on spiceworks which sums it up as disabling SSH/Console (telnet?) access and setting up proper SSL cert and a very complex unguessable username/password pair. With the obvious implication of single-entry attack point.
Comment: @jonatan, I have looked at AWS, however I have distrust and would rather host/keep my own data
Comment: This is just a bad solution. I see it asked here way too often, though, and I'm not sure why people end up in the situation without a real firewall.
Comment: What are you planning to run on the ESX? There might be a better way to approach the problem. For web servers, have you looked into AWS?
Comment: Of course you have the host firewall and the firewall on the guests but to my line of thinking this is like leaving the vault door open and letting the bank robbers bang away at the safety deposit boxes. Is there no hosting provider that you can use that implements a firewall at the ingress/egress of the network?
Comment: @ewwhite could be because of unusual circumstances like a hosting provider.
Comment: @joeqwerty at the time of my researched, hetzner seemed to be the most cost effective provider for what they offered (full server hardware rent on the cheap)
Comment: Right, I understand... but a hosting provider + ESXi and no networking flexibility is the worst of all combinations. The hardware won't be resilient enough, you'll have problems with out-of-band access, security is dependent upon weird VM-based networking and there still won't be any NIC/switch redundancy.
Answer: You can limit the IP addresses permitted through the ESXi firewall.
http://pubs.vmware.com/vsphere-50/index.jsp?topic=%2Fcom.vmware.vcli.examples.doc_50%2Fcli_manage_networks.11.11.html
That is really all you need to harden it. Locking your management down to specific IP addresses is very secure. Naturally follow the other best practices re passwords etc as well.
Just make sure to look at the firewall completely and lock down everything to your management IPs.
Non Static IP Alternative
Lock all ports down to 127.0.0.1 as given above except for SSH.  Lock SSH down to private/public key authentication only and disable ChallengeResponseAuthentication and PasswordAuthentication. This is very secure.
Use your favourite SSH client connect to the server with a command line such as:
ssh my.vmhost.rackhoster -L80:localhost:80 -L443:localhost:443 -L903:localhost:903
Then leave the SSH session running and point your browser to https://localhost/ and it will automatically forward port 443 through to the ESXi host. Change the ports if you are already using port 443 on your local machine (ie, -L8443:localhost:443 instead -> https://localhost:8443/). Same for port 80.  Port 903 is for the console.
If you ever loose your private key you're pretty screwed this way so back it up! :-)
For ultra security ensure your private key is encrypted with a good passphrase.  Don't forget it!
Comment: Not potential.  *definite* :-)  In that case you could (a) invest in a static IP address or (b) have a Terminal Server/GUI Frontend somewhere else on a static IP address such as the office or (c) setting up a VPN connection to some static IP address and then managing it over the VPN. Naturally any other than the first option introduce additional points of failure, though fairly minimal.
Comment: I see a potential problem of locking yourself out if you do not have a static IP from wherever you are managing it (in my case - at home).
Comment: I added another alternative to the answer where you just have no access to any static IP address at all.
Comment: I will give this a try at home first to see how it works, but this seems like it might just work! Thanks! Marking as an answer for now
Answer: Use the ESXi builtin firewall to close down unneeded ports and limit access to the open ones to a range of known IP addresses.
This might be challenging if you do not use a fixed external IP address at home (like most people), so you may end up restricting access to the addresses of some other servers that you have on the Internet.
Answer: Why would you run ESX on the public net? Can't you just use the pfSense FW as the "public endpoint" and make everything else private? This is how I would do it.
Comment: As stated in the original question, this is not possible. With this hosting provider, you can't setup a server behind another server (via switch). Each server you get is connected to a public IP.
Comment: This has the disadvantage that, if anything goes wrong on the firewall, the ESXi server may not be salvaged.
Comment: @Jorn: Make it a HA-pair of Firewalls then? Works good using pfSense.


Django - How to put a list in an url

Question: I'm creating a list in a view to show elements from loaded csv file(def showCsv(request)). What I would like to get this list and put this list in url redirection (the first link 'a'), but I don't know how to do this.
def showCsv(request):
    if request.POST:
       object_pk = request.POST.get('pk')
       csvname = request.FILES['f']
       path = default_storage.save('media/csv', ContentFile(csvname.read()))
       tmp_file = os.path.join('', path)
       csvname = open(tmp_file, 'rb')

       reader = csv.reader(codecs.iterdecode(csvname, 'utf-8'), delimiter=";")
       list_test = []
       for row in reader:
           list_test.append((row))

    return render(request, 'website/show_csv.html',
    { 'app_version':APP_VERSION, 'object_pk':object_pk, 'list': list_test})

show_csv.html
{% block content %}

    Continuer

     Retour

            {% for row in list %}

                  {{ row.0 }}
                  {{ row.1 }}

            {% endfor %}

{% endblock %}

Comment: Can't you store that CSV in a model? If yes, you can write a `view` which displays this list with a refering `pk`.
Comment: I can't use model because i didn't to store element of my csv, because when user log on my website, the csv is just "load temporarly" on media.
Comment: What to you clearly want to do with this list and URL ?
Comment: For example, they are elements on my csv : [['NumeroProduit', 'NumeroSerie'], ['SUPP-MC67-01110', '20160428'], ['PACE-MK25-03265', '10035701']], and i'd like to save or transfert this list on another view to use elements to write templates and print them. I choice url because i can get the list (like get_object() for pk)
Comment: Ok, what's the `pk` refering to?
Comment: User choice a label format to print (the pk is the id of label), after he choice a type of printing and if he choice the the second method, he load his csv, show his csv and print his label.  My problem his on show csv, dunno how get the list.
Comment: Since you're storing it in `media`, can't you create a `FileField` in this model refering to this field? If not tell me clearly why is it different from your method atm. If you can then i've an answer.
Answer: if I'm understanding this, you are reading a list in one view (where you get it from uploaded file) and then you would like to pass whole list to the other view.
for sure you will not be able to pass whole list as url parameters - if file will be bigger than allowed url length - it will fail. Other issues are matter of performance or even - clarity.
There are multiple solutions for passing data between views, but you need to store and keep data somehow on the server side, and then pass some identifier between views.
simplest one is to use database, more complex - store data into file (you have this file already), then store path to the file in session or pass it via parameter to the url, you can store data in the cache (if it is not so big) etc.
Answer: Sorry for my absence,I found a solution to my question.
To do this i write the url of my csv in other file and i open this file on my other view, not really the best idea but it's work.
After you just have to work on (add element, delete element, show in context,...). Thanks for your help.
ShowCsvView
path = default_storage.save('media/csv', ContentFile(csvname.read()))
    tmp_file = os.path.join('', path)
    csvname = open(tmp_file, 'rb')

    reader = csv.reader(codecs.iterdecode(csvname, 'utf-8'), delimiter=";")
    list_test = []
    for row in reader:
        list_test.append((row))

    f = io.open("media/list_file", "w")
    f.write(tmp_file)
    f.close()

CreatePdfView
list_element_csv = []
    with io.open("media/list_file", "r") as infile:
        str_path = infile.read()

    csvname = open(str_path, 'rb')
    reader = csv.reader(codecs.iterdecode(csvname, 'utf-8'), delimiter=";")
    for row in reader:
        list_element_csv.append(row)

Django - How to put a list in an url


openvpn to AWS VPN endpoint gets a connection reset error

Question: I've setup a new AWS client VPN Endpoint using mutual authentication, and trying to connect using openvpn, I get a connection reset error:
<code>2023-07-06 12:44:43 OpenVPN 2.5.5 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Jul 14 2022
2023-07-06 12:44:43 library versions: OpenSSL 3.0.2 15 Mar 2022, LZO 2.10
2023-07-06 12:44:43 TCP/UDP: Preserving recently used remote address: [AF_INET]18.104.22.168:443
2023-07-06 12:44:43 Socket Buffers: R=[131072->131072] S=[16384->16384]
2023-07-06 12:44:43 Attempting to establish TCP connection with [AF_INET]22.214.171.124:443 [nonblock]
2023-07-06 12:44:43 TCP connection established with [AF_INET]184.108.40.206:443
2023-07-06 12:44:43 TCP_CLIENT link local: (not bound)
2023-07-06 12:44:43 TCP_CLIENT link remote: [AF_INET]220.127.116.11:443
2023-07-06 12:44:43 Connection reset, restarting [-1]
2023-07-06 12:44:43 SIGUSR1[soft,connection-reset] received, process restarting
</code>
I've configured the client VPN endpoint to use TCP, since UDP is blocked by firewall in the office I'm working from.
Other than this, all is by the guide: https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-getting-started.html
Nothing is logged to the related CloudWatch Log Group.
How can I further investigate?
Answer: Had the same issue and made it work with assistance from their support engineer. Two things to check:

CA part in ACM client certificate is required (even though it says it's optional)
Any changes in ACM client certificate are NOT automatically reflected in AWS VPN endpoint referencing that cert. In other words, when you re-import ACM client certificate (e.g. to add CA part) you need to create a new VPN endpoint.

Once I took both of these items into account all soft-resets went away


Prolem in replacing special characters "@" with a blank using regex replace function

Question: i am using following regex expression to replace
query=query.replace(/[^a-zA-Z 0-9*?:.+-^""_]+/g,'')

But when my query is diam!@#%d i get diam@d after execution of this.
it means it is not replacing @ . Why is so ??
Comment: what would you like to accomplish? If it is to remove everything except letters, why not use `query.replace(/[^a-zA-Z]+/, '')` directly?
Comment: epoch : i juss want to replace @ with a blank ie with ''
Comment: epoch : No i want to replace characters other than i have given in the expression
Answer: You need to escape - sign in your regex (- => \-), i.e.: [^a-zA-Z 0-9*?:.+\-^""_]+, therefore it will match: !@#%.
Comment: +1 or move it to the start or the end `[^a-zA-Z 0-9*?:.+^""_-]+`
Comment: @Romi, inside `[]` `-` means range of chars, i.e. `[+-^]` means from char `+` to char `^`.
Comment: polishchuk: why so, why Escape sign only affecting @ charecter
Comment: `-` is reserved within character classes


Set perdomain localstorage limit in Opera

Question: If I run this test in Opera first time, then I get a popup, where I can set the storage size of this domain. But if I click cancel, then the next time there is no popup, the storage size will be the default.
So how to set the localStorage size per domain in Opera?
Answer: To change the general quota limit, visit opera:config#PersistentStorage|DomainQuotaForlocalStorage.
To read/edit the per domain quota preference, open your profile directory (the location can be found via Help > "About Opera"), and edit override.ini(multi-user). You can also open Opera's application folder, and edit operaprefs.ini.
The format is as follows:
[domain.tld]
Persistent Storage|Domain Quota For localStorage=<bytes>
Persistent Storage|Domain Quota Exceeded Handling For localStorage=0

[Overrides]
domain.tld

At the domain section, the first entry is the quota limit. The second entry is zero when you reject the request for quota expansion.
For more information, see Opera's settings file explained#Persistent storage.
Comment: thanks. Unfortunately in the other browsers I can't set it per domain :S


Why does the series $\sum_{n=1}^{\infty}\frac{(-1)^{n+1}}{n}$ converge?

Question: I saw the proof, that the alternating harmonic series converges. So $\sum_{n=1}^\infty \frac{(-1)^{n+1}}{n}$ converges. I didn't understand one thing in proof. So the argument here is, if we look at subsequence
$s_{2n}=(\frac{1}{1}-\frac{1}{2})+(\frac{1}{3}-\frac{1}{4})+\ldots+ (\frac{1}{2n-1}-\frac{1}{2n})$ we can see, that this subsequence is monotone increasing and if we look at subsequence
$s_{2n+1}=\frac{1}{1}-(\frac{1}{2}-\frac{1}{3})-(\frac{1}{4}-\frac{1}{5})-\ldots-(\frac{1}{2n}-\frac{1}{2n+1})$ is monotone decreasing. And since
$0<s_{2n}<s_{2n}+\frac{1}{2n+1}=s_{2n+1}\leq1$ we have that both of these subsequences are bounded
below by 0 and above by 1. Therefore they are both convergent and to the same value. Why does it follow? From which theorem? So I can't understand it. Thank you in advance!
Comment: I think [this](https://en.wikipedia.org/wiki/Alternating_series_test) may be helpful.
Comment: The limits are same because $s_n-s_{n-1} \to 0$.
Comment: Adjacent sequences theorem : If 1) $(a_n)$ is decreasing, 2) $(b_n)$ is increasing and 3) $\lim_{n \to \infty} (a_n−b_n) = 0$ then both $(a_n)$ and $(b_n)$ converge to the same limit.
Comment: @ÁtilaCorreia thank you) But I don't want to use it, because in my book, I didn't have it yet. So I want to use the theorems or argument from theorem, that I had. Like the Bolzano-Weierstrass Theorem or Monotone Convergence Theorem etc. So this basic theorems.
Comment: @geetha290krm thank you))
Answer: There are two theorems at work here:
Theorem 1: A bounded, monotonic sequence must converge
This is why both $(s_{2n})$ and $(s_{2n+1})$ are convergent sequences.
Theorem 2: If $a_n \leq b_n \leq c_n$ for all $n$ and $\lim_{n \to \infty} a_n = \lim_{n \to \infty} c_n = L$, then $b_n$ converges with $\lim_{n \to \infty} = L$.
To use this second result, we note that
$$
\lim_{n \to \infty} s_{2n} + \frac 1{2n+1} = \lim_{n \to \infty} s_{2n} + \lim_{n \to \infty} \frac 1{2n+1} = \lim_{n \to \infty} s_{2n} + 0 = \lim_{n \to \infty} s_{2n},
$$
so taking $a_n = s_{2n}$ and $c_n = s_{2n} + \frac 1{2n+1}$, we can conclude that $\lim_{n \to \infty} s_{2n} = \lim_{n \to \infty} s_{2n+1}$
Comment: thank you so much!
Comment: I think it would be helpful to the proposer to point out that we know the increasing sequence $(s_{2n})_n$ and the decreasing sequence $(s_{2n+1})_n$ are bounded because  $s_2<s_4< ...<s_{2n}<s_{2n+1}<...<s_3<s_1,$  so $s_1$ is an upper bound for $(s_{2n})_n$ and $s_2$ is a lower bound for  $(s_{2n+1})_n.$
Comment: @DanielWainfleet That is certainly a valid way of demonstrating that the sequences are valid, but it is not a part of the particular proof that the asker is concerned with. If you think that this detail is valuable to the asker regardless of the literal intent of the question, then you're welcome to post your own answer.
Answer: This does not answer your question, but I'll write the answer anyway so you can look at the problem from a different point of view.
Using Taylor series of $\log (1+x)$, we have:
$$\log (1+x)=\sum_{n=1}^{+\infty} \frac{(-1)^{n+1}x^n}{n} \quad \text{for} \quad |x|\leq1, x\neq-1 $$
$$\sum_{n=1}^{+\infty} \frac{(-1)^{n+1}}{n}=\sum_{n=1}^{+\infty} \frac{(-1)^{n+1}1^n}{n}=\log 2 $$
Comment: @mathguruu It is useful to keep this result in mind. Regards :)
Comment: You give $|x|<1$ for the region of convergence yet you use the power series with $x=1$. You need to show that the series converges when $x=1$ and then refer to Abel's theorem to conlude that the limit is $\log 2$.
Comment: @Gary Thank you for pointing this out, I've wrote the wrong radius of convergence
Comment: No, the radius of convergence is indeed $1$. What you wrote is stronger than what the OP has to prove. You did not really prove anything here.
Comment: @Gary Yes I know this is not an answer, I just wrote it to see the problem from a different point of view. Actually, if you find the sum then indeed the series converges, but I know doing this implies knowing Taylor series. It can be used as a fact for future problems
Comment: thank you ) for your answer)


How do I fit a double Poisson regression model?

Question: $$
X_k \sim \mathcal{Pois}(\lambda_k) \\
Y_k \sim \mathcal{Pois}(\mu_k) \\
\\
\ln \lambda_k = \alpha_{i(k)} + \beta_{j(k)} + \gamma + \eta / 2 \\
\ln \mu_k = \alpha_{j(k)} + \beta_{i(k)} + \gamma - \eta / 2
$$
Imagine the above problem for modelling basketball points,
Where $X_k$ represents the total points scored by the home team in game $k$ and $Y_k$ represents the total points scored by the away team in game $k$ (assume $X$ and $Y$ are independent for simplicity).
How would one fit these models using Maximum-likelihood estimation?
$(\alpha_1,...,\alpha_n)$ and $(\beta_1,...,\beta_n)$ are two vectors of coefficients to be estimated.
$\alpha_{i(k)}$ is an 'attacking' coefficient for team $i$ (the 'home' team) in game $k$.
$\beta_{j(k)}$ the 'defending' coefficient for team $j$ (the 'away' team) in game $k$.
$\gamma$ is a constant, could be interpreted as the average points scored per game.
$\eta$: I'm not too sure, possibly a binary indicator variable or maybe another constant. Something like home advantage which could take the form $(X-Y)$ but I think that would violate the model ?
Comment: The roles of the subscripts $i$ and $j$ are obscure.   It appears you are trying to fit two variables $\lambda_k$ and $\mu_k$ using *six* parameters.  Please explain.
Comment: Please explain the symbols used. How does it differ from two independent Poisson models?
Comment: @Tim - $\gamma$ and $\eta$ are shared parameters.  Also, the $\alpha$ and $\beta$ values may be shared, depending upon the subscripts, e.g., if $k=2$ and $i(k) = 3$ in the first expression and $k = 4$ but $j(k) = 3$ in the second expression, both expressions contain $\alpha_3$.
Comment: I don't think your interpretation that the "attacking team" is the "home team" is correct.  In each game (represented by the two observations $X_k$ and $Y_k$ both teams are both attacking and defending).  Instead, $X_k$ is the score of the home team and $Y_k$ the score of the away team and the expected values of these Poisson variables depends on the attacking and defence coefficients of the home and away team, respectively.
Answer: You can fit this as an ordinary Poisson glm with a log link function, treating each $X_k$ and $Y_k$ scored in each game as separate observations, including the attacking and defending teams as factors, and including the home-/away-field advantage/disadvantage via a binary factor with a sum-to-zero contrast.  If you have $m$ teams, you need to impose some constraints on the $m$ $\alpha_i$'s and $\beta_i$'s to make the model identifiable, for example, via treatment or sum-to-zero contrasts.
Answer: It sounds like you could use bivariate Poisson distribution (Karlis and Ntzoufras, 2003) to model this data, especially since it was already used in similar context. The distribution is defined in terms of three random variables
$$
Z_i \sim \mathcal{P}(\lambda_i), \quad i = 1,2,3
$$
where
$$\begin{align}
X &= Z_1 + Z_3 \\
Y &= Z_2 + Z_3 \\
(X, Y) &\sim \mathcal{BP}(\lambda_1, \lambda_2, \lambda_3)
\end{align}$$
with probability mass function
$$
f(x) = \exp \left\{-(a+b+c)\right\} \frac{a^x}{x!} \frac{b^y}{y!} \sum_{k=0}^{\min(x,y)}{x \choose k} {y \choose k} k! \left( \frac{c}{ab} \right)^k
$$
In such a case, you would model $\lambda_1$ and $\lambda_2$ parameters in terms of your $\alpha$ and $\beta$ parameters and $\lambda_3$ as the joint term. $\lambda_3$ would influence the degree of dependence between $X$ and $Y$. So there would be some slight modifications of your model.
There is an R package for bivariate Poisson GLMs, PMF and random generator are available through R's extraDistr package (disclosure: I'm the author), or you could define the model in a probabilistic programming language of your choice.

Karlis, D. and Ntzoufras, I. (2003). Analysis of sports data by using bivariate Poisson models.
Journal of the Royal Statistical Society: Series D (The Statistician), 52(3), 381-393


How to connect two command line arguments?

Question: I need to connect two command line arguments. The user is supposed to put -input "filename.txt" and/or -output "filename.txt" but I can't seem connect the -input or -output parts with the filename.
So for example the user could enter any of the following:
java classname
java classname -input filename.txt
java classname -output filename.txt
java classname -input filename.txt -output filename.txt
java classname -output filename.txt -input filename.txt

I tried this:
        for(int i = 0; i < args.length; i++){
        if(args[i].equals("-input")){
            input = args[i + 1];
        }
        else{
            //input from terminal
        }

        if(args[i].equals("-output")){
            output = args[i + 1];
        }
        else{
            //output to terminal
        }

But it's not working and seems inelegant. I have been looking into the Apache Commons CLI but I can't seem to quite figure out how that works and if there is a applicable function. Using the Apache thing or some other way is there some way I can connect the -input to the filename.txt?
Comment: "-fin" and "-input" are completely different Strings, and likewise for "-fout" and "-output". Why make things more confusing for you and us?
Comment: Oops! sorry, I copied my commented code and didn't realize I hadn't changed the String to match. I fixed it now.
Comment: If your command line structure is correct, then you need only to count the command line argument array size, and look at the odd number arguments and deal with the next arguments if the previous argument is a one of interest. I wouldn't worry about elegance at this stage of the game. I'd worry more about "functionality".
Comment: One problem you might be having is that you find arguments i and i+1.  Then you incement i by 1.  You might need to increment i by 2.
Comment: The Apache cli libray does look to be quite useful. Have you tried playing with it some? It looks like all you'd need to do would be to add two Option objects to an Options object, and then call `parse(...)` passing in the Options object and your command line. Then it would be an easy business extracting the Strings you need from the CommandLine object returned. Shoot, I may have to download this library as it looks quite easy and useful. Thanks for the heads up!
Comment: I think I'll try to do that with the Apache CLI... Thanks for the thoughts.
Comment: Example code can be found [here](http://commons.apache.org/cli/usage.html)
Answer: This should work
public static void main(String[] args) {
    String input = findArg("input", args);
    String output = findArg("output", args);
}

static String findArg(String name, String[] args) {
    for (int i = 0; i < args.length; i += 2) {
        if (args[i].equals("-" + name)) {
            return args[i + 1];
        }
    }
    return null;
}

Answer: There is a flaw in your logic; and that is why it doesnt work. If I run the program with the following arguments java classname -input input.txt -output output.txt then your code will take input from terminal and output to the output.txt.
Update - actually it will crash with NullPointerException


Should there be an EntityManager per thread in Spring-Hibernate?

Question: We are designing an application using Spring-Hibernate where 6 threads run simultaneously. Each thread performs a different operation and inserts/updates a few records in common table(all threads work on common tables).
While we know that we can have just one single instance of EntityManagerFactory, we are not sure how many instances of EntityManager should we have? Should we create six entity managers(one for each thread)? How should we create the DAO? Should we just create one EntityManager like following and use the same dao class for all the threads? I know EM specification says that it's not thread safe, but I read somewhere that injected EM in the case of spring are threadsafe(I wasn't convinced with the explanation, though).
@Trasactional
public class myAppDao {
@PersistenceContext
private EntityManager entityManager;
..
}

or should we do something different ?
Comment: See this http://stackoverflow.com/questions/14888040/java-an-entitymanager-object-in-a-multithread-environment
Comment: `Entity managers are not thread-safe But, if the injector is injecting each thread with its own entity manager then things should be OK.Spring and possibly other DI frameworks will inject a ThreadLocal-based proxy for a real entity manager into your beans. Calls that each thread makes will proxy to the real thread-local instance of an entity manager - this is how things can work even though it might appear an entity manager is shared among multiple threads.`
Answer: Yes, usually the EntityManager or Session are bound to the thread (implemented as a ThreadLocal variable). @PersistenceContext annotation is recognized by Spring IoC/CDI and is treated in a special way to enable this.
There is some layer in your app (usually marked as @Transactional) that creates EntityManager and binds it to the ThreadLocal variable. This happens every time the 1st @Transactional is invoked. And same - EntityManager is closed every time the method exits.
Alternatively this can be implemented using OpenSessionInViewInterceptor or OpenSessionInViewFilter.
Comment: So can I just create one Dao class in which I initialize an EM and inject that dao to all other classes where each class has its own thread?
Comment: Yes, but don't forget that the invocation should go through `@Transactional` method.
Comment: @Arash, yes, see https://stackoverflow.com/questions/13539213/why-do-i-need-transaction-in-hibernate-for-read-only-operations/13540484#13540484
Comment: Yes sure. Thank you very much.
Comment: Should i use **@Transactional** for methods that their job are finding data(not changing) to make the container to close EM?


Feeds import - Skip importing item based on some condition

Question: I am making API call to import data into Drupal. The API provides 2 filters by which I can get the data. Now I want to apply additional filter on the returned data and only save data which validate the third filter.
E.g.
The API - http://example.com/users?country=US&state=NY
Requirement - I want to import users data into Drupal only if users age is above 18 (And from US-NYC).
Now the API do not have age filter, but it provides age in the response. How can I write a code to ask feed importer to skip import if age is below 18.
Hope I am clear asking this question.
Answer: You can do this using hook_feeds_presave to check the data prior to it being saved.
<code>function mymodule_feeds_presave(FeedsSource $source, $entity, $item) {

  // check that this is fired only for the importer being used
  if($source->importer->id=='my_user_importer'){

    // check that the age is over 18
    if($item['age'] < '18'){
      $entity->feeds_item->skip = TRUE;
      drupal_set_message(t("Skipping user who's age is below 18", 'warning');
    }
  }
}
</code>


Effective way to notate triplets

Question: I was directed by America Luke to this forum site. I hope this is the correct place.
I have a score with a lot of triplets. It's awkward to write always \times 2/3 {c16 d e} \times 2/3 {d e f}.
Since the \times causes not only the duration scaling but also the bracket length you can't use
\times 2/3 {c16 d e   d e f}.

How can this done more efficiently.
Answer: It's worth pointing out that as of LilyPond 2.17.11, you can write

\tuplet 3/2 8 {c16 d e d e f}

and get 3:2 tuplets in groups of duration 8 (in this case, two groups of three tuplets each).  This is basically the same as temporarily overriding tupletSpannerDuration.
Answer: I think that your problem isn't intrinsically with the triplets, but rather with controlling beams; one approach is to manually set the beams:
Running lilypond 2.16 on

{
\times 2/3 {c16^"Two 3-note phrases"  d e } \times 2/3 { d e f } r4 r2

\times 2/3 { c16^"Manual Beaming" [d e] d [e f] } r4 r2

\set tupletSpannerDuration = #(ly:make-moment 1 8)
\times 2/3 { c16^"Moment & Manual Beaming" [d e] d [e f] } r4 r2

}

yields this
The square brackets in the lilypond file indicate the beams in the same manner as parentheses indicate slurs.
Comment: @CarlWitthoft use `\times 4/6` instead, and lilypond will even try to infer the best beaming as available.
Comment: Cool!  Question: shouldn't the "one six note phrase" really have a "6" over it to indicate the number of notes in one beat?
Comment: Yeah, the "six note prhase" looks odd, and possibly ambiguous; c.f. (http://music.stackexchange.com/questions/12655/notating-6-or-more-triplets-with-a-single-bar)
Comment: Well, all your examples show some inadequate pictures. First (as my example) has correct brackets but wrong beaming. Second and third has a bracket over multiple triplets. I write a piece with triplet over several staves. (as at page 4 of http://javanese.imslp.info/files/imglnks/usimg/5/50/IMSLP248772-PMLP403277-ETAHoffmann_Harp_Quintet_score.pdf) It's not a pleasure to find somewhere the bracket number instead about the triplet itself. Isn't there an effective way to write triplets.
Comment: Yes I know that I can start and stop the beams with []. But that isn't what I am looking for. Can't I tell Lilypond to write 100 triplets with _automatic_ beaming?
Answer: You have to specify the property tupletSpannerDuration to get several tuplets using only one \times command:
\set tupletSpannerDuration = #(ly:make-moment 1 8)
\times 2/3 {c16 d e d e f }

See LilyPond Documentation for more on this.
Answer: I think, there is no need to restrict the contents of one brace to 3 notes only, so for consecutive triplets, as in your example, a minor compression can be:
\times 2/3 {c16 d e d e f}

Comment: Ok, since the OP claimed this fouls up the bracket length, can someone post the actual pdfs this code generates?
Answer: A better looking grouping:
\relative c' {
  \override TupletBracket.bracket-visibility = #'if-no-beam
  \times 2/3 { c16 c \set stemRightBeamCount = #1 c }
  \times 2/3 { \set stemLeftBeamCount = #1 c c c }
}

yields this:

Effective way to notate triplets


Erro ao consumir serviço utilizando o volley

Question: Estou desenvolvendo um aplicativo no Android Studio no qual consome um serviço que criei no Play Framework.
Essa é minha rota no serviço:
GET /Services/cadastrarPalheta/{matricula}/{data_instalacao}/{local}/{cod}/{estado}/{bairro}/{rua}/{complemento}/{pais}/{latitude}/{longitude}/{obs}            Services.cadastrarPalheta

Minha classe de serviço:
public class Services extends Controller {
public static void cadastrarPalheta(String matricula, String data_instalacao, String local, String cod, String estado, String bairro,
        String rua, String complemento, String pais, String latitude, String longitude) {

    if (validation.hasErrors()) {
        String mensagem = "Erro ao cadastrar";
        JsonObject j = new JsonObject();
        j.addProperty("Erro", 404);
        j.addProperty("msg", mensagem);
        renderJSON(j);
    } else {
        String msgsucess = "Cadastrado com sucesso!";
        Endereco endereco = new Endereco();
        endereco.estado = estado;
        endereco.bairro = bairro;
        endereco.local = local;
        endereco.rua = rua;
        endereco.complemento = complemento;
        endereco.pais = pais;
        endereco.latitude = latitude;
        endereco.longitude = longitude;
        endereco.save();
        Agente funcionarioBanco = Agente.find("login = ?", matricula).first();
        Palheta pal = new Palheta();
        pal.agente = funcionarioBanco;
        pal.codigo = cod;
        DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        try {
            pal.data_instalacao = formatter.parse(data_instalacao);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        pal.endereco = endereco;
        pal.save();
        JsonObject j = new JsonObject();
        j.addProperty("Success", 200);
        j.addProperty("msg", msgsucess);
        renderJSON(j);
    }

}

Minha aplicação Android:
public class FormPalhetasActivity extends Activity implements AdapterView.OnItemSelectedListener, LocationListener {

double latitude = 0;
double longitude = 0;
public static final String TAG = "LOG";
public static final String REGISTER_URL = "http://192.168.0.108:9000/Services/cadastrarPalheta";
EditText frua, fbairro, fcompl, fcidade, festado, fpais, fobs, fcod;
public static final String KEY_USERNAME = "username";
public static final String KEY_ADDRESS = "address";
public static final String KEY_DISTRICT = "district";
public static final String KEY_COMPLEMENT = "complement";
public static final String KEY_CITY = "city";
public static final String KEY_STATE = "state";
public static final String KEY_NOTE = "note";
public static final String KEY_COD = "codigo";
public static final String KEY_LOCALE = "local";
public static final String KEY_DATE = "date";
public static final String KEY_LAT = "latitude";
public static final String KEY_LONG = "longitude";
String fmatr, flocal, fdata;
SimpleDateFormat formataData = new SimpleDateFormat("dd-MM-yyyy");
Date data = new Date();
String dataFormatada = formataData.format(data);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );

    setContentView( R.layout.activity_form_palhetas );
    Bundle inBundle = getIntent().getExtras();
    fmatr = inBundle.get("username").toString();
    frua = (EditText) findViewById(R.id.rua);
    fbairro = (EditText) findViewById(R.id.bairro);
    fcompl = (EditText) findViewById(R.id.compl);
    fcidade = (EditText) findViewById(R.id.cidade);
    festado = (EditText) findViewById(R.id.estado);
    fpais = (EditText) findViewById(R.id.pais);
    fobs = (EditText) findViewById(R.id.observacao);
    fcod = (EditText) findViewById(R.id.cod);

    // Spinner element
    Spinner spinner = (Spinner) findViewById(R.id.spinner);

    // Spinner click listener
    spinner.setOnItemSelectedListener(this);

    // Spinner Drop down elements
    List<String> categories = new ArrayList<String>();
    categories.add("Terreno baldio");
    categories.add("Esgoto a ceu aberto");
    categories.add("Lixo");
    categories.add("Piscina");
    categories.add("Construção");

    // Creating adapter for spinner
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

    // Drop down layout style - list view with radio button
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // attaching data adapter to spinner
    spinner.setAdapter(dataAdapter);

    readMyCurrentCoordinates();
    Button enviar = (Button) findViewById( R.id.enviar );

    enviar.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            registerForms();
        }
    } );
}
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState( outState );
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String item = parent.getItemAtPosition(position).toString();
    if(position == 0){
        flocal = "Terreno baldio";
    }else if(position == 1){
        flocal = "Esgoto a ceu aberto";
    }else if(position == 2){
        flocal = "Lixo";
    }else if(position == 3){
        flocal = "Piscina";
    }else if(position == 4){
        flocal = "Construção";
    }else if(position == 5){
        flocal = "Outros";
    }
}
public void registerForms() {

    final String address = frua.getText().toString().trim();
    final String district = fbairro.getText().toString().trim();
    final String city = fcidade.getText().toString().trim();
    final String complement = fcompl.getText().toString().trim();
    final String state = festado.getText().toString().trim();
    final String note = fobs.getText().toString().trim();
    final String code = fcod.getText().toString().trim();
    final String pais = fpais.getText().toString().trim();

    StringRequest stringRequest = new StringRequest( Request.Method.POST, REGISTER_URL+"?matricula="+fmatr + "&data_instalacao="+dataFormatada+"&local="+flocal
            +"&cod="+code+"&estado="+state+"&bairro="+district+"&rua="+address+"&complemento="+complement+"&pais="+pais+"&latitude="+latitude+"&longitude="+longitude
            +"&obs="+note,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if (response.contains("Erro")) {
                        Toast.makeText( FormPalhetasActivity.this, response, Toast.LENGTH_LONG ).show();

                    } else {
                        Intent intent = new Intent(FormPalhetasActivity.this, PrincipalActivity.class);
                        Toast.makeText( FormPalhetasActivity.this, response, Toast.LENGTH_LONG ).show();
                        startActivity(intent);
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText( FormPalhetasActivity.this, error.toString(), Toast.LENGTH_LONG ).show();
                    Log.i( TAG, "Lat: " + error );
                }
            } ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> map = new HashMap<String, String>();
            map.put( KEY_USERNAME, fmatr );
            map.put( KEY_ADDRESS, address );
            map.put( KEY_DISTRICT, district );
            map.put( KEY_COMPLEMENT, complement );
            map.put( KEY_CITY, city );
            map.put( KEY_NOTE, note );
            map.put( KEY_STATE, state );
            map.put( KEY_COD, code );
            map.put( KEY_LOCALE, flocal );
            map.put( KEY_DATE, dataFormatada );
            map.put( KEY_LAT, String.valueOf( latitude ) );
            map.put( KEY_LONG, String.valueOf( longitude ) );
            return map;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue( this );
    requestQueue.add( stringRequest );
}
}

Estou aprendendo agora a criar e consumir serviços, e estou com o seguinte erro ao executar o aplicativo:
com.android.volley.NoConnectionError: java.io.IOException: unexpected end of stream on Connection{192.168.0.108:9000, proxy=DIRECT@ hostAddress=192.168.0.108 cipherSuite=none protocol=http/1.1} (recycle count=0)

Comment: tente chamar o endereço no seu navegador e vê se obtém o resultado esperado, pode ser algum erro no lado do servidor.
Answer: Altere sua rota para POST e altere StringRequest stringRequest = new StringRequest( Request.Method.POST, REGISTER_URL+"?matricula="+fmatr + "&data_instalacao="+dataFormatada+"&local="+flocal +"&cod="+code+"&estado="+state+"&bairro="+district+"&rua="+address+"&complemento="+complement+"&pais="+pais+"&latitude="+latitude+"&longitude="+longitude+"&obs="+note,new Response.Listener<String>()
para isto:
StringRequest stringRequest = new StringRequest( Request.Method.POST, REGISTER_URL, new Response.Listener<String>()


Calling a function stored in array produces "Unexpected trailing closure" in Swift

Question: I'm using Swift 1.2
I've got an array where I store my functions/closures.
Declaration of the array:
var pillFunctions: [(String, position: CGPoint) -> Void]

Declaration of function:
private func setPill1(number: String, position: CGPoint) -> Void {
    pillLabel1.text = number
    pill1.frame.origin = position
}

Storing functions in array (my class extends UIView):
required init(coder: NSCoder) {
    super.init(coder: coder)
    pillFunctions = [
            setPill1, setPill2, setPill3, setPill4, setPill5
    ]
}

Calling it:
pillFunctions[1]("213", position: CGPointMake(1.0, 2.0))

I'm new to Swift but I hoped this would work.
What am I missing here?
Thanks
Krystian
Comment: **Where exactly** do you get **which** error? Basically your code should work. Try if it compiles if you remove the `private` modifier.
Comment: sorry @idmean, I got the error "Unexpected trailing closure" when calling the pillFunctions[1] function.
Answer: I've made a several mistakes.
First of all, I've had to initialize the array:
var pillFunctions: [(String, position: CGPoint) -> Void] = []

And the init function of my class was incorrect:
required init(coder: NSCoder) {
    super.init(coder: coder)

    self.pillFunctions = [ self.setPill1, self.setPill2, self.setPill3, self.setPill4, self.setPill5 ]
}

After these two changes, it started to work.
I'm not sure this is the best approach, only because "it works", doesn't mean it's good.
Comment: This looks more correct. Actually your initializer was correct, you just did not initialize `pillFunctions` before calling the super initializer. It is typical of the Swift compiler to produce errors at random locations if there is a mistake in an initializer.


Middleware que salva um user_id após uma requisição no adonis.js/node.js

Question: Eu possuo a seguinte tabela job:
job
--------------
id INTEGER PK,
name VARCHAR,
user_id INTEGER FK

Eu preciso salvar na coluna user_id o id do usuário que criou aquele registro.
Eu tentei criar este middleware:
'use strict'

class Auditory{
  async handle ({ request, auth }, next) {

    const userLogged= await auth.getUser()
    const idUser= userLogged.id

    request.user_id = idUser

    await next()
  }
}

module.exports = Auditoria
Eu coloquei um console.log() dentro do Auditory class, então eu sei que esse midlware está sendo chamado quando eu faço a requisição, porém o user_id não está sendo salvo no banco de dados.
Se eu coloco um console.log() no idUser eu obtenho o valor correto do id esperado, porém ao consultar no banco o que foi salvo, o user_id é null.
Estou esquecendo algo?
Eu não recebo do frontend o user_id, ficando por conta do backend salvar este dado através do token.
@Edit:
Gravação conforme solicitado:
async store ({ request }){

    let job= request.all()
    job = await Job.create(job)
    return job

}

Comment: não, o retorno da variável userLogged e idUsuario está conforme o esperado. O problema é que eu seto ele no request e ele salva como null, tentei settar no request.body e request antes e depois do await next() mas ambos os casos salvam o user_id como null
Comment: Está vindo `null` ? coloque um `console.log(userLogged)` verifique o que retornou
Comment: Coloque a parte da gravação?
Comment: `let job = request.all()`? aqui vem o valor? `user_id`?
Comment: "Eu não recebo do frontend o user_id, ficando por conta do backend salvar este dado através do token."
Comment: Isso eu sei `"Eu não recebo do frontend o user_id, ficando por conta do backend salvar este dado através do token."`? você pode resgatar no front - end somente o que precisa, dando um `return (request.all());` para ver o que ele retorna! entendeu
Comment: não estamos na mesma linha de raciocínio
Comment: o request.all() não possui o user_id
Comment: Então você testou? `request.all() não possui o user_id`?
Comment: não, minha ideia é colocar ele através do backend antes de salvar
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/100527/discussion-between-virgilio-novic-and-veronesecoms).
Answer: Com a ajuda do @Virgilio Novic consegui chegar no resultado esperado através da seguinte implementação:
Criei esse middleware:
class Auditoria {
    async handle ({ request, auth, }, next) {

        const usuarioLogado = await auth.getUser()

        request.user_id = usuarioLogado.id
        await next()
    }
}

No meu store eu crio um objeto user com os dados do request.all() e acrescento o user_id que veio do middleware:
async store ({ request }){

    const user = {...request.all(), user_id: request.user_id};
    const response = await User.create(user)

    return response

}

Meu principal problema foi achar que o request.all() iria conter o user_id do middleware, porém, o método request.all() é um método que não pega o dinamico criado pelo request do middleware.


Bootstrap Fixed Navbar Behavior

Question: Can somebody explain what is going on here?
I'm using bootstrap 3.3.7.
Why are .container elements invisible?

            Big Brother

Home

Messages

something

Invisible

Answer: Your
 is not invisible, it's hiding behind your navbar.
You're using a navbar that uses fixed positioning. This takes it out of the normal document flow where it doesn't take up space so the elements after it begin to flow as if it wasn't there.
If you add padding-top: 50px; to  you will see your
.
If you read through the Bootstrap Navbar Docs you'll notice a callout that says Body padding required.
Comment: So, I should always pad my body by the size of nav bar? If it is fixed-top
Comment: At the minimum, yes. Bootstrap's navbar starts at a height of 50px. It's up to you if you'd like a little extra padding or not.

Bootstrap Fixed Navbar Behavior


AWS NACL by HOSTNAME

Question: Is it possible to allow a Network ACL by a hostname? Not IP address.
For a certain subnet, I want to allow all outbound traffic to host.example.com (port 443) but deny everything else.
Comment: no. AWS ACL's only support IP's. For the use case you've presented you will need another third party control system... Iptables can do that, a proxy is a option too.
Answer: You can't.
NACLs only allow for IP addresses.
You could modify the outbound rule(s) in  your security group to only allow traffic to port 443/tcp, but you also won't be able to set it by host name; it's probably better than using a NACL since it won't apply to every other EC2 instance (ENI, actually) in the subnet and it will also apply to the other subnets in the VPN where you might move this host (quicker than changing all the subnets).

AWS NACL by HOSTNAME


How can I play Für Elise well?

Question: I've always heard that Für Elise is an extremely difficult piece to play well, despite being relatively easy in a technical sense.  An added challenge is that it's been extremely over-played (I'm just glad it's no longer a fashionable ringtone where I live).  I learned it as a kid but was never really happy with how I played it, and listening to "professional" recordings hasn't given me much insight.
So the question is, how can I play it well?  By that I mean: What should I focus on when playing this piece?

What should I emphasize?
It's usually played with a fairly large variation in tempo within a phrase.  How do I manage this?  How much is too much?
I'm kind of lost when it comes to the tone of the piece.  Parts seem melancholy, others joyous.  What should I be aiming for with each section and how can I keep them from sounding too distinct?
Comment: One of my favorite versions though many disagree but I tend to think that this is conveying the actual message that I think there is in the music http://www.youtube.com/watch?v=yAsDLGjMhFI
Comment: Another tricky point: should one emphasize the "downbeat" in the melody, or does the anacrusis just blur over it?
Answer: This is very much a matter of taste. You emphasize different things and get different interpretations. Others may love it, others may hate it. The most important thing is that it "works", but it can work in so many different ways. Just as an example, there's a temporary change of key in the section with the repeated bass notes. Say you want to emphasize the sudden Bb chord there. You could do it by doing a crescendo and some ritenuto to bring the Bb out. Or you could do a subito piano. Other ways probably work, too, maybe just bring the change A->Bb in the base line out... It would definitely be easier if you made a recording and then we could comment on it.
Anyway, here's a rough roadmap of how I would approach the piece (it's not a song! :p)

First the big picture: The piece has a clear form of ABACA. Every section is quite uniform and quite different from every other section. This is helpful because you don't have to do anything to make the piece both relatively interesting  and coherent. I would make sure that I make every section sound as a single unit and that different sections have clearly different characters. The A section sounds quite "neutral", B section is playful, and C is a little bit frightening.
Since the A section repeats (too much if you ask me), you don't have to care too much about the other sections being "too different". The A section will keep the piece in one piece. You can even take different tempi in different sections. Faster in B, maybe slower in C (not much of course!) The most important thing will be how you move from one section to another. It should sound natural, as if that's exactly what the music wants, not you.
The sections have internal structure and it's quite important in the music of that time that it "speaks". There must be words, sentences, punctuation, and so on. One could say that the first phrase are the first eight bars. It has two sentences of four bars and each sentence consists of two parts: the "Für Elise melody" and the arpeggios. I would play a phrase as one unit, which means, for example, not too much variation of tempo inside it. (A great deal of rubato without a great deal of skill in using it tends to break the music in too small ill-formed pieces thus making everything incomprehensible.) The sentences are separated by a slight breath and the parts of the sentences just by some small variation in tone. Then it repeats, and it's usually good to do something a bit different the second time. Maybe a tiny bit softer, or bring out a different "word" or something.
The second part of the A section begins with a sequence of four almost identical bars. I would play these as one descending unit, not emphasizing any single part. Then there's a short bridge type thing (which I find problematic to interpret satisfactorily) and the first part of the section returns. And then there's a repeat and you can vary a different thing than the last time.
In the B section one could at least play brighter. Use less pedal, articulate clearly and make sure the left hand stays in the background. In the C section, on the other hand, one could play darker. More pedal, heavier bass. Experiment with the balancing of chords; sometimes play the notes in a chord equally loud, sometimes play the top note louder than others, etc. Remember the horizontal line; not every chord is a stopping point. Instead, the longer phrases should still be there.
After all this complexish analysis, I would still try to play it "simply", not trying to do anything, just letting the music do itself, so to speak. To get to this you must learn the piece technically so well that it is easy to play. Then you can just listen and let the music do its thing.
Comment: This is helpful, thanks.  I won't upload a recording though ... 50% shame and 50% probably leading into too-narrow discussion :P
Comment: For the awkward octaves-and-minor-seconds phrase at the end of the A section, I find that it flows well when I play with a slight emphasis on the beat, and a slightly stronger emphasis on the right-hand beats: One-and-Two-and-THREE-and-One-and-TWO-and-Three-and-ONE-and-Two-and-THREE, with that final stressed THREE falling on the anacrusis of the next repetition of the A section.
Comment: That is: E-e-E-e-E!-e-E-e-E! d#-E-d#-E!-d#-E-d#-E!-d#-...
Answer: This will always be subjective, but I'd say subtle tempo changes are probably best (and yes, I'm aware that's a subjectively interpreted answer in itself!)
You want to demonstrate an awareness of the tempo changes, you want to give the listener the sense of that tempo change, but without taking it to extremes. Practice until you have control over the tempo changes without stalling or stuttering, and then experiment! Find where exactly you want to place those changes, and why - but I'd advise against taking to extremes.
However, as important as tempo is I'm not sure this is the most prominent factor. When I've heard this piece played by the masses, banging it out on the nearest piano and torturing all ears around (I only semi-jest), there's almost always one thing that's missing - and that's dynamic contrast, or at least a sensitivity to dynamic contrast. If you want to emphasize anything in this piece, make it the dynamics - again not to silly levels, but make sure they're there, master them then play around until you've found a contrast which you feel adds to the music.
Finally, be aware of your use of pedal - another thing that often remains constant with many, either drowning it out in swathes of pedal or avoiding it altogether. An awareness and knowledge of how the pedal can affect and change various parts of the piece will help to add another dimension to your performance.
Answer: Deceptively simple - the well-known bit anyway.  Later sections are a little more challenging.
Because of the simplicity, some pianists apply great wodges of 'expression'.   But this, the first Google came up with, plays it straight, at a fair lick!  It sounds very Beethoven!

We can always rely on Sally to wring every ounce of emotion from a piece!  Makes me nauseous, but you might like it.

Or there's this one.  What do you think?

How can I play Für Elise well?


Problemas em converter objeto num projeto Spring Boot

Question: Esse aqui é meu projeto

Quando vou submeter o formulário ele dá esse erro em tela

Se trata de um projeto Spring Boot, eu achei que não precisasse de uma classe converter para o combo de categoria, mas como deu a mensagem de erro eu resolvir criar a classe converter como pode ver abaixo;
<code>import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import br.com.armazem.model.Categoria;

public class CategoriaConverter implements Converter<String, Categoria> {

    @Override
    public Categoria convert(String codigo) {
        if (!StringUtils.isEmpty(codigo)) {
            Categoria categoria = new Categoria();
            categoria.setCodigo(Long.valueOf(codigo));
            return categoria;
        }
        return null;
    }

}
</code>
Sendo que mesmo assim ele continuar gerando erro, o que será que posso fazer?
Eu sou novo programador Spring Boot.
Answer: Não entendi muito bem mais se for converter uma string em long tenta isso,
categoria.setCodigo(Long.parseLong(c));
Comment: desculpe @Aderbal mas sua sugestão não ajuda muito, eu acho que meu problema é mais uma questão de configuração do Spring Boot do que a conversão propriamente dita.
Comment: Estou tentando submeter um combo num formulário num projeto Spring Boot


Character of action of permutations on a subset

Question: I have a problem involving characters of a certain $\mathbb C$$G$-module, where $G = S_n$. The module is the vector-space $V$ with basis $\{v(I) | I\subset\{1,...,n\},|I| = k\}$, where $k\le n$. With $\chi$ the character induced by the natural action of $S_n$ on $V$, the question asks to prove,
$(\chi,\chi )=min(k,n-k)+1$
But I am struggling to find a way to tackle this. My attempts have involved direct calculation but I didn't find a nice way to characterise the sum. I have also tried to deduce through applying similar ideas to those that are use when dealing with the normal permutation character. This included that the inner product is related to fixed points, or even related to the orbits of $V\times V$. But in all cases I can't see any way to characterise the orbits or fixed points.
I believe this problem has some connections with quite deep representation theory, but I would like a more combinatorial approach to the problem, seeing as I have only had a basic introduction to representation and character theory!
Comment: Whenever $\chi$ is a permutation character coming from a finite group acting on a set $X$, the inner product $(\chi,\chi)$ calculates the number of orbits on the diagonal action of $G$ on the set $X\times X$. I think this helps for it looks like the orbits would consist of pairs $(I_1,I_2)\in V\times V$ such that the size of $I_1\cap I_2$ is fixed. Haven't checked everything. Probably it is better to look at the complements, when $k$ is large.
Answer: Without loss of generality $k\leq n/2$ (otherwise replace $k$ by $n-k$, the modules are isomorphic via the complement map).  As Jyrki points out, it is enough to show that there are exactly $k+1$ orbits on $V\times V$. Certainly if $(a,b)$ and $(c,d)$ lie in the same orbit then $|a \cap b |=|c \cap d|$. This intersection can have any size between $0$ and $k$, because $k\leq n/2$. So there are at least $k+1$ orbits, and if we show all pairs $(a,b)$ with fixed $|a \cap b|$ lie in the same orbit then there are exactly $k+1$.
Suppose $|a \cap b| = r \leq k$. The subsets $a \cap b, a\setminus (a \cap b), b \setminus (a \cap b)$ are disjoint so we can choose a permutation $\pi \in S_n$ such that $\pi$ maps $a \cap b$ to $\{1,\ldots,r\}$, $a \setminus (a\cap b)$ to $\{r+1,\ldots,k\}$ and $b \setminus (a\cap b)$ to $\{ k+1,\ldots,k+(k-r)\}$. Then
$$ \pi (a,b) = (\{1,\ldots,k\}, \{1,\ldots,r\}\cup \{k+1\ldots,2k-r\})$$
and every such pair $(a,b)$ therefore lies in the orbit of $(\{1,\ldots,k\}, \{1,\ldots,r\}\cup \{k+1\ldots,2k-r\})$.
Comment: I was struggling with this for ages but didn't simplify it as smart as this. Cheers


Passing vars in javascript / jquery

Question: I have followed the following link and implemented the example for my own script.
Preview an image before it is uploaded
I have 8 file upload inputs followed by a img tag of it's own
<input type="file" name="file[]" accept="image/gif,image/jpeg" onchange="readURL(this,1);"/>

Now the javascript I modified
function readURL(input,cnum) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            var cimage = 'imagediv'+cnum;
            reader.onload = function (e) {
                $("#cimage")
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
  }     }
}

I did an alert(); within the javascript and the cimage var does get created properly.
However, the img doesn't change as it does in the example. I did try manually creating a function for each imagediv#, and it works fine.
Am I missing something within the javascript ?
Answer: You need to take "cimage" out of the quotes and instead concatenate it to "#":
$("#"+cimage)

Or, better yet, don't bother with creating the cimage variable at all and just do this:
$("#imagediv" + cnum)

Answer: Change your selector:
$("#" + cimage).attr("src", e.target.result).width(150).height(200);

Your selector $("#cimage") is looking for an element with id="cimage".

Passing vars in javascript / jquery


Should the picking hand little finger be resting on the guitar?

Question: I notice I tend to rest the little finger of my picking hand on the body of my guitar, typically on the edge of the sound-hole, for greater accuracy and steadiness of the picking hand.
After extended periods of time this finger can start to ache, which makes me wonder if using it like this can cause injury in the long-term.
Is it ideal to use this finger like this or not?
Answer: I don't think there's an ideal or not ideal. It can be a good technique for accuracy, but you lose speed. It is worthwhile having as another technique in your arsenal.
I use it a lot and I think practice will make it less of a strain for you, but you will also find that you can improve your free hand accuracy over time anyway so you'll probably end up only using it for specific runs or sections..
Answer: I find that anchoring my hand like this limits my range of motion to an unacceptable degree, so I try to avoid it.
Answer: I had a teacher who told me to do this and at the time it was great. I wasn't getting into very advanced playing so I didn't need that extra mobility.
There's nothing wrong with doing it, but you won't always want to because it does limit your mobility in you picking hand. Also, if it's causing any pain, you really shouldn't do it. It won't go away, and it could cause long term injury. You should either find a different way of anchoring your pinky or stop doing it altogether.
Answer: It's a matter of some contention...  There are those who maintain you shouldn't and others who do it all the time.
I do so if I'm "Travis picking", seems to help with accuracy.  However, not when I'm playing jazzy complex chords as I use more fingers...
And never when flatpicking.
Answer: Actually this is not a very good technique.
You are not supposed to rest your finger. If you watch famous guitarist, you 'll probably see that they follow this technique, but they only use it while performing, and, I guess, without noticing it.
For example, Jimi Hendrix, Eric Clapton, John Frusciante, etc.
But of course you know you are not Jimi Hendrix, and even these players, I believe try to avoid resting the little finger while they practice.
If you want to check what's the best technique, you should definitely see videos of great Jazz player, who usually have an excellent technique even while performing.
For instance, you can check Scott Henderson giving tips in this video:
http://www.youtube.com/watch?v=Sm_VSjadCiU
Check his picking hand! ;-)
Answer: Maybe you should, maybe you shouldn't. The fact is that a lot of guitar players do this (John Frusciante comes to mind):

I personally tried to do this but didn't find it helpful. If some day you find yourself really uncomfortable doing it, you'll just stop. In fact, people tend to overstate the power of habit: it's not like it will take you years to stop doing it. While it helps you, stick with it.
Comment: I've seen Frank Gambale do it too - now and again.
Answer: When I first started to learn the default seemed to be to place the little finger to anchor. As I progressed I found that naturally I was actually doing it less and less. What I would say was that it did help in the beginning as it encourages your muscle memory for where the strings are, I think that is the logic behind it.


SetInterval runs only one time

Question: I'm trying to display the time on a clock that I created on my website, so I used the setInterval to display the time every seconds.
But it only runs once and I don't know what to do.
However, Firefox doesn't notice any error in my code.
var date = new Date(); //Time of the clock in-game
var hours;
var minutes;
var seconds;

var display_hours; // Displayers for the time
var display_minutes;
var display_seconds;

window.onload = function() {
    display_hours = document.getElementById("hour");
    display_minutes = document.getElementById("minute");
    display_seconds = document.getElementById("second");
};

function time_on() {
    hours = date.getHours();
    if (hours < 10) {
        hours = "0" + hours;
    };
    minutes = date.getMinutes();
    if (minutes < 10) {
        minutes = "0" + minutes;
    };
    seconds = date.getSeconds();
    if (seconds < 10) {
        seconds = "0" + seconds;
    };

    display_hours.textContent = hours;
    display_minutes.textContent = minutes;
    display_seconds.textContent = seconds;
};

var go_time = setInterval(time_on, 1000); // Display time on the clock every seconds

I want to be able to clear this interval later in the code.
Comment: Why are you defining `go_time` twice?
Answer: My guess is that window.onload triggers after you already created the interval, so inside the interval handler, display_{hours,minutes,seconds} are undefined and cause your code to crash.
Try starting the interval from within the onload handler:
window.onload = function() {
    display_hours = document.getElementById("hour");
    display_minutes = document.getElementById("minute");
    display_seconds = document.getElementById("second");
    var go_time = setInterval(time_on, 1000);
};

EDIT: also, make sure you actually update date each time:
function time_on() {
  date = new Date();
  ...
}

Comment: It doesn't work neither : the time is diplayed one time and that's all
Comment: See edit: you don't update `date` ;D
Comment: It's working, thanks a lot. When I think about it, it makes sense
Comment: Another option, is just place your script just before body close tag.
Answer: This is a simple clock:
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
return i;
}

and in the body put this:

Comment: "try this" is not an answer. What have you changed and why?
Comment: The problem is that I want to clear the interval later so I have to put it in a var, is it right ?

SetInterval runs only one time


Sharing the same document root - except for a folder and a file

Question: I have two websites, websitea and websiteb.
I have them both pointing to the same document root and all works fine, however I want websitea to have different db details to websiteb.
Database details are stored in /config/database.php
I could just write an if statement in that php file to tell it which database details to use depending on the hostname, however I am going to add another 10 websites like this, and that is going to get a pain very fast.
The second issue is I have a folder called /images/ which contains user uploaded pictures, these again need to be different.
When I was first thinking about it, I thought I could use apaches alias's - however thats not going to work with php, as doing
<?php include('config/database.php');?>

will not follow the alias (not a web request, it's a local dir lookup) and thus will fail.
So I am a bit stuck :)
Anyone have any thoughts?
Answer: Just use symlinks for all files and directories in the site's root folder.
Answer: I have a couple solutions that you may want to consider, but they do have downsides, they also assume that you are using Linux, or another *nix.
One option you could use here is to use unionfs.  Unionfs is basically provides a method to combine two filesystems.  The downside here is that unionfs isn't available in all systems by default. You may have to recompile a kernel.
So basically you could setup something that looks like this
/srv/www/basefolder (all the common files
/srv/www/localstuff/site1.example.org (files unique to a specific site)
/srv/www/localstuff/site2.example.org
/srv/www/localstuff/siten.example.org
/srv/www/unions/site1.example.org (unionfs ro:/srv/www/basefolder + rw:/srv/www/localstuff/site1.example.org)
/srv/www/unions/site2.example.org (unionfs ro:/srv/www/basefolder + rw:/srv/www/localstuff/site2.example.org)
/srv/www/unions/siten.example.org (unionfs ro:/srv/www/basefolder + rw:/srv/www/localstuff/siten.example.org)

Another option would be to simply use hardlinks.  Setting this up is pretty easy to do using rsync.  The downside of this is that you make break something for many sites, if you aren't paying attention.  If you forget you have hard-linked everything together, and you make a change to the files in one location, that changes in all locations.   You will also need to re-run the rsync command whenever you update files.
/srv/www/basefolder (all the common files
/srv/www/site1.example.org
/srv/www/site2.example.org

Use commands like this to build this structure
rsync -vr /srv/www/basefolder /srv/www/site1.example.org --link-dest /srv/www/basefolder
rsync -vr /srv/www/basefolder /srv/www/site2.example.org --link-dest /srv/www/basefolder

Comment: This is similar to what I have now - and want to move away from. (rsync - hard links)
Answer: Is placing all the common content in a separate place and creating many docroots with different config files and images folders and symlinks to common data directories an option? You can even create a bash script for automatic deployment of this structure.
Comment: This is similar to what I got, and want to move away from. Thanks :)
Answer: It isn't clear what uses the /images/ folder or how many php scripts you have.
However, it would be possible to rewrite the php to use config/HTTP_HOST.database.php so it scales as you add virtualhosts.  If the php code uses the /images or creates the links to /images it could be rewritten to use HTTP_HOST as well (passed in from Apache).  If the links come from another app you could use apache rewrite rules to put the vhost info in requests for /images/ so you end up with dirs that look like /images/ but map to unique things on disk.
More info on HTTP_HOST in php:
http://lab.artlung.com/echo-http-host/
This solution would eliminate the need to duplicate data for each user deployment, but does require code changes and perhaps rewrite rules in apache.


Sitecore 6.5 urls across multiple sites/domains (not resolving sites?)

Question: I'm using a Sitecore install with multiple sites. When linking from example1.com (/sitecore/content/example1) to an item under example2.com (/sitecore/content/example2/about)
Sitecore is not generating the link correctly for any cross-domain links. It is generating:
http://www.example1.com/example2/about.aspx
This is what is expected:
http://www.example2.com/about.aspx
The same thing happens from example2.com when linking to example1.com or any item under that site.

Both sites are defined in the web.config.
The rootNodes are both "/sitecore/content"
The start items are "/example1" and "/example2" respectively.
Rendering.SiteResolving is set to true
Rendering.SiteResolvingMatchCurrentSite is set to false
I'm using sc:link to generate the links.
Sitecore.Links.LinkProvider's alwaysIncludeServerUrl is set to true
Answer: If you are using hostName with wild cards (eg. "www.example1.com|example1.com"), you need to set targetHostName="www.example1.com" on your  entry.
Even if you only have one domain, set targetHostName, as there is one thing/function that only looks at targetHostName. Eg. GetItemUrl() doesn't work as planned without a targetHostName and in 6.5.0 ver. 120706 it doesn't account for stuff set in the web.config. This is a bug and one they hopefully have fixed in future version. If you expirience the problem look here for a solution:
http://sitecorepm.wordpress.com/2010/08/04/using-cross-site-links-dynamic-links/
Answer: Have you set the hostName value of the <site> entry in web.config?
<code><site name="example1" hostName="www.example1.com" ... />
<site name="example2" hostName="www.example2.com" ... />
</code>
There's a very good blog post on this here: http://blog.paulgeorge.co.uk/2011/05/01/sitecore-linkmanager-inside-out-muti-site-and-sub-site-setups/  It looks like you've covered everything else required to make this work.


Is it safe to use ngx permissions in angular for acl management?

Question: I am using angular 6 and I want to control access of users. As far as I know it is recommended to manage acl in the backend but, angular has some packeges such as ngx permissions to do it in frontend. Is it safe to use its features? Or I'm in a wrong foot!?
Answer: No it is not safe to only manage your security in your front-end application.
If you have an Angular application, it is very likely that it connects to some back-end API, which must be secured.
Let's take a simple example.

You have a Save button
When clicking the Save button, it calls your API to create or update a record

You can easily hide the Save button or prevent the calls to your API, possibly using ngx permissions.
However nothing prevents the user to find out that the button is making that call and perform the call outside of your application. So your API must be secured.
"Securing" your front-end application is only a mean to provide a better user experience.
There is also a warning mentioned by the author if ngx-permissions
Answer: If your angular app does have no connection to a backend (REST service) then it would be ok - then it is the only way. But if you are connected to some sort of service that is published via an interface you should build some security there too.