Should we have a tag for Family Economics?

Question: In this question, the OP points out that we have no tag for Family Economics, which can reasonably be claimed to be a sub-field of economics (see here).  My only doubt about having such a tag is whether Household Economics, which is a largely overlapping sub-field (see here), would be more appropriate (or whether it would be useful to have both).  Differences between them could arise from a) households not occupied by traditional families; b) families in which members live apart.  Any views?
Update 7/2/18.
Voting to date seems to indicate a majority preference for adding synonyms to the demographics tag, but not adding a family economics tag.  I've added an answer to allow voting on the combination, ie adding the synonyms and the new tag.
Comment: Per Ubiquitous's answer, I think we should create the tag. There's very little downside and potentially quite a bit of upside to those that want to follow that tag.
Comment: I always seen family economics as a field dominated by sociologists and not economists. Based on what i've been exposed to in the past I personally dont think the tag is necessary. I personally think this is due to the fact sociologists see economics simply as apart of conflict theory and not as a branch isolated from non-economic social phenomenon.
Comment: A demographics tag and household economics tag both do not seem like they'd cause much clutter and could be helpful.
Comment: @KitsuneCavalry if you are advocating separate tags, could you post that suggestion as an answer so that people can vote on it?
Answer: Here are some relevant parts of the JEL classification, which might offer some guidance
D1: Household Behavior and Family Economics
    D10: General
    D11: Consumer Economics: Theory
    D12: Consumer Economics: Empirical Analysis
    D13: Household Production and Intrahousehold Allocation
    D14: Household Saving • Personal Finance
    D15: Intertemporal Household Choice • Life Cycle Models and Saving
    D18: Consumer Protection
    D19: Other

J1: Demographic Economics
    J10: General
    J11: Demographic Trends, Macroeconomic Effects, and Forecasts
    J12: Marriage • Marital Dissolution • Family Structure • Domestic Abuse
    J13: Fertility • Family Planning • Child Care • Children • Youth
    J14: Economics of the Elderly • Economics of the Handicapped • Non-Labor Market Discrimination
    J15: Economics of Minorities, Races, Indigenous Peoples, and Immigrants • Non-labor Discrimination
    J16: Economics of Gender • Non-labor Discrimination
    J17: Value of Life • Forgone Income
    J18: Public Policy
    J19: Other

According to the JEL classification, most of the topics meant by the poster of the linked question fall under the demographic economics area, for which we have a tag demographics.
So an alternative to creating a new tag would be to create some synonyms that link marriage, fertility etc., to demographics. We can edit the tag wiki to make clear the expanded scope of demographics. I am not advocating for this alternative, only putting it on the table.
Comment: (+1) ...but your answer reminded me of an old proposal of mine that was met with universal rejection back then... unavoidably, I will now re-propose it in a little while!
Comment: @AdamBailey I have created synonyms from fertility, marriage, and family-economics to [tag:demograpics]. I have also created a tag wiki for demographics explaining the scope of its usage.
Comment: This seems to be the preferred option.  Would someone like to implement (I don't think I have the necessary rep on the tag to do so myself)?
Answer: I would not be opposed to making demographics as well as a family-economics separate tags, considering they have different JEL classifications. It would not be too much clutter to have them both I think.
Answer: I was the person who raised this question and I would like to propose a different solution. Economics is sometime, correctly in my view, accused of 0f having a rather clueless androcentric viewpoint. At the time of my post, it seemed to me that the list of available topics would lend support to someone of that view, and this seemed to me to be less than ideal.
I endorse the idea of multiple quasi-synonyms. Whatever term is chosen, this is a radial category and a person seeking information on one of the peripheral extensions out from whatever center is chosen may not see what holds the categories together or anticipate the identity of conceptual hub. Certainly I would never have guessed that anyone would have categorized my question in demographics, as I was asking about the welfare consequences  of smaller households, not about fertility decisions. But I don't really care for any of the alternatives above, including the one I originally suggested.
If it were just up to me, I would call the category I was requesting "Feminist Economics," though "anti-Feminist economics" would link all the same topics together. I suspect this group would prefer something a bit more ideologically neutral. I believe that if we as economists don't want to be clueless about women's interests and child wellbeing and how they might be different from men's and adults', if we don't want to sweep gender concerns under the rug, or assume that husband and wife are one and that one is the husband, then it makes sense to chose a central category that recognizes that such issues are real and makes it easier to find information about them.
Seriously, look at the list of topics under "Demographic Economics." How many of them would be of any interest to a demographer? Certainly 314, 315, 316 and 317 have nothing at all to do with demography, and even in 312 and 313 -- domestic abuse? Child care? Youth? What were they thinking? This grouping of topics under that heading makes sense only if you regard child bearing and rearing as an economically valuable service that women render to men.
My suggestion is to call the topic Gender & Family Economics. That is a much more sensible name for everything currently listed under demographic economics except 311 (and perhaps fertility under 313), and in my view would also  naturally subsume the heading D13: Household Production and Intrahousehold Allocation under Household Behavior and Family Economics.
Note that D13 is the only topic listed under Household Behavior and Family Economics that does not fit more naturally under the heading Consumer Economics and Intertemporal Choice. I believe the "Family Economics" in the name of this subject arises as a historical remnant from the time when there was a substantial subfield, and even many departments, in Home Economics, teaching women to make good decisions as consumers. My undergraduate Alma Mater Cornell U. had such a department, though it, like most such departments, had been renamed as a department of Consumer Economics (and Housing) by the time I got there, and appears to have since been abolished.
Answer: I think the suggestions of @Ubiquitous (synonyms linking to demographics) and @Kitsune Cavalry (family economics as a tag) are both good.  I'm posting this as an answer to allow voting on the combination.


InvalidOperationException: Invalid attempt to read when no data is present. (SQL)

Question:     void ExecuteContent()
{
    StringBuilder sb = new StringBuilder();
    sb.Append("SELECT TOP 1 @UsersID,u.Avatar,t.Date, u.Name, t.ThreadTitle, t.ThreadParagraph");
     sb.Append(" FROM Users as u");
     sb.Append(" INNER JOIN Threads as t ON u.UsersID = t.UsersID");
     sb.Append(" Where @UsersID=t.UsersID");
     sb.Append(" ORDER BY t.Date DESC");

     using (SqlConnection conn = new SqlConnection(AnswerQuestion.connectionString))
     {
         conn.Open();
         SqlCommand sqlComm = new SqlCommand(sb.ToString(), conn);
        MembershipUser CurrentUser = Membership.GetUser();
         Guid i = (Guid)CurrentUser.ProviderUserKey;
         sqlComm.Parameters.Add("@UsersID", SqlDbType.UniqueIdentifier).Value = i;
         SqlDataReader dr = sqlComm.ExecuteReader();

         UserName = dr["Name"].ToString();//The exception is thrown here
         Image = (Image) dr["Avatar"];
         ThreadTitle = dr["ThreadTitle"].ToString();
         ThreadParagraph = dr["ThreadParagraph"].ToString();
         Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString());
     }

}

I dont understand why I get it. All i am trying to do is to get the last person who posted the thread.. I looked at debugging, and things seem fine. I also looked at the sql server in visual studio 2010.. there is data,,but somehow it is not being read and an exception is thrown... :(
Answer: You should check for dr.Read() before accessing the values:
if(dr.Read())
{
    UserName = dr["Name"].ToString();//The exception is thrown here
    Image = (Image) dr["Avatar"];
    ThreadTitle = dr["ThreadTitle"].ToString();
    ThreadParagraph = dr["ThreadParagraph"].ToString();
    Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString());
}

Comment: Additionally you should check whether there are any results: if (dr.HasRows) { ...
Comment: Peter, i prefer to use dr.Read.. But i do know that i have data in the database. cause i entered it and saw
Answer: You must loop trough your reader:
while(dr.Read())
{
    serName = dr["Name"].ToString();//The exception is thrown here
         Image = (Image) dr["Avatar"];
         ThreadTitle = dr["ThreadTitle"].ToString();
         ThreadParagraph = dr["ThreadParagraph"].ToString();
         Time = (DateTime)AllQuestionsPresented.TryParse(dr["Date"].ToString());
}

or if(dr.Read()) if you only have one result
And
You should always surround you Reader with a using:
using(dr)
{
    while(dr.Read())
    {
    }
}

And you should do some null check before you call ToString();
ThreadParagraph = dr["ThreadParagraph"] == null ? "" : dr["ThreadParagraph"].ToString();

And here's a little tip to write queries in code, use verbatim:
var query = @"SELECT TOP 1 @UsersID,u.Avatar,t.Date, u.Name, t.ThreadTitle, t.ThreadParagraph
    FROM Users as u
    INNER JOIN Threads as t ON u.UsersID = t.UsersID
    Where @UsersID=t.UsersID ORDER BY t.Date DESC";

Comment: What do u mean by verbatim.. and why do u use var query and not stringbuilder?
Comment: var query is a string. Look here for more info on the verbatim sign: http://en.csharp-online.net/CSharp_FAQ:_What_is_a_verbatim_string_literal
Comment: I get nulls in the properties..as if nothing is in the database..i get null for ThreadParagraph and the rest...
Comment: I see where the problem is.. For some reason i have a problem in an insert statement that i didnt present here. it worked..But now it stopped working.. i need to check why:( ..thanks for the help... i did a DBnull.Value.Equals(dr["Image"]) and more null checks


How to override a service provided by a contrib module?

Question: I need to override Validator class from Telephone Validations contrib module.
I tried the both static and dynamic methods described here:
https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services
namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\Core\DependencyInjection\ServiceModifierInterface;
// @note: You only need Reference, if you want to change service arguments.
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the language manager service.
 */

class MyServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides language_manager class to test domain language negotiation.
    // Adds entity_type.manager service as an additional argument.
    $definition = $container->getDefinition('telephone_validation.validator');
    $definition->setClass('Drupal\mymodule\MyValidator');

    $definition->addArgument(new Reference('country_manager'));
  }

}

and also static:
services:
  telephone_validation.validator:
    class: Drupal\mymodule\MyValidator
    arguments: ['@country_manager']

but it the both methods do not work, Drupal still uses Validator class form oroginal module
Also I tried modified method described here:
https://github.com/RikdeBoer/service_overrider
class MyServiceProvider implements ServiceModifierInterface {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides language_manager class to test domain language negotiation.
    // Adds entity_type.manager service as an additional argument.
    $definition = $container->getDefinition('telephone_validation.validator');
    $definition->setClass('Drupal\mymodule\MyValidator');

    $definition->addArgument(new Reference('country_manager'));
  }

}

The result is the same: MyValidator class is not used instead of default Validator class.
So what I am doing wrong?
Comment: See the linked doc for the correct class name, try `MymoduleServiceProvider`.
Comment: thanks, I somehow skipped the description:  the name of this class is required to be a CamelCase version of your module's machine name followed by ServiceProvider
Answer: The name of your Class must be MyModuleServiceProvider.
You can the documentation here: Altering existing services, providing dynamic services

Note that if you want this service alteration to be recognized
automatically, the name of this class is required to be a PascalCase
version of your module's machine name followed by ServiceProvider, it
is required to be in your module's top-level namespace
Drupal\your_module, and it must implement
\Drupal\Core\DependencyInjection\ServiceModifierInterface (which
ServiceProviderBase does).

This must solve your issue.


Giving message according to if check

Question: In a framework, i use below code. However, i always give success message
  if ($artistID)
                NCore::db('PERSON_MOVIE')->insertAsArray(array('PERSON_ID' => $artistID->id, 'MOVIE_ID' => $movieID, 'JOB_ID' => 374));
            else
                header('Location: http://www.sinemalar.com/management/artistAddEditRemove/');

This is the message

How can give a message according to else statement ? This is my js. What might be the changes?

Comment: I think it's a bit vague, your back end code seems to either redirect the user or save data in the database, it doesn't return any messages to be used.
Answer: Try this :
if(success=="a"){
    alert("Done")
    }else {
    alert("Something went wrong")
};

Giving message according to if check


var, const ou let? Qual usar?

Question: Recentemente descobri a existência do let e const mas agora estou na dúvida qual usar constantemente?
E por que nunca vejo códigos com let ou const?
Answer: Versão curta:
Quando devo usar:

var: nunca mais
const: sempre que possível
let: quando a variável precisar de ser sobreescrita

Versão longa:
A versão 6 da ECMAScript trouxe consigo novos comandos para declarar variáveis, o let e o const. Isto veio, finalmente corrigir problemas que o var tinha, e na prática não devemos usar mais var. Continua a ser importante declarar variáveis mas agora temos duas opções:

const

O const deve ser usado em casos onde a variável não precise ser reatribuída, sobrescrita. Esta é a maioria dos casos. O const bloqueia a variável a um valor constante e vai dar erro se for reatribuída, ela fica como que em "modo só de leitura`, então:
const a = 10;
a = 20; // vai dar erro

mas vale a pena observar que const obj = {} permite modificar o objeto, com por exemplo obj.foo = 'bar' mas não permite re-declarar const obj = {novo: 'objeto'}.

let

O let é a nova maneira de declarar variáveis que precisam ser sobrescritas. O caso mais comum é uma iteração de um loop, onde a variável a iterar é sobrescrita N vezes durante o loop.
Caracteristicas em comum de let e const:

Ambos let e const não permitem que uma variável seja re-declarada. Tal era permitido com var, sem que avisos fossem dados, criando bugs difíceis de detectar.
Ambas declaram a variável no escopo e bloco em que estão, não permitindo dentro da mesma função ou bloco re-declarar a mesma variável.

Estas novas versões ainda não são usadas diretamente nos browsers porque o suporte ainda não é universal, mas usam-se já em ambientes pré-transpilados. O var é portanto desaconselhado em código novo.
Comment: Isso vale para Javascript e typescript?
Comment: @Luhhh sim, é questão de boas práticas para evitar erros. O typescript ajuda a minimizar o problema, mas a resposta é válida na mesma

var, const ou let? Qual usar?


Notation for the set of all tuples whose elements are all part of a particular set

Question: So, for example, let's say we have A = {3,6,1}
I would like to generate a set B which is such that the elements of B are tuples. Each tuple is such that if x is an element of the tuple then x is an element of A. Additionally, there are no repeated elements in any given tuple (each element of a given tuple is distinct).
If A contains x number of elements, then B should contain all the tuples (meeting the distinctness restriction) with 1 element, all the tuples with 2 elements, ...., all the tuples with x elements.
So in our example, B would be:
B = { (3) , (6) , (1) , (3,6) , (3,1) , (6,3) , (6,1) , (1,6), (1,3) , (3,6,1) , (3,1,6) , (6,3,1) , (6,1,3) , (1,3,6) , (1,6,3) }
so basically if A has x amount of elements, B is like the set of all permutations of A, taken x elements at a time, taken x-1 elements at a time, taken x-2 elements at a time,..., taken 1 element at a time. ....but instead of basic sets we have tuples.
Now, furthermore, I would like to have another set, C, which is such that x is an element of C iff x is an element of B, and x is such that its first element is less than its second (if there is a second), its second element is less than its third (if there is a third), etc...
(with "less than" being the standard less than relation among integers)
So we would get:
C = { (3) , (6) , (1) , (3,6) , (1,6) , (1,3) , (1,3,6) }
Thanks
Answer: Interpreting the $n$-tuples with no repeated entries as injective functions from $[n]=\{0,1,2,\dots,n-1\}$ to $A$, and adopting the notation that $Y^{\underline{X}}$ is the set of all injective functions from $X$ to $Y$, then you could notate it as:
$B = \bigcup\limits_{n=1}^\infty A^{\underline{[n]}}$
As for denoting $C$, I think you would have an easier time referring instead to the power set of $A$ (without the emptyset) and reinterpret each set appearing as a tuple with entries in ascending order.
$C\simeq \mathcal{P}(A)\setminus\{\emptyset\}$
In terms of counting how large each set is, $|B|=\sum\limits_{n=1}^\infty |A|^{\underline{n}}$ using falling factorial notation and $|C|=2^{|A|}-1$ (if you removed the emptyset)
Comment: I was in the middle of writing an answer with an identical suggestion, which leads me to think the notation is not so unnatural after all :) The notation $A^{\underline{[n]}}$ is by analogy with the falling factorial ([Wikipedia](https://en.wikipedia.org/wiki/Falling_and_rising_factorials)). (And I've also seen the notation $\binom{A}{k}$ to mean "the set of all $k$-element subsets of $A$".)
Comment: In regards to B, it is ok that we have the union going to infinity, as opposed to having |n| above the union sign (where |n| = size of [n])? n doesn't really go to infinity if the size of [n] = 3, no?
Comment: @Boolean_functions it is fine since there exist no injections from a set $X$ to a set $Y$ if $|X|>|Y|$.  Of course, you could stop at $|A|$ instead of continuing past.  Once we have passed $|A|$ then we are continually unioning the emptyset which has no further effect on the outcome.  $\bigcup\limits_{ n=1}^\infty A^{\underline{[ n]}} = \bigcup\limits_{n =1}^{|A|} A^{\underline{[n]}}$
Comment: Also just to help clarify for myself...B is the union of all  sets whose elements are also sets (they are sets of all particular injective functions...and functions are defined as sets). And so the elements of our union B, will be all these particular injective functions (sets)?   ...So now, if you _had to_ define C in terms of B (i.e., define C as being such that x is an element of C if x is an element of B and x meets the less than requirement), how would you do so? Since the elements of B _are sets_ and not tuples and since {2,3,5} is the same set as {3,5,2}...how would we be able to get
Comment: to get the tuples? That is, how would we be able to say something like "...also, each x in B must meet the requirement that the elements (of the tuples which don't exist in B) are ordered via less than relation...in order for x to be in C."  And also thanks for your last response, that clears that up.
Comment: Since {2,3,5} would _not_ be metting the "less than requirement" since {2,3,5} = {3,5,2} and that's not what we want. Again, thanks
Comment: @Boolean_functions why would you want to define $C$ from $B$ instead of directly from $A$?  Before we continue the discussion further, you need to keep in mind how tuples are defined.  One definition is that it is an $n$-tuple is an element of the cartesian product $\underbrace{A\times A\times \dots \times A}_{n~\text{times}}$.  A different yet equivalent definition however is that it is an injective function from $[n]$ to $A$ where $f(k-1)$ corresponds to the $k$'th entry in the tuple.
Comment: Well at first I didn't realize I could define C that easily from B...and now I'm just curious because I like notational matters
Comment: @Boolean_functions Although functions are technically sets, here there is absolutely no confusion since the $3$-tuple $(2,3,5)$ can be canonically expressed as the function $f(k)$ from $[3]$ to $A$ where $f(0)=2, f(1)=3, f(2)=5$.  This is different than the $3$-tuple $(3,5,2)$ which is instead the function $g(k)$ where $g(0)=3, g(1)=5, g(2)=2$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/44221/discussion-between-boolean-functions-and-jmoravitz).


Avoid `delete[]` accepting an implicit pointer conversion?

Question: I have a class with an implicit conversion operator to a pointer. Deallocating that pointer is not valid. Can I prevent the conversion to a pointer when used with the delete[] operator? I would like a compile time error. For the free function, I can delete an overload that takes the class as an argument.
void foobar(double*){}

struct A {
  // Please pretend I have a good reason for doing this.
  operator double*() const { return nullptr; }
};

void free(A&) = delete;

int main(){
  A a;

  // Just works TM
  foobar(a);

  // This compiles :(
  delete[] a;
  // This does not :)
  //free(a);
  return 0;
}

I think something clever would be needed for the desired effect.

A use case for implicit conversion: Say A implements a scoped array. Conversion makes A almost a drop in replacement for an alloc/dealloc pair. Templates and iterators requiring explicit conversion. Otherwise the call sites of c-like functions remain unchanged.
Comment: Do you need the conversion operator to be implicit? Marking it `explicit` would solve the problem.
Comment: You could add a `operator void*() const { return nullptr; }` to make it an ambiguous situation.
Comment: Although `std::free(a)` would compile even with your code
Comment: @Eljay That seems to be an answer! With limited use so far, I'm not seeing other inconvenient ambiguities either. Might still have some though. Side effect of  `-Wdelete-incomplete` existing instead of just being an error.
Comment: Do you really need a *conversion operator*, and not a simpler method? `double* A::toDoublePtr() const { return ...; }`
Comment: @RemyLebeau Probably better to go with C++20 [`std::to_address()`](https://en.cppreference.com/w/cpp/memory/to_address) by specializing `std::pointer_traits` if applicable.
Answer: As a workaround, you can prevent the conversion to a pointer when used with the delete[] operator by making the conversion ambiguous.
However, depending on the situation of the rest of the code, this may cause undesirable ambiguity for the desired use cases.
struct A {
  operator double*() const { return nullptr; }
  operator void*() const { return nullptr; }
};

Answer: Whenever it comes to stopping something at compile time you can think of using templates.
void foobar(double*){}

class A {
  // Please pretend I have a good reason for doing this.
  public :
  operator double*() const { return nullptr; }
  template<typename type>
  void operator delete[] (void*, type size);
};

template<typename type>
void free(void*);

template<>
void free(void*) = delete;

int main(){
  A a;

  // Just works TM
  foobar(a);

  // Now this will not compile to ! :(
  delete[] a;
  // This does not :)
  //free(a);
  return 0;
}

Comment: This didn't work. Without `delete[] a;` I still get "error: expected unqualified-id before 'delete'" @ `void delete[] (`...Tried compiling with `g++ -std=c++17 foo.cpp`
Comment: Actually , I have mistaken, therefore I have modified my answer and this finally works
Comment: The updated version compiles even **with** `delete[] a;`. The defined `delete` is not a candidate to be called. I'm not sure there is a way to make defining that operator work.


Which cumulative distribution of F(X) is equal to the cumulative distribution of its sample median (as sample statistics)

Question: We consider random sampling from a population in which the variable of interest $X$ has some cumulative distribution $F$. Next, we consider a simple random sample of size $n, X_1,\ldots,X_n,$ which are i.i.d. $F$. We then compute a sample statistic $T_n=T(X_1\ldots,X_n)$. Subsequently, we can think about the cumulative distribution of $T_n,$ which I will call $F_{tn}.$
The question is the following: given that we use $T_n$ = "sample median" -- thus, our sample statistic is the sample median -- for which distribution $F$ does the following hold: $F=F_{tn}$?
Comment: For which $n$ do you require these two distributions to be equal?  Just one $n$ (presumably not $n=1,$ though!) or for all $n$?
Comment: Thanks for your answer, this is the question that is asked. maybe we can ignore n=1
Comment: Right.  It may be useful to know $n=1$ and $n=2$ don't impose any constraints.
Answer: Let $F$ be the distribution of $X,$ as in the question, and $F_n$ be the distribution for a median $T_n$ of a sample of $n$ iid variables $X_i$ distributed like $X.$  (Since the median is usually not uniquely defined for even $n,$ we have to be a little open-minded about $T_n$ and $F_n$!  More about this below.)  Then, by the very definition of any median, for all real numbers $x$ the event $$T_n \le x$$ is identical to the event "at least $n/2$ of the $X_i$ are less than or equal to $x.$"  For any $i,$ the chance of $X_i \le x$ is given by $F(x)$ and because the $X_i$ are independent, the chance that $T_n \le x$ is given by a tail probability for the Binomial distribution with parameters $n$ and $F(x).$
Suppose $F=F_n$ for some $n$ to be determined as appropriate to produce interesting results.  The cases $n=1$ and $n=2$ yield no useful information, but consider the case $n=3.$  Then because "at least $n/2$" means "$2$ or $3$," we obtain
$$F(x) = F_3(x) = \Pr(T_3 \le x) = \binom{3}{2}F(x)^2(1-F(x)) + \binom{3}{3}F(x)^3.$$
This is a cubic equation in $F(x)$ whose only solutions are $\{0,1/2,1\}.$  This limits $X$ to random variables having positive probabilities of attaining at most two values (namely, the point where the jump from $0$ to $1/2$ occurs and the point where the jump from $1/2$ to $1$ occurs).  For nonconstant $X$ these are the affine transformations of Bernoulli$(1/2)$ variables.  In other words, either $X$ is constant or there exist distinct numbers $x_0, x_1$ and $$\Pr(X=x_0) = \Pr(X=x_1)=\frac{1}{2}.$$
For such variables to have the same distribution as the median $T_n$, you need to define medians in such a way that guarantees they are possible values of $X.$  However you do it, it's clear that for these "affine Bernoulli" variables the median also has equal chances of being either $x_0$ or $x_1$ and so obviously has the same distribution as $X$ itself.
Comment: Thanks for your answer. I read it several times, but I don't understand the what the answer is. Bernoulli or Binominal?
Comment: The answer is "the affine transformations of Bernoulli(1/2) variables."  The meaning of this is explained by the final equation, beginning with the bold text preceding it.
Comment: Many thanks for your answer. I'm sorry but I dont understand why you use  Binomial distribution? and why this (This is a cubic equation in F(x) whose only solutions are {0,1/2,1})?
Comment: Both are immediate applications of the definitions.
Comment: I'm sorry but I read several times and It is not understandable for me. However, I will try my best again. Billion Thanks for your reply.


What is the lowest scientific note on a piano (for sampling)?

Question: Why do these audio samples start at a different note on each loudness?  Pp starts at Bb0, mf starts at B0, and ff at A0. I'm wondering if the reason is because of some technical reason that I don't understand, or if the uploader just didn't make them or forgot them?
Also, is this image correct ?
Answer: The range shown in the last link is correct for almost any standard piano.
There are models with a narrower range (like those small pianos seen in living rooms of many american films and tv series, usually spanning 5-6 octaves), as there are others with a bigger extension (notably, the Bösendorfer Imperial which has a full lower octave extending to the C below the standard A0).
That said, most pianos have an 88-notes range, starting from A0 up to C8.
The reason for the samples you provided might vary.
Consider that sampling techniques can be very different: depending on the requirements and technical skills of the "sampler" (those who actually record the instrument, available microphones, etc).
"Low quality" piano samples often have just a few notes for each octave (sometimes every three half tones, but I've seen some with just one note per octave), while better samples have each note recorded and for many different levels of "velocity" ("dynamics").
One of the most important limits of sampling is that the more accurate sampling is (more notes, more dynamics), the more size it requires, which can be very important for performance, since a sampler engine usually loads all samples for every instrument; this means that loading time can be very long, and it occupies a lot of system resources.
Since lower notes are rarely played, those who created that sampling might have decided to decrease the memory footprint of the library by leaving out "less used notes". Maybe it was done just for convenience, or after careful analysis of the result (by comparing the given samples at different dynamics).
Consider that lower notes also have a much longer sustain (meaning: they occupy a lot of disk space). Take for instance the pianissimo of the Bb0 compared to the C8: the latter only takes 1.1mb, while the former is 6mb. Adding all levels for all (very rarely used) notes would have increased the size by at least 20-25mb.
Comment: What are these "small pianos seen in living rooms of many american films and tv series"?  Can you cite an example?  In my experience most small uprights, well more than 90%, have 88 keys.
Comment: @phoog I'm not sure, but I believe they're called "console pianos", they have shorter strings, slightly different mechanics and sometimes a smaller range. For example: https://i.stack.imgur.com/T1JXp.jpg


how to get value of n if the value of n * log n is given?

Question:
Possible Duplicate:
How can I solve for $n$ in the equation $n \log n = C$?

how to get value of n if the value of n * log n is given ?
I am stuck with this:
n log n = 6 * 10^6

how to tackle such equations ?
Comment: $\log$ is to the base 10? This specific problem can be done by inspection....
Comment: @Hurkyl yes. 10 can be used as the base. Mainly i am looking for approach to solve this so things can be assumed.
Comment: Does $n$ have to be integers?
Answer: If you can't solve it by inspection, it is unlikely there is a "nice" solution.  In that case you can use the fact that $\log n \ll n$ and varies slowly.  So in this problem, you can write it as $n=\frac {6 \cdot 10^6}{\log n}$  Then for a first guess use $n=6 \cdot 10^6$, take the log to get $6.778$, plug that in and evaluate $n$, iterating until it converges.
Answer: In general, the equation $x \log(x) = a$ cannot be solved for $x$ in closed form in terms of elementary functions. "Elementary functions" refers to the functions formed via the composition of the basic arithmetic operations +, -, *, /, the exponential and logarithm functions, and the trigonometric functions (though the inclusion of these last functions is redundant if one uses complex numbers, due to Euler's formula.), with the composition being finite.
Usually, elementary solutions are considered the best, though, as this shows, they are in many cases not possible. (There are analogies of this in other areas of mathematics -- e.g. in Euclidean geometry, constructions relying only on compass and straightedge are considered the best. Again, there are many cases in which such construction is not possible.) This is because elementary functions are simple and have numerous useful properties.
That being said, if one is willing to venture outside the realm of elementary functions, one can solve this equation. One commonly used non-elementary, but still simple to describe, function is the Lambert W function, defined as the inverse of $f(x) = xe^x$. Note this is similar to a logarithm function, but not quite the same. Such an inverse is not a proper function, since $f(x) = xe^x$ is not injective, however, we usually define a "principal branch" similar to, say, square root, by inverting on the interval $[-1, \infty)$. The Lambert W-function is denoted $W(x)$. To use it to solve your equation, make the substitution $x = e^u$. EDIT: In fact, this can be used as a proof that there is no elementary solution, because this shows that if you can solve the equation, you can express the Lambert W function in terms of its solution, but we know that one is not elementary. (The proof of that is much harder, however.)
However, if your $\log$ is base-10, then there is an elementary solution, namely $n = 10^6$! The form of the right-hand side makes me wonder whether a base-10 log was meant.
Comment: Do you mean $n = 10^6$ in the second to last line?
Comment: Fixed that. For some reason, I was thinking $n 10^n$ :)
Answer: For this kind of problem, with a specific number given, an iteration formula is best. What matters most is that n appear once in  a direct way (the factor n) and once in a slowly-varying way (the logarithm).
(I'll take the log to be natural base.)
Since log(n) varies slowly, and is "small" relative to n, we'll take it to be "constant" and set it to 1 just for a moment.  Then n = the given number, 6E6.  Obviously wrong; log(6E6)  (using base e) is about 15.  Okay, take n to be 6E6/15.607   and plug that into the logarithm to get a "better" number than 15.607.   Repeat...
n = 6E6
n ← (6.0E6)/log(n)   (repeat)

This converges quickly to n=460147.3...
If you need some sort of analytic formula, exp() both sides and maybe the Lambert W function or something similar will be helpful.  There won't be any solution in terms of common everyday arithmetic and familiar functions.
Comment: I think the log is base 10.


[SOLVED]W2K8 DNS server is resolving private IP addresses to the internet

Question: OK, so I've read a bunch of articles which revolve around my problem, but none of them have a clear answer. There is a ton of arguing back and forth and while I understand there are a few schools of thought regarding this topic,                  I'd like to try to clear the air.
This is all run out of my home both for convenience and to learn.
I run two W2K8 servers, both with AD, DNS and other services, and a separate server which is also my windows VPN server. mydomain.com is both my local AD domain name, and I also own mydomain.com, and I have it pointed to my home's IP address. I have a bunch of A-records that I use with different services. Most are only used internally, however some need to be resolved externally. Obviously none of the local only DNS records need to resolve unless you are connected via LAN or VPN (i.e. DC1.mydomain.com needs to be local only, while helpdesk.mydomain.com needs to resolve both internally and externally.)
I would rather not resolve LAN IP addresses to the public internet because I believe it is bad practice. So my questions is, how to I set up DNS so it resolves all records to LAN users (and VPN users, but DNS shouldn't know the difference between LAN users and VPN users, right?), but only certain records to the internet?
Comment: Don't get it, what's the problem? (there are no question marks...)
Comment: Sorry, I'll edit that. Basically I want DNS to resolve all records to users on the LAN, but only allow resolution of certain records to the internet. Does that make more sense?
Comment: Let me see if I got it. You want your local DNS to resolve all local addresses, but resolve only selected internet addresses?
Comment: If I ping DC1.mydomain.com from inside my LAN, it resolves to 192.168.100.231. That is correct and working. However if I ping it from anywhere else on the internet, it STILL resolves to 192.168.100.231, which should not happen. It should time out, not get resolved. But if I ping VPN.mydomain.com, it resolved to my public IP address from both inside and outside my network. That needs to continue to happen.
Comment: The fact that your DC1 resolved to internal IP means nothing - it's not like it's routable...
Anyway, do a whois query (plenty of websites to do this) to see who holds this record. Also, generally, I think that having the same domain name both on the inside and the outside is bad - it can cause unnecessary confusion.
Comment: I know it's not routable, for me it's not a security issue, just seems like bad practice. I ran a whois query and everything was expected, it's my name servers and the registrar is 1and1 as it should be. When I set up my network years and years ago, I knew very little and it seemed like a good idea at the time. If I ever rebuild it, I'll definitely do things different. As I said initially however, I did this all to learn. So at least that's working - I'm learning lol,
Answer: Not doable. What you would need is a split dns setup - which requires multiple dns servers.
I suggest you move the internet side of mydomaain out to a third party and do not host that DNS yourself. Cloudflare does that for free.
Comment: So, cloudflaire or the like would handle DNS requests for internet users for the mydomain.com domain (which would be authoritative for mydomain.com) AND I would have a DNS server set up on my local LAN which would not be visible to the public internet, which would ALSO be authoritative for mydomain.com domain? I suppose the idea is that my local DNS server would simply resolve DNS requests for mydomain.com and not forward them to the cloudflaire DNS server?
Comment: That is why normally you do not se the same domain. You would for example use internal.mydomain.com as domain internally. Ten mydomain.com can always go to the internet. Using the same doman name is really not standard.
Answer: You need to configure split-DNS properly. Basically, you need proper DNS zones configured for internal and external resources, with IP addresses set appropriately.
http://www.thesuperkev.com/2012/10/setting-up-split-dns-in-windows-server.html


one of the saddle's springs on the bridge of my guitar is missing

Question: I picked this cheap guitar up from a pawn shop. As you can see the spring is missing! Will this affect the guitar or its ability to play? If so, How do I fix it?
Comment: The Spring is there to prevent unwanted vibrations that lead to a buzzing sound.
Answer: As you can already see, the saddle is out of position (note the head of the saddle position screw is not against the bridge plate as it should be.
You just need to find a replacement spring. You might find something that will work at a hardware store or at an online or brick and more music instrument retailer.
Comment: The saddle may well be *in* position! O.k., the setscrew isn't tightened!
Comment: @Tim It's theoretically possible but unlikely. Saddle displacement essentially follows from string gauge. The low E saddle is almost always closer to the nut than the A saddle when a guitar is well intonated.
Comment: Just checked seven of my regularly used guitars, and the low E (and A) are longer than the others, thus the saddles are further away from the nut. Works pretty well the same for basses - thcker strings= slightly longer open speaking length. It's usual that the saddles are in a slight diagonal to the string direction, top shortest, with the usual exception of a slightly out of line B string. Sorry.
Answer: Once the string is present and tensioned, I don't see the spring making a difference.  It's just nice for setting up the saddle "offline" and not having it rattle around (and rearrange itself) while no string is there.
It also avoids having the string pressure on the maggot screws temporarily stop the fixture from pulling out fully and then later adjust itself with a jerk when tensioning the string.
But the spring action is nothing that you can't replace with manual action on setup and tensioning, and afterwards it's no longer necessary.
Answer: How do you fix it? Strip it down, and put another spring in! However, when the saddle is in the correct place, so it's intonated correctly, and it may even be there now, looking at it, tighten up the screw until its head just reaches the metalwork. At that stage, it could be left for ever, and not affect the intonation or playing of the guitar.
As others have said, springs are available - even one from a ball-point retractable pen could do the trick!


Combination of Node.JS(+ Socket.io) and PHP, what about users and changing Socket ID's

Question: I have been playing around with Node.js for two days now, I am slowly understanding how it works. I have checked multiple threads and posts now but I seem to either misunderstanding them or the way I am thinking about this application is completely wrong.
My application is mainly based on PHP and uses Node.js as a notifications system.
I first wanted to this solely in Node.js but I am more familiar with PHP so that is why I only want to use Node.js as a notifications system.
I do not have any real code to show as I have been mainly playing around and see all what Node can do and so far it seems to be the thing I need, there is one thing I just can't figure out or seem to mis understand. So far I figured out how to send data between the user and the server and used socket.io for this.
So, what if I have a user, which is registered and logs-in on my application. He then has a socket id from socket.io, but when the user leaves my application and comes back the next day his socket ID is changed because it seems to change on every connection. I need to have my users somehow always have the same socket ID or something else which tells my node.js server that it should only send data to one specific user or multiple users. Also, as the socketid seems to change on every request it is even changed when the user visits a different page so I don't ever seem to know which user is what.
I am a little confused and the flow of working with both PHP and Node.js is still a little mystery to me so I hope my question is clear. I dont want to be depending on many modules as I find all these different modules kind of confusing for a beginner like me.
Comment: do you share "sessions" between PHP and Node.JS ?
Comment: No, have not thought about that. Would it be a reasonable solution? Setting a session in php a D transfering it to node.js?
Answer: As long as PHP-Node.js are using sessions stored somewhere else other than flag file sessions let's say a cache service or a database mysql or nosql ..
you can use the "same flat file" sessions thought cache or database could be make your application "more"of course there are additional practises of allowing authenticated users to try to connect by controlling when to render the javascript code that holds the information to connect to socket.io server, where an additional list is stored in memory of all connected having information like username/log/timestamps/session variables/etc..
Comment: Is this the only way to do it? It seems so unlogical. I did manage to do it this way though, by saving all users and their sockets in an array on the server side. But it somehow feels dirty.
Comment: it not "dirty" its a way of tracking user connected to websocket server, thats how games,chats do it and has worked pretty well so far
Comment: Okay, but when an existing user opens a new window a new socket is created, which you then have to save in an array containing all sockets from a user. I am not saying it wouldn't work, it's just that in my opinion there should be a cleaner way of achieving this by somehow using the same socket (which does not seem to be possible).
Comment: yes there are possibilities of a user opening up like 100 windows which means 100 connection requests, no matter what application (game/chat/etc) this should be handled by server, which assigns a unique ID to each client, of course you can use SESSIONS to authenticate clients trying to connect and disconnect them if it sees that a client with same credentials is already connected .. i'll not say there is or isn't a cleaner way it really depends on how you want your application to handle it ..
Comment: Thanks for your explanation. I always assumed this to be handles automatically


Function with other function as variable

Question: I have to write a function in octave, of the form f(fun,x,m) where fun is another function
but i have a problem with that, how can i do such thing? (put a function as variable)
Comment: @HelloWorld - your suggestion is not so good. Please look at the answer of [Roney](http://stackoverflow.com/a/15996903/1714410) - using function handles. please remove your comment.
Answer: You can use "function handles".
As per the article given here,

handle = @functionname %returns a handle to the specified MATLAB® function.

A function handle is a MATLAB value that provides a means of calling a function indirectly. You can pass function handles in calls to other functions (often called function functions). You can also store function handles in data structures for later use (for example, as Handle Graphics callbacks). A function handle is one of the standard MATLAB data types.
The following example creates a function handle for the inbuilt humps function and assigns it to the variable fhandle.
fhandle = @humps;

Now you can pass the handle to another function in the same way you would pass any argument. This example passes the function handle just created to fminbnd, which then minimizes over the interval [0.3, 1].
x = fminbnd(fhandle, 0.3, 1)
x =
    0.6370


Distribution of min(X+Y,Y+Z,X+Z,Z+V,X+V,Y+V)?

Question: Let $X,Y,Z,V$ be i.i.d continuous random variables in an interval $[a,b]$. What will be the distribution of $\min(X+Y,Y+Z,X+Z,Z+V,X+V,Y+V)$? Assume the distribution of the random variables to be $F(.)$, with $F(a)=0$ and $F(b)=1$.
My attempt:-
Let $W=\min(X+Y,Y+Z,X+Z, Z+V,X+V,Y+V)$. We need to find $P(W\leq w)$. This means $P(X+Y \leq w \wedge Y+Z\leq w\wedge X+Z\leq w \wedge Z+V\leq w\wedge X+V\leq w\wedge Y+V\leq w)$. But these sums are not independent, so I wasn't able to proceed further.
What should be the general approach for such problems?
Comment: Please erase the last probability expression which is not correct.
Answer: Your notations do not help. Rephrase the problem as
$$X_1,\ldots,X_4\stackrel{\text{iid}}{\sim} f(x)$$
and
$$Y=\min\{X_1+X_2,X_1+X_3,X_1+X_4,X_2+X_3,X_2+X_4,X_3+X_4\}$$
You can then express $Y$ in terms of the order statistics
$$X_{(1)}\le X_{(2)}\le X_{(3)}\le X_{(4)}$$
and deduce that $Y$ is a specific sum of two of these order statistics, which leads to the conclusion. Indeed,
$$Y=X_{(1)}+X_{(2)}$$
and, since
$$(X_{(1)},X_{(2)})\sim \frac{4!}{2!}f(x_{(1)})f(x_{(1)})[1-F(x_{(2)})]^2$$
one can derive the distribution of $Y$ from a convolution step:
$$Y\sim\int_{-\infty}^{\infty} \frac{4!}{2!}f(x_{(1)})f(y-x_{(1)})[1-F(y-x_{(1)})]^2\,\text{d}x_{(1)}$$
Comment: I get your point. I'm supposed to find out the distribution of $X_{(1)} + X_{(2)}$ now. But order statistics are not independent, so do you have any idea what should I do next?


Should the entire project be compliant with PSR-0

Question: Is PSR-0 suppose to be able autoload any classes or just libraries/external api:s?
Example structure on a MVC compliant with PSR-0
Application
  Controller
     TestController.php
  Model
  View
  Library
System
  ...

TestController.php
<?php
namespace Application/Controller;

class TestController extends Controller
{
}

... Or just a custom autoloader for controllers, models etc...?
Answer: According to Phil Sturgeon (whose claims to fame include writing the PHP-FIG FAQ):

Are you trying to make your entire application PSR-0, because it
  should only be generic code packages that you do this with

http://philsturgeon.co.uk/blog/2013/04/is-psr0-shortsighted-or-are-you
So it would seem the answer is no, PSR-0 is not designed to be used for an entire web application, but for packages or libraries that you intend to publish for other developers to include in their projects.


Evaluate $f(x,y,z) = \frac{y}{\sqrt{z}}$ in $y \geq 0 \ $ , $0 \leq z \leq x^2$ and $(x-2)^2 + y^2 \leq 4$

Question:
Evaluate $f(x,y,z) = \frac{y}{\sqrt{z}}$ in $y \geq 0 \ $ , $0 \leq z \leq
 x^2$ and $(x-2)^2 + y^2 \leq 4$

The integral set up I got is
$$\int_{0}^{\frac{\pi}{2}} \int_{0}^{4 \cos(\theta)} \int_{0}^{r^2\cos^2(\theta)} \frac{r \sin(\theta)}{\sqrt{z}} \ dzdrd\theta$$
but the answer I get, $\dfrac{128}{5}$, is different that this textbook's answer (which is $\dfrac{64}{3}$).
Am I missing something?
Note: This wouldn't be the first time this textbook contains an error.
Answer: Your integrand should be  $\frac{r \sin(\theta)}{\sqrt{z}} \ \color{red}r dzdrd\theta.$
In fact, you have forgotten the Jacobian $\color{red}r$ of the transformation from cartesian to cylindrical coordinates (http://mathworld.wolfram.com/CylindricalCoordinates.html).
All the rest is correct; in particular, the boundary of the half circle (at the base of the integration domain) has polar equation $r=4\cos(\theta)$ for $0 \leq \theta \leq \tfrac{\pi}{2}$ (and not $\tfrac{\pi}{2}$ as I thought at first).
It can be of interest to know how it is possible to check this result by a numerical simulation.
Here is a way to do this (Matlab program below), with results at $\pm 1/\sqrt{N}=1/1000$ of the true result.

<code>clear all;close all;
N=10^6;S=0;
for k=1:N;
    % unif. distributed random point in enclosing brick
    % [0,4]x[0,2]x[0,16] with volume 128:
    x=4*rand;y=2*rand;z=16*rand;
    if z<x^2 && (x-2)^2+y^2<4
        S=S+y/sqrt(z);
    end
end
128*S/N,%=vol. of integrated zone times mean value
% good approximation of exact value 64/3
</code>

Remark: There are different ways to obtain an approximate value of an integral by simulation. This one could be considered as a "brute force" version.
Comment: Since the circumference is shifted, shouldn't I consider ONLY the first quadrant? When I do, I get the textbook's answer also. Thank you.
Comment: I completely agree at your first bound. I have modified my text and added the simulation program I have used to check the computation.


Find $f : [0,1] \to \mathbb R$ s.t. $\{x \in [0,1]$, for all neighborhood of $x$, there exist $y$ and $z$ in it s.t. $f(y)f(z)<0 \}\ $ is uncountable

Question: I am looking for a continuous function $f : [0,1] \to \mathbb R$ such that $\{x \in [0,1]$,  for all neighborhood of $x$ in $[0,1]$, there exist $y$ and $z$ in it such that $f(y)f(z)<0 \}\ $ is uncountable.
I am thinking about something like that: $x \mapsto \int_0^1(x-u)\sin (\frac{1}{x-u})du$. Would it work?
Comment: Do you just need one function, or a characterization of all?
Comment: The question is about finding one function. A characterization would be very interesting.
Comment: Thanks. What is the source of the question?
Answer: Let $E$ be the Cantor set.  Let $f(x) = 0$ for $x \in E$.  On each "middle third" $(a, b)$ removed in the $n$'th stage of the set's construction, let $f(x) = (-1)^n (x-a)(b-x)$.
With a bit more work, you can even get an $f$ that is $C^\infty$.


FileSize referenced in PHP Post is unusually high

Question: CentOS 5.x | Apache 2
I'm setting up an instance of w2box on my web server.  It basically uses a standard perl script (upload.cgi) to store a file being posted.
As a test, I'm trying to upload an ubuntu ISO (716 MB).  However, when I examine the apache access logs I see this:
 -  [07/Jul/2010:03:08:44 +0400] "POST /upload.cgi?sid=a4984a5sdkfjhsdkfhsdk68ef1c25f5931&maxsize=1073741824 HTTP/1.1" 500 636
My PHP limits are:
post_max_size 1100M
memory_limit 1200M
My question though is, why is the maxsize so high in the POST url? Does the web browser do some extra encoding that bloats the size of data?
If I want to support uploads of up to 1 GB, what would my php memory values need to be?
-M
Answer: That "maxsize" parameter in the URL doesn't seem to be related to either PHP or Apache.
It's probably a value that your PHP application is expecting. If it's specified in bytes, it means 1024MB.
Comment: Thanks Guys.  You're right.  It was an additional parameter in the upload.cgi script. Thanks!


Code Changes for Apache Server Upgrade

Question: The security team found a loophole in Apache version 2.4.23 so we need to upgrade Apache to version at least 2.4.56 or later. However, the developers told me it required a lot of code changes (around 60% of the entire codebase). Is this true?
Comment: How can we know if it's true?
Comment: A bit of an old answer of mine here https://serverfault.com/a/737872/37681 -  and only tangentially related your question, which  is very short in details so I might be barking up the wrong tree but: finding a specific version string does not equate to your system being vulnerable to every and all bugs published for that version, as long as you're running an supported (enterprise/LTS) distribution that backports security updates.
Comment: If we are talking about PHP code, then, unless the PHP code is actually parsing or generating the Apache configs there should be ZERO impact. But as it stands the question is MUCH TOO vague to answer. voting to close.
Comment: This (code change) look VERY unrealistic for me. I will be surprised if more than 10 lines of code need to be changed. Do the test, install on test machine new version and app and make QA to test the app.
Answer: As long as Apache is installed via system packages and the system is not yet end of life security patches are backported by the package maintainers to older versions.
Check the changelog of the Apache package, chances are high that your Apache is already patched, as long as security updates are installed when they become available.

Code Changes for Apache Server Upgrade


Function $f:X\to X$

Question: "We have function $f:X\to X$. We know that $f$ is injective but it is not surjective."
Is it even possible?
If function is injective if $f(x_1)=f(x_2) \implies x_1 = x_2$, which means that each $x$ from domain gets different $y$ from range. If the function is not surjectve then we know that not all elements from the range are "used". Which at least for $X$ does not make sense because the cardinality of domain and range is the same as $X$ is both domain and range.
Are there any mistakes in my thinking? Does this depend on whether the set is finite or infinite?
Comment: X must be infinite in order for there to be a non-surjective yet injective map from X to X.
Comment: Your thinking seems to ignore the very definition of what "infinite" means. A set is infinite if and only if there is a *proper* subset with the same cardinality as the whole set.
Comment: Google Hilbert's Hotel and you will find  some nice examples that will help you think about infinite sets and their possible mappings.
Answer: Yes it is possible for infinite sets. As an example consider $f \colon \mathbb{Z} \to \mathbb{Z}$ given by $f(n) = 2n$.

Function $f:X\to X$


Reading from usb device using node-usb

Question: I am trying to read data from a USB device "connected to my PC" using tessel/node-usb in my electron application
but i am not able to read anything or getting any error !
i am using following js :
function connectdevice(vID, pId){
var device = usb.findByIds(vID, pId);
device.open();
var deviceINTF=device.interface(0);

if (deviceINTF.isKernelDriverActive())
    deviceINTF.detachKernelDriver();
deviceINTF.claim();

var ePs = deviceINTF.endpoints;
var epIN;
$.each( ePs, function( index, ep ){
    if(ep.direction=="in"){
        epIN=ep;
}
});
if(epIN){
    epIN.on('data', function (data) {
        alert("1"+data);
    });
    epIN.transferType = 2;
    alert("non empty port : "+epIN);
    epIN.transfer(64, function(error, data) {
        console.log(error, data);
    });
    alert("after transfer");
}else{
    alert("unable to read ..");
}
}

Answer: The code has no issue but my device has 2 interfaces , and my code checking the first interface when i change this line code :
var deviceINTF=device.interface(0);

to :
var deviceINTF=device.interface(1);

It works !
Hope this help anybody.

Reading from usb device using node-usb


Wrong line drawing for coords sequence

Question: Here is a gif showing my problem:

In my example: When I click on the radio buttons, lines have to be generated in this order -> sion -> sarnen -> altdorf -> bellinzona and form into a trapeze (trapezium) but unfortunately my code switches the coordinates of the second and third position. I've tried it with other cities so maybe it could be something wrong with the fxml (which I don't think). It must be the code in class FXMLDocumentController. I get in the console this output:
Sarnen
Line[startX=600.0, startY=347.0, endX=803.0, endY=594.0, stroke=0x000000ff, strokeWidth=1.0]
Line[startX=803.0, startY=594.0, endX=373.0, endY=585.0, stroke=0x000000ff, strokeWidth=1.0]
Line[startX=373.0, startY=585.0, endX=702.0, endY=347.0, stroke=0x000000ff, strokeWidth=1.0]
Line[startX=702.0, startY=347.0, endX=600.0, endY=347.0, stroke=0x000000ff, strokeWidth=1.0]
Bellinzona
Sion
Altdorf

This means just that first sarnen has been created then bellinzona then sion and then altdorf.
FXMLDocumentController: I personally think the method starter() isn't doing that what it should so have there a first look
package tsprealone;

import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
//import javafx.scene.control.Alert;
//import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.shape.Line;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;

/**
 *
 * @author kbwschuler
 */
public class FXMLDocumentController implements Initializable {
    // private Alert alert = new Alert(AlertType.WARNING); just a message box
    @FXML
    private AnchorPane anchorPane;
    @FXML
    private ImageView img;

    @FXML
    private ArrayList<Stadt> stadte = new ArrayList<Stadt>();
    @FXML
    private ArrayList<Line> lines = new ArrayList<Line>();
    @FXML
    private Button generiere;
    @FXML
    private RadioButton zug;
    @FXML
    private RadioButton zurich;
    @FXML
    private RadioButton schaffhausen;
    @FXML
    private RadioButton stgallen;
    @FXML
    private RadioButton aarau;
    @FXML
    private RadioButton chur;
    @FXML
    private RadioButton glarus;
    @FXML
    private RadioButton frauenfeld;
    @FXML
    private RadioButton schwyz;
    @FXML
    private RadioButton luzern;
    @FXML
    private RadioButton sarnen;
    @FXML
    private RadioButton bellinzona;
    @FXML
    private RadioButton sion;
    @FXML
    private RadioButton liestal;
    @FXML
    private RadioButton bern;
    @FXML
    private RadioButton delemont;
    @FXML
    private RadioButton solothurn;
    @FXML
    private RadioButton fribourg;
    @FXML
    private RadioButton neuchatel;
    @FXML
    private RadioButton lausanne;
    @FXML
    private RadioButton genf;
    @FXML
    private RadioButton altdorf;
    @FXML
    private RadioButton stans;
    @FXML
    private RadioButton basel;
    @FXML
    private RadioButton appenzell;
    @FXML
    private RadioButton herisau;

    private ArrayList<Stadt> ausgewaehlt = new ArrayList<Stadt>(); //check if is checked

    @FXML
    private void clearPane(ActionEvent event)
    {
        //anchorPane.getChildren().clear();
        anchorPane.getChildren().removeAll(lines);
        lines.clear();
        anchorPane.getChildren().removeAll(ausgewaehlt);
        ausgewaehlt.clear();

        RadioButton[] allRadioButtons = new RadioButton[] {
                zug, zurich, schaffhausen, stgallen, aarau, chur, glarus, frauenfeld, schwyz, luzern, sarnen, bellinzona, sion, liestal, bern, delemont, solothurn, fribourg, neuchatel, lausanne, genf, altdorf, stans, basel, appenzell, herisau
        };
        for (int i = 0; i < allRadioButtons.length; i++) {
            RadioButton setToUnSelected = allRadioButtons[i];
            for (Stadt stadtToUnSelected : stadte) {
                stadtToUnSelected.setIsClicked(false);
            }
            setToUnSelected.setSelected(false);
        }

    }
    @FXML
    private void handleButtonAction(ActionEvent event) {
        addCities();

        for (Stadt stadt : stadte) {
            if (stadt.isIsClicked()) {
                ausgewaehlt.add(stadt);
                if(ausgewaehlt.size() == 1)
                {

                    /*alert.setTitle("Warnung");
                    alert.setHeaderText("Schau, eine Warnung wurde herausgegeben!");
                    alert.setContentText("Du hast nur eine Stadt ausgewählt. Um das Programm korrekt laufen zu lassen, muss man mehr als eine Stadt auswählen.");

                    alert.showAndWait();
                    System.err.println("Nur eine Stadt ausgewählt");*/
                    //alles kommentiere adel
                }
            }
        }

        starter();
        for (Stadt stadt : ausgewaehlt) {
            System.out.println(stadt.getName());

            for(Line line: lines)
            {

                    try {
                        anchorPane.getChildren().add(line);
                        do {
                            System.out.println(line);
                        }
                        while(ausgewaehlt.size() < lines.size());

                    }catch(IllegalArgumentException e)
                    {

                    }

            }

        }
    }

    public void addCities(){

        stadte.add(new Stadt("Zug", zug.getLayoutX(), zug.getLayoutY(), check(zug)));
        stadte.add(new Stadt("Zurich", zurich.getLayoutX(), zurich.getLayoutY(), check(zurich)));
        stadte.add(new Stadt("Schaffhausen", schaffhausen.getLayoutX(), schaffhausen.getLayoutY(), check(schaffhausen)));
        stadte.add(new Stadt("Aarau", aarau.getLayoutX(), aarau.getLayoutY(), check(aarau)));
        stadte.add(new Stadt("Chur", chur.getLayoutX(), chur.getLayoutY(), check(chur)));
        stadte.add(new Stadt("Glarus", glarus.getLayoutX(), glarus.getLayoutY(), check(glarus)));
        stadte.add(new Stadt("Frauenfeld", frauenfeld.getLayoutX(), frauenfeld.getLayoutY(), check(frauenfeld)));
        stadte.add(new Stadt("Schwyz", schwyz.getLayoutX(), schwyz.getLayoutY(), check(schwyz)));
        stadte.add(new Stadt("Luzern", luzern.getLayoutX(), luzern.getLayoutY(), check(luzern)));
        stadte.add(new Stadt("Sarnen", sarnen.getLayoutX(), sarnen.getLayoutY(), check(sarnen)));
        stadte.add(new Stadt("Bellinzona", bellinzona.getLayoutX(), bellinzona.getLayoutY(), check(bellinzona)));
        stadte.add(new Stadt("Sion", sion.getLayoutX(), sion.getLayoutY(), check(sion)));
        stadte.add(new Stadt("Liestal", liestal.getLayoutX(), liestal.getLayoutY(), check(liestal)));
        stadte.add(new Stadt("Bern", bern.getLayoutX(), bern.getLayoutY(), check(bern)));
        stadte.add(new Stadt("Delemont", delemont.getLayoutX(), delemont.getLayoutY(), check(delemont)));
        stadte.add(new Stadt("Solothurn", solothurn.getLayoutX(), solothurn.getLayoutY(), check(solothurn)));
        stadte.add(new Stadt("Fribourg", fribourg.getLayoutX(), fribourg.getLayoutY(), check(fribourg)));
        stadte.add(new Stadt("Neuchatel", neuchatel.getLayoutX(), neuchatel.getLayoutY(), check(neuchatel)));
        stadte.add(new Stadt("Lausanne", lausanne.getLayoutX(), lausanne.getLayoutY(), check(lausanne)));
        stadte.add(new Stadt("Genf", genf.getLayoutX(), genf.getLayoutY(), check(genf)));
        stadte.add(new Stadt("Altdorf", altdorf.getLayoutX(), altdorf.getLayoutY(), check(altdorf)));
        stadte.add(new Stadt("Stans", stans.getLayoutX(), stans.getLayoutY(), check(stans)));
        stadte.add(new Stadt("Basel", basel.getLayoutX(), basel.getLayoutY(), check(basel)));
        stadte.add(new Stadt("Appenzell", appenzell.getLayoutX(), appenzell.getLayoutY(), check(appenzell)));
        stadte.add(new Stadt("Herisau", herisau.getLayoutX(), herisau.getLayoutY(), check(herisau)));
        stadte.add(new Stadt("St Gallen", stgallen.getLayoutX(), stgallen.getLayoutY(), check(stgallen)));

    }

    public void starter() {

        for(int i = 0; i<ausgewaehlt.size(); i++)
        {
                if(i != ausgewaehlt.size() - 1){

                    lines.add(new Line(ausgewaehlt.get(i).getxCoord() + 9, ausgewaehlt.get(i).getyCoord() + 9, ausgewaehlt.get(i+1).getxCoord() + 9, ausgewaehlt.get(i+1).getyCoord() + 9));
                }else {
                    lines.add(new Line(ausgewaehlt.get(i).getxCoord() + 9, ausgewaehlt.get(i).getyCoord() + 9, ausgewaehlt.get(0).getxCoord() + 9, ausgewaehlt.get(0).getyCoord() + 9));
                }

        }

    }

    public boolean check(RadioButton rb) {
        if (rb.isSelected()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        //addCities();
        //starter();
    }

}

FXMLDocument.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.image.*?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.*?>

<AnchorPane fx:id="anchorPane" prefHeight="773.0" prefWidth="1184.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="tsprealone.FXMLDocumentController">
  <children>

    <ImageView fx:id="img" fitHeight="771.0" fitWidth="1184.0">
      <image>
        <Image url="@schweizerkarte-schweiz.png" />
      </image>
    </ImageView>
    <RadioButton fx:id="zug" layoutX="659.0" layoutY="228.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="zurich" layoutX="659.0" layoutY="166.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="stgallen" layoutX="873.0" layoutY="145.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="schaffhausen" layoutX="682.0" layoutY="51.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="aarau" layoutX="538.0" layoutY="159.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="chur" layoutX="909.0" layoutY="344.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="glarus" layoutX="794.0" layoutY="275.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="frauenfeld" layoutX="746.0" layoutY="94.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="schwyz" layoutX="694.0" layoutY="293.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="luzern" layoutX="599.0" layoutY="275.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="bellinzona" layoutX="794.0" layoutY="585.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="sion" layoutX="364.0" layoutY="576.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="liestal" layoutX="462.0" layoutY="121.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="bern" layoutX="382.0" layoutY="315.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="delemont" layoutX="367.0" layoutY="168.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="solothurn" layoutX="408.0" layoutY="225.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="fribourg" layoutX="319.0" layoutY="367.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="neuchatel" layoutX="258.0" layoutY="302.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="lausanne" layoutX="180.0" layoutY="474.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="genf" layoutX="53.0" layoutY="576.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="stans" layoutX="622.0" layoutY="306.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="basel" layoutX="423.0" layoutY="94.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="appenzell" layoutX="882.0" layoutY="169.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="herisau" layoutX="849.0" layoutY="154.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <Button fx:id="generiere" layoutX="1035.0" layoutY="640.0" mnemonicParsing="false" onAction="#handleButtonAction" text="Generiere Linien" />
     <Button fx:id="clear" layoutX="1035.0" layoutY="690.0" mnemonicParsing="false" onAction="#clearPane" text="Lösche Linien" />
    <RadioButton fx:id="sarnen" layoutX="591.0" layoutY="338.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
    <RadioButton fx:id="altdorf" layoutX="693.0" layoutY="338.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
  </children>
</AnchorPane>

Comment: I couldn't read everything, can you display the polygon's generation code? is it the `starter` method ?
Comment: @BoHalim i think its the starter() method .. just lines being added into arraylist
Answer: for (Stadt stadt : stadte) {
    if (stadt.isIsClicked()) {
        ausgewaehlt.add(stadt);
        if(ausgewaehlt.size() == 1)
        {

            /*alert.setTitle("Warnung");
            alert.setHeaderText("Schau, eine Warnung wurde herausgegeben!");
            alert.setContentText("Du hast nur eine Stadt ausgewählt. Um das Programm korrekt laufen zu lassen, muss man mehr als eine Stadt auswählen.");

            alert.showAndWait();
            System.err.println("Nur eine Stadt ausgewählt");*/
            //alles kommentiere adel
        }
    }
}

This adds the cities in the same order in which they occur in the stadte list. This may or may not be the same order the user clicked the buttons...
In this case it is not...
The better idea would be adding a RadioButton to the list when it's selected. I recommmend adding the Stadt instances as to the RadioButtons instead of adding them to a list. Also remove the clicked property (or how you call it) from the class, since this doesn't seem necessary.
private static void createStadt(RadioButton button, String name) {
    button.setUserData(new Stadt(name, button.getLayoutX(), button.getLayoutY()));
}

private final List<Stadt> selectedCities = new ArrayList<>();

public void initialize(URL location, ResourceBundle resources) {
    createStadt(zug, "Zug");
    createStadt(zurich, "Zurich");
    ...

    allRadioButtons = new RadioButton[] {
            zug, zurich, schaffhausen, stgallen, aarau, chur, glarus, frauenfeld, schwyz, luzern, sarnen, bellinzona, sion, liestal, bern, delemont, solothurn, fribourg, neuchatel, lausanne, genf, altdorf, stans, basel, appenzell, herisau
    };
}

@FXML
private void citySelectionAction(ActionEvent event) {
    RadioButton source = (RadioButton) event.getSource();
    Stadt city = (Stadt) source.getUserData();

    if (source.isSelected()) {
        selectedCities.add(city);
    } else {
        selectedCities.remove(city);
    }
}

private RadioButton[] allRadioButtons;

@FXML
private void clearPane(ActionEvent event) {
    anchorPane.getChildren().removeAll(lines);
    lines.clear();
    selectedCities.clear();

    for (RadioButton button : allRadioButtons) {
        button.setSelected(false);
    }
}

@FXML
private void handleButtonAction(ActionEvent event) {
    final int size = selectedCities.size();
    switch (size) {
        case 1:
            /*alert.setTitle("Warnung");
            alert.setHeaderText("Schau, eine Warnung wurde herausgegeben!");
            alert.setContentText("Du hast nur eine Stadt ausgewählt. Um das Programm korrekt laufen zu lassen, muss man mehr als eine Stadt auswählen.");

            alert.showAndWait();
            System.err.println("Nur eine Stadt ausgewählt");*/
        case 0:
        break;
        default:
            Stadt c1 = selectedCities.get(0);
            Stadt c2 = selectedCities.get(size-1);
            lines.add(new Line(c1.getxCoord() + 9, c1.getyCoord() + 9, c2.getxCoord() + 9, c2.getyCoord() + 9));
            // intentional fallthrough
        case 2:
            Stadt currentCity = selectedCities.get(0);
            for(int i = 1; i < size; i++) {
                 Stadt nextCity = selectedCities.get(i);
                 lines.add(new Line(currentCity.getxCoord() + 9, currentCity.getyCoord() + 9, nextCity.getxCoord() + 9, nextCity.getyCoord() + 9));
                 currentCity  = nextCity;
            }

    }

    selectedCities.clear();

    // start adding lines starting at the end until a line is found that is
    // already added to the anchorPane
    Line line;
    for (int i = lines.size()-1; (i >= 0) && ((line = lines.get(i)).getParent() == null); i--) {
        anchorPane.getChildren().add(line);
    }

}

...
<RadioButton fx:id="zug" onAction="#citySelectionAction" layoutX="659.0" layoutY="228.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
<RadioButton fx:id="zurich" onAction="#citySelectionAction" layoutX="659.0" layoutY="166.0" mnemonicParsing="false" prefHeight="0.0" prefWidth="0.0" style="-fx-color: red;" />
...

Answer: It looks like your second and third marked points are third and forth in your ArrayList.
It seems so because in this loop
for (Stadt stadt : stadte) {
        if (stadt.isIsClicked()) {
            ausgewaehlt.add(stadt);
}

cities are ordered by their order in FXMLDocument.
I advice you to add your cities in list when you are clicking on the city points. When you end marking and click on your "Generiere Linien" button, you just should render the linked lines.

Wrong line drawing for coords sequence


Azure Blob Storage's ListBlobsSegmentedAsync method doesn't return metadata if metadata value is empty

Question: Calling ListBlobsSegmentedAsync method of Microsoft.Azure.Storage.Blob's (11.1.2) CloudBlobContainer attaches the blob metadata if BlobListingDetails.Metadata parameter (3rd) is set. However if blob metadata's value is empty, the metadata is not returned at all.
In turn, the metadata with empty value is displayed in the Storage Explorer.
BlobResultSegment blobList = await container.ListBlobsSegmentedAsync(blobPath, true, BlobListingDetails.Metadata, null, continuationToken, null, null);

foreach (CloudBlockBlob blobItem in blobList.Results)
{
  // trying to access blobItem's metadata
}

Edit: It seems it's not possible to create metadata with empty value through Azure Storage Blob's API (throws ArgumentException). However with Storage Emulator it's possible.

I need to upload blobs containing metadata with empty ("" or null) value, is it possible somehow?
Edit 2: The feature is working with Azure.Storage.Blobs v.12.8.3. I'm using Microsoft.Azure.Storage.Blob v11.1.2. So the question applies to this library!
Comment: Basically, it is not allowed to set metadata with an empty value, but you can set value with 'null', but it is still a string value
Comment: @StanleyGong Is there any documentation that value can't be empty? Storage Emulator is able to set metadata with (seemingly) empty value.
Comment: Yes, I tried that, we can generate metadata with an empty value by Storage Emulator. But   it is not allowed using SDK or REST API, if you use SDK , it will throw an error: `value can't be a an empty string`  and if you use REST API leave header `x-ms-meta-name` empty , the value will be `null` finally
Comment: It's working with version 12 (Azure.Storage.Blobs v12.8.3)! I'm using v.11.

@StanleyGong What version are you using?
Comment: Wow, glad to know your issue has been solved.  I am also tested by v.11 as you shared your code with this version. I'll summarize your solution as an answer below, pls accept it to close this question and it will also help others I think :)
Comment: @StanleyGong The problem is not really solved, since v.12 is a totally different library (different namespace, so I think the versioning is misleading...), so I either have to use both libraries, which is not nice, or I have to migrate fully to v.12 which means rewriting the whole codebase using v.11. It should be **proven** that using v.11 with empty values in **impossible**. We can accept that through SDK it's impossible, but I haven't checked through REST API. If you confirm and update your answer that it can't be done with REST API as well I'll accept it.
Comment: Sure, I have updated my answer that using REST API to add a metadata with empty value, pls have a check :)
Answer: Using Azure.Storage.Blobs v12.8.3 works for the scenario that adding/retrieving metadata with an empty value.
UPDATE
This is the step that I tried to add metadata with empty value by REST API:

Result:
Though I leave metadata value as empty,to check its result on Azure Portal, it is set as null :

I also tried to remove all characters in textbox, but it is not allowed to update:


Why does freestyle swimming restrict underwater swimming?

Question: According to Wikipedia and to CONI:

Some part of the swimmer must break the surface of the water
  throughout the race, except it shall be permissible for the swimmer to
  be completely submerged during the turn and for a distance of not more
  than 15 meters after the start and each turn. By that point the head
  must have broken the surface

I fail to see the point of this rule, it seems completely arbitrary to me.
While arbitrary rules are usual in heavily regulated sports, this strikes me as quite odd in a "freestyle" environment...
Why does freestyle swimming restrict underwater swimming?
Comment: Just making things crystal clear. Sports SE had a [question](http://sports.stackexchange.com/questions/2929/tips-advice-for-stringing-a-lacrosse-stick-with-a-v-shooter-pocket-and-2-cross) that was being interpreted as asking for health/medical advice because the OP said "stick doctor."
Comment: Maybe they don't want these situations: http://www.youtube.com/watch?v=Vox9KOxC1ZA
Comment: @Bernhard yes but the question is _why_ do they want to avoid such situations? "freestyle" is supposed to be, as the name implies, as free as possible, and innovation should be encouraged…
Comment: @waxeagle why? It's actually free except for this single rule, and that's why I'm wondering why this rules exists at all.
Comment: FYI, without the question, this sounds like a rant.
Comment: @edmastermind29 I'm sorry, it wasn't meant to be a rant. Thanks for the edit (I assumed people would read the title, as well as the body...)
Comment: "freestyle" is a misnomer.
Answer: Ultimately this goes back to David Berkoff, a US Olympic backstroker in the '88 and '92 games. He realized that by dolphin kicking underwater he could go faster than swimming on top of the water (no surface tension to slow you down).  Using this technique, he was able to set several world records and an NCAA championship.
The problem was, this underwater dolphin kick is also quite suitable for freestyle or butterfly, and if most of the race is underwater dolphin kicks there wouldn't be much difference between the strokes. (Breaststroke requirements preclude dolphin kicking). Therefore FINA decided to limit the distance that a back/fly/free swimmer could remain underwater dolphin kicking.  Why 15 meters was chosen isn't completely clear, other than being a manageable fraction of a 50 meter long course pool, and not to far off what many people were doing already coming off a wall with a few kicks. At least one note I have found states the original limit was 10 meters (Source: Berkoff's bio at the International Swimming Hall of Fame site).
Comment: @WillAppleby - actually, 'freestyle' has two different meanings. For non-medley (relay or IM), it means anything other than back/breast/fly. By itself (any 'freestyle' event) it can mean anything you want, including dog paddle, sidestroke, corkscrew, ... - anything at all. Freestyle is not defined in the rulebook like back/breast/fly. You use a forward start, must breakout by 15 meters, must touch the wall, and must finish by touching the wall. That is all (except, again, it can't be back/breast/fly in a medley event).
Comment: I think this should be the right answer. As a long-time swimmer myself I think it's important that each stroke is different and without the underwater restriction there would be nothing separating fly, backstroke or freestyle. In the context of swimming, "freestyle" isn't really meaning "get to the other end using any means possible", it simply means you can use any of the 4 established strokes to complete the race.
Comment: If that was the reason they could have restricted the underwater swimming only in the non-freestyle events. Freestyle should not have any style restrictions…
Answer: When you allow someone to complete their entire swim as a glide you do a few things that are not considered good for the sport

You emphasize swimsuit technology over strength and speed
Emphasizes lung capacity over strength and speed
Don't use half the body

Swimming is a total body sport about strength and speed. If you allow someone to go the whole way under water you change the competition into something that it's not intended to be.
Answer: My guess is that the 15 m line was chosen because it is the least multiple of 5 m that will not force most swimmers to surface unnaturally early after the start. Had they picked 10 m, half of us would break the rule by just doing what used to be normal. Of course, by introducing the rule they also made most of us strive to reach further than before. A 50 back or 50 fly in short course is not much swimming anymore. And the same swimmer can excel in both events by just having a great kick in a way you just couldn't in the days when swimmers swam more in these events.
As for why freestyle is not free to be done totally submerged, it basically goes back to the origins of the sport. It was always done on the surface (sub-surface swimming, with mono fins and snorkels for example, is governed by a different organisation) and when flip turns were invented, no one thought about restricting the under water part of the turn because everyone returned to the surface soon enough to breathe anyway. The backstroke events at the Seoul olympics changed that. And when the rule was introduced for backstroke, it was also introduced for butterfly and freestyle to avoid the same thing happening there.
As an aside, backstroke is pretty much as free as freestyle. You just cannot chose to swim it on your stomach like you can in freestyle.
Comment: Do you have any sources for this? The question does state "at worst, interviews/articles from informed experts...".
Answer: As with just about any sports activity, part of the answer boils down to money. If nobody watches, there's no money. And, if 95% of a swim race were to happen underwater, as it would if this rule didn't exist, even fewer people would watch swimming than already do.
While the Olympics are nominally an "amateur" event, they have become pretty much like all other televised sports events and, sadly, that means money is a factor. Since the Olympics are probably THE most watched swimming contests in the world, they tend to dictate the rules that everyone else follows.
Sort of like when the Indy 500 effectively banned turbine engines back in the 70s by limiting the size of the intake so much that no turbine could function. If that rule hadn't been implemented, everybody would have run turbine engines starting in 1968. Same in swimming - if this resurfacing rule didn't exist, everybody would just swim entire laps under water using the fish kick. Not much fun to watch. . .
Comment: When an existing answer already explains the origin of the rule, a new answer based on speculation that doesn't match it is not likely to be valid.
Comment: I'm going to remind *everyone* to please [Be Nice](https://sports.stackexchange.com/help/be-nice) - that includes both content and tone. Thank you.


drupal_add_js and variables into anonymous functions, objects undefined?

Question: Pulling my hair out. Read a lot of stuff about scopechain and closure to tackle this one myself. And as i understand at some level, i can't get this to work.
I wrote a module for likebuttons (like facebook twitter etc). It's working ok, but I want to make it more generic and multilingual. I did the following. In my facebook function I have this:
<?php
  $lang = 'en_EN'; //

  // Load javascript
  $settings['lang'] = $lang;
  drupal_add_js(array('mymodule' => $settings), 'setting');
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/myscript.js');
?>

This is working ok. The javascript gets loaded and the $settings['lang'] is passed to browser too (as I can see in chrome console it gives me 'en_EN' on Drupal.settings.mymodule.lang).
In myscript.js script I have the following (simplified to be a more generic question
(function() {

  var language = Drupal.settings.mymodule.lang;
  console.log(language); //undefined

}());

UPDATE:
So it's anonymous.... All those terms.
Ok, got the object inside now. Now i got to figure out how to get the 'en_EN' from the object.
Updated script:
(function(language) {

var my_var = language.settings.mymodule.lang;
console.log(my_var); // undefined
console.log(language); //Object { settings={...}, behaviors={...}, locale={...}, meer...}
console.log(language.settings); //Object {}
console.dir(language.settings) // There are no underlying objects
}(Drupal));

Here language contains the complete object drupal has passed. (I can see that in console).
Why can't I go in the object language like normal and get my value by using language.settings.mymodule.lang?
Seems like Drupal.settings is empty inside the anonymous function, but has all elements there in the DOM tree. I don't know what causes this to be an empty object inside an anonymous function.
Comment: try wrapping your function in jQuery(document).ready(); - maybe the setting has not actually been set when the function fires?
Comment: Thx. Only jQuery didn't work, the answer below has it to but the behaviors did the rest.
Answer: As of Drupal 6 javascript is put inside function that we assign as a property of Drupal.behaviors. Example,
Drupal.behaviors.myModuleBehavior = function (context) {
  //Do some fancy stuff
};

Drupal 7.x:
Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    $('input.myCustomBehavior', context).once('myCustomBehavior', function () {
    // Apply the myCustomBehaviour effect to the elements only once.
    });
  }
};

So your code should be
(function($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      var my_var = Drupal.settings.mymodule.lang;
      console.log(my_var);
      console.log(language);
    }
  };
})(jQuery);

Comment: You totally made my day! Now I can set language for my sharebuttons in my module admin page :) Like! Vind ik leuk!


Recuperar valor de um HTTP query string

Question: Tenho uma URL onde retorna um  HTTP QueryString, e necessito recuperar as informações da URL e converter em variáveis para fazer consultas no banco de dados.
Em PHP basta utilizar o $_GET[""], agora em C# eu não sei como proceder.
Vou dar um exemplo para esclarecer melhor.
Possuo a URL: http://html.net/page.php?name=Joe&age=12
Tenho que pegar os valores "Joe" e "12" para uma consulta posterior.
Answer: Experimente isso e veja se resolve.
string nome = Request.QueryString["name"];

string idade = Request.QueryString["age"];

Comment: Não esquece de verificar se o parametro está nulo antes de usar e não use parametros sensíveis na query string. Ex: login, senha, id de usuário logado, session, qualquer parametro de controle que possa ser usado para assumir uma sessao sem necessariamente conhecer algum login.
Comment: Adicionei este código em meu controller, mas ao chamar a página, a variável null.
Comment: public ActionResult Dependente()
        {
            string nome = Request.QueryString["name"];
            var dependente =
                dependenteRepository.Dependentes.Where(r => r.NmPessoa == nome).ToList();
            return View(dependente);

        }

E estou tentando recuperar o valor desta URL:
http://localhost/Usuario/Dependente?name=joao
Comment: Deu certo, esqueci de colocar os parâmetros em meu controller. Obrigado a todos.
Comment: Eu tenho que colocar a quantidade de parâmetros que receberei em minha Query String em meu controller, correto?

Recuperar valor de um HTTP query string


Extract the element from html page in R

Question: I am new to R and trying to scrape the map data from the following webpage:
https://www.svk.se/en/national-grid/the-control-room/. The map is called "The flow of electricity". I am trying to scrape the capacity numbers (in blue) and the corresponding countries. So far I could not find a solution on how to find the countries' names in the HTML code and consequently scrape them.
Here is an example of data I need:
Would you have any idea?
Thanks a lot in advance.
Answer: The data is not in the table, hence we need to extract all the information individually.
Here is a way to do this using rvest.
library(rvest)
url <-'https://www.svk.se/en/national-grid/the-control-room/'

webpage <- url %>% read_html() %>%html_nodes('div.island')

tibble::tibble(country = webpage %>% html_nodes('span.country') %>% html_text(),
                watt = webpage %>% html_nodes('span.watt') %>% html_text() %>%
                         gsub('\\s', '', .) %>% as.numeric(),
                unit = webpage %>% html_nodes('span.unit') %>% html_text())

#  country    watt unit
#  <chr>     <dbl> <chr>
#1 SWEDEN     3761 MW
#2 DENMARK     201 MW
#3 NORWAY     2296 MW
#4 FINLAND    1311 MW
#5 ESTONIA     632 MW
#6 LATVIA      177 MW
#7 LITHUANIA  1071 MW

Comment: Hi Ronak, thanks a lot for your answer. I meant the figures from the map though. So, each individual flow from one country to another. Should look something like FI > EE  1031MW. I cannot find the "FI>EE" element in html. Regards.
Comment: I don't see anything like `FI > EE 1031MW.` on the map. There are values like `€6.89` on the map.
Comment: I uploaded the screenshot in the problem description.
Answer: The flow data comes from an API call so you need to make an additional xhr (to an url you can find in the network tab via dev tools ) to get this data. You don't need to specify values for the timestamp (Ticks) and random (rnd) params in the querystring.
library(jsonlite)

data <- jsonlite::read_json('https://www.svk.se/Proxy/Proxy/?a=http://driftsdata.statnett.no/restapi/PhysicalFlowMap/GetFlow?Ticks=&rnd=')

As a dataframe:
library(jsonlite)
library (plyr)

data <- jsonlite::read_json('https://www.svk.se/Proxy/Proxy/?a=http://driftsdata.statnett.no/restapi/PhysicalFlowMap/GetFlow?Ticks=&rnd=')

df <- ldply (data, data.frame)

Extract the element from html page in R


Is it possible to gather the licenses in one server?

Question: How can servers take licences from one server? How about MS office licenses (more than 300) could be installed on the clients, I know there is a way but what is the best way to do this?
Comment: Could you explain what you are asking in more detail?  Hard to tell what you are asking.
Comment: There 300 computers in a certain domaine, how is it possible to assign them a MS office license automatically without having to install the licenses one by one...
Comment: Again, what you're saying doesn't make sense. Anyone with 300 PCs with office would have a volume license with the same license on every machine. You put a copy of office on a server, generate an msp file with your options preselected and you enter the license. When you install its automatic, no questions, no license to enter. Activation is automatic.  You can push out office with a script or at logon. What are you trying to do? Hopefully its not install 300 copies of office retail?
Comment: Since i'm a newbie, I would be thankfull if you could share with me some documentation about how to do that.
Answer: For Office 2010, volume license is managed through KMS role. It's just a 2008 Server to which your give KMS keys. Same for Windows 7.
You can use VAMT to scan your computers and gather license info
Volume imply Microsoft contract with your company and not buying license in the box at the local store


open multiline text file in perl

Question: I have the following text file
Hello my
name is
Jeff

and I want to open it using perl. However, when using this code
use strict;
use warnings;
open(my $fh, "<", "input.txt") or die "cannot open input text!";
my $text= <$fh>;
print $text;

The output text is only Hello my. How can I make it print all of my input text lines and not just the first one ?
Comment: `while (<$fh>){ print;  }`
Answer: If you read the section on I/O operators in perldoc perlop, you will see the following:

In scalar context, evaluating a filehandle in angle brackets yields the next line from that file

And, a bit further down:

If a <FILEHANDLE> is used in a context that is looking for a list, a list comprising all input lines is returned, one line per list element.

If you assign <FILEHANDLE> to a scalar variable, you will get the next line (actually record) from the file. This is what you are doing:
my $text = <$fh>;

If you assign <FILEHANDLE> to an array, you will get all of the remaining data from the file, with each line (actually record) in a separate element of the array.
my @text = <$fh>;

If you want to get all data from a file into a scalar, there are a few approaches you can take. The naive approach is to read the data in list context and then join it using an empty string:
my $text = join '', <$fh>;

You can use $/ to change Perl's idea of a "record" (often done in a do block):
my $text = do { local $/; <$fh> };

I like the slurp method from Path::Tiny.
use Path::Tiny;

my $text = path($filename)->slurp;

Answer:
In scalar context, evaluating a filehandle in angle brackets yields the next line from that file

so you can use while loop to read the lines (preferred method)
while (<$fh>) #output will store into default variable $_
{
    print ;

}

Or you can use the array but you are trying to storing the all content of the file at time in the variable
my @array = <$fh>;

And the slurp mode to read all file in the scalar variable
my $multiline = do { local $/; <$fh>; } #$/ input record seprator

Comment: *"When you store the file handle into the scalar variable it will read the next line from the file"* That isn't what happens when you store a file handle in a variable. When you call `readline` on a file handle, maybe.
Comment: *When you store the file handle into the scalar variable it will read the next line from the file* Or as perldoc, more accurately, puts it: "In scalar context, evaluating a filehandle in angle brackets yields the next line from that file".
Comment: @DaveCross and Borodin Thanks for your comment Post edited

open multiline text file in perl