How to add a multiple enum field to the create and edit forms in Grails 4?

Question: In my domain model, some classes have a collection of enums as a field. I have modeled it in two differente ways, as an embedded collection:
class A {
  String name
  Set<Enumeration> enumerations

  static embedded = ['enumerations']
}

enum Enumeration {
  ENUM_VALUE_1,
  ENUM_VALUE_2,
  ENUM_VALUE_3
}

And also as a hasMany collection:
class A {
  String name

  static hasMany = [enumerations:Enumeration]
}

enum Enumeration {
  ENUM_VALUE_1,
  ENUM_VALUE_2,
  ENUM_VALUE_3
}

In both cases, I can add enum values to the collection in BootStrap.groovy in the following way:
A.withTransaction { status ->
  def a1 = new A( name:"a1" )
  a1.addToEnumerations( Enumeration.ENUM_VALUE_1 )
  a1.addToEnumerations( Enumeration.ENUM_VALUE_2 )
}

Using scaffolding, I can see the content of the enumeration collection in the index and show pages, but in the edit and create pages, only the label is shown, no widget is displayed.
Which is the simplest way to show a widget, e.g. a multiple select, for this kind of fields in Grails 4 (I am using Grails 4.0.3)?
Thanks in advance.
Comment: In a relational database, how would you represent the consequences of `static embedded = ['enumerations']` in a schema?  I don't think that would be possible, would it?  `enumerations` is a `Collection`.
Comment: I suppose the relational schema for both modeling approaches is the same or very similar. I can save and retreive data using both of them. My problem is about the user interface and scaffolding.
Comment: "I suppose the relational schema for both modeling approaches is the same or very similar." - I don't think that is true. `embedded` causes that property to be stored in the same table as "owner" that references them so there would have to be a column for each entry in the collection, without any way to know how many there are ahead of time.  We don't support that (because it isn't possible).
Comment: @jeff-scott-brown: I have opened the in-memory H2 database and the relational schema is exactly the same for both modeling approaches. There is a table named A(ID,VERSION,NAME) with PK=ID, and another table named A_ENUMERATIONS(A_ID,ENUMERATION) with PK=(A_ID,ENUMERATION), that stores pairs(A.id,Enumeration). Think of "embedded" as the way of implementing "composition" in UML, for example. However, my question is about scaffolding the user interface, not about the underlying relational schema.
Comment: What you are describing there is not what `embedded` does but we don't support embedding collections.  It can't be done.  Think of a `Person` class and an `Address` class. in `Person` you have `Address homeAddress` and `static embedded = ['homeAddress']`. What that says is instead of creating an `ADDRESS` table, store all of the attributes that make up an `Address` in the same table with the `Person` attributes. That works because the properties in `Address` are finite and known about ahead of time. It would be impossible to do the same with a Collection of Enum.
Comment: You can remove `static embedded = ['enumerations']` and I wouldn't expect anything to change.
Comment: You are right, I have removed the `static embedded = ['enumerations']` and nothing has changed.
Answer:
Which is the simplest way to show a widget, e.g. a multiple select,
  for this kind of fields in Grails 4 (I am using Grails 4.0.3)?

You can use the select tag.
<g:select multiple="true" name="someName" from="${somePackage.SomeEnumClassName}"/>

Comment: Thank you very much for your answer @jeff-scott-brown. I have added a detailed answer of what I did to solve my problem. Considering that the solution is quite simple, I think it should be the default scaffolding for collections of enumerations in Grails.
Answer: This is the process I followed after @jeff-scott-brown answer:

I generated the views for class A:

generate-views A

Then in grails-app/views/a/edit.gsp and grails-app/views/a/create.gsp I changed this element:

<f:all bean="a"/>

into these other elements:
<f:with bean="a">
    <f:field property="name"/>
    <f:field property="enumerations">
        <g:select
            multiple="true"
            name="${property}"
            from="${Enumeration}"
            value="${a?.enumerations}"
        />
    </f:field>
</f:with>

And it works for both the embedded and the hasMany approaches.
Should not this be the default scaffolding for collections of enumerations in Grails?
Comment: If you want to involve the fields plugin then it would be more simple to use a property template (https://grails-fields-plugin.github.io/grails-fields/latest/guide/index.html#customizingFieldRendering).  The `g:select` tag would go there and you wouldn't have to have `g:field` tags for every field.
Comment: "Should not this be the default scaffolding for collections of enumerations in Grails?" - StackOverflow discourages asking questions in your answer.  You are welcome to submit a feature request at https://github.com/grails-fields-plugin/grails-fields/issues.
Comment: Submitted as https://github.com/grails-fields-plugin/grails-fields/issues/306
Answer: This is a simpler solution without having to generate the views, i.e. no need to  modify edit.gsp and create.gsp. Just using the fields plugin as suggested by @jeff-scott-brown.
Assuming this is your domain class:
package mypackage

class MyClass {
  // ...
  // properties
  // ...
  Set<MyEnumeration> enumerations

  // no need to declare it as embedded
  // static embedded = ['enumerations']
}

enum MyEnumeration {
  ENUM_VALUE_1,
  ENUM_VALUE_2,
  ENUM_VALUE_3
}

And that you have generated a scaffold controller for it, i.e.
package mypackage

class MyClassController {
    static scaffold = MyClass
}

The only thing you have to do is creating the file grails-app/views/_fields/myClass/enumerations/_widget.gsp with the following content:
<g:select
    multiple="true"
    name="${property}"
    from="${mypackage.MyEnumeration}"
    value="${myClass?.enumerations}"
/>

It also works if you declare the collection of enumerations as a hasMany association, i.e.
package mypackage

class MyClass {
  // ...
  // properties
  // ...

  static hasMany = [enumerations:MyEnumeration]
}

enum MyEnumeration {
  ENUM_VALUE_1,
  ENUM_VALUE_2,
  ENUM_VALUE_3
}

Comment: This solution is also applicable to grails 3.3.11.
Answer: Well if this is for validating data for your database, you can use the 'inList' constraint on your domain as the same constraint by extracting that as a 'List' for you to use:
def class = grailsApplication.getDomainClass(className)
def props = class.getConstrainedProperties()
props.each(){ k,v ->
    if(k=='theColumnName-you-are-trying-to-get'){
        return v.getInList()
    }
}

Comment: Thanks @orubel, but I think enums are closer to the conceptual model and they are better for i18n than `inList' constraints.


Closed form or limiting form of an expression involving binomial coefficients

Question: This question leads to an application of the inclusion‒exclusion principle leading to this sum:
$$
\sum_{k=0}^n (-1)^k \binom n k (n-k)^x = (-1)^n \sum_{k=0}^n (-1)^k \binom n k k^x
$$
$$
\text{e.g. } \quad 1\cdot 6^{10} - 6\cdot 5^{10} +15\cdot 4^{10} - 6\cdot3^{10} + 1\cdot2^{10}
$$
Is there either a closed form or some sort of limiting form as $n\to\infty\text{?}$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

$\ds{\sum_{k = 0}^{n}\pars{-1}^{k}{n \choose k}\pars{n - k}^{x} =
\pars{-1}^{n}\sum_{k=0}^{n}\pars{-1}^{k}{n \choose k}k^{x}:\ {\Large ?}}$.

\begin{align}
&\bbox[10px,#ffd]{\ds{%
\pars{-1}^{n}\sum_{k = 0}^{n}\pars{-1}^{k}{n \choose k}k^{x}}} =
\pars{-1}^{n}\sum_{k = 0}^{n}\pars{-1}^{k}{n \choose k}
\bracks{x!\oint_{\verts{z} = 1}
{\expo{kz} \over z^{x + 1}}\,{\dd z \over 2\pi\ic}}
\\[5mm] = &\
\pars{-1}^{n}\, x!\oint_{\verts{z} = 1}{1 \over z^{x + 1}}
\sum_{k = 0}^{n}{n \choose k}\pars{-\expo{z}}^{k}\,{\dd z \over 2\pi\ic} =
\pars{-1}^{n}\, x!\oint_{\verts{z} = 1}{\pars{1 - \expo{z}}^{n} \over z^{x + 1}}
\,{\dd z \over 2\pi\ic}
\\[5mm] = &\
x!\oint_{\verts{z} = 1}{\pars{\expo{z} - 1}^{n} \over z^{x + 1}}
\,{\dd z \over 2\pi\ic}
\end{align}

With the identity
  $\ds{\pars{\expo{z} - 1}^{n} = n!\sum_{\ell = 0}^{\infty}{\ell \brace n}{z^{\ell} \over \ell!}}$ where $\ds{{\ell \brace n}}$ is a
  Stirling Number of the Second Kind:

\begin{align}
&\bbox[10px,#ffd]{\ds{%
\pars{-1}^{n}\sum_{k = 0}^{n}\pars{-1}^{k}{n \choose k}k^{x}}} =
x!\, n!\sum_{\ell = 0}^{\infty}{\ell \brace n}{1 \over \ell!}\
\overbrace{\oint_{\verts{z} = 1}{1 \over z^{x - \ell + 1}}
\,{\dd z \over 2\pi\ic}}^{\ds{\delta_{\ell x}}} =
\bbx{n!\, {x \brace n}}
\end{align}

Note that $\ds{{x \brace n}_{\ x\ <\ n} = 0}$
Comment: Interesting read. (+1).
Comment: @MarkoRiedel Thanks. Stirling ${\brace}$ are quite useful...


A regular expression for all strings over $\{a,b\}$ which do not have both substrings $bba$ and $abb$

Question: I am looking at the answer in a solution manual to the following question.

Let the alphabet $= \{a,b\}$.
    Write regular expressions for:

all the words that don't have both substrings $bba$ and $abb$.

The answer given was

$a^*(baa^*)^*b+b^*(a^*ab)^*a^*$

I don't think this is correct, since it can't make $abb$, which is in the language. So it's got to be wrong.
So I came up with my own. Would this be all the words that don't have both substring $bba$ and $abb$?

$(a+ba)^*(bb+b+\lambda)$

Or maybe this one should work

$(b+\lambda)(ab+a)^*+b^*$

(In the above $\lambda$ is the empty string.)
Comment: I think the solution manual is interpreting the question to mean, strings that have neither bba nor abb (so abb is not in the language), whereas you are interpreting it to mean, strings that may have one or the other of bba and abb but don't have both of them.
Answer: The regex a*(baa*)*b+b*(a*ab)*a* does match abb:

a* matches a
(baa*)* matches empty string
b+ matches bb,
(a*ab)*a* matches empty string.

Also, both of your regexes match bbabb which shouldn't be matched according to the task. And what is the point of bb+b+, isn't it the same as bbb+?
Not sure what are you trying to accomplish with "^ is an empty string by the way", but usually ^ matches the beginning of the string
Comment: We are talking about basic regular expression syntax.  Plus stands for union and there are no extensions like the caret anchoring the match to the beginning of the word.
Comment: @FabioSomenzi  sometime in these two years it was edited to replace `^` with $\lambda$, hence my comment on the earlier version
Comment: I had not noticed it had been two years, but I had checked the edit history and I was aware of what had caused the confusion.
Answer: These are incorrect regular expressions. We generate $bba$ from the second part.
I think $b^*+a^*(ab)a+a^*(ba)a+a^*ba(a+ab)a+a^*ab(a+ab)a$ may be a correct regular expression.

The correct regular expression is
$$b^*+a^*(a^*aba^*)^*+a^*(a^*ba)^*a^*(V+b)+a^*(ba)^*(a+ab)^*a+a^*(ab)^*(a+ab)*.$$

$ababaab$ accepted
$abababaab$ accepted
$baababaab$ accepted
$ababba$ Rejected


MySQL database - optimizing same multiple fields

Question: Recently i have created an achievement system which sets a field like achievement1 to int 1 when something is a achieved, the problem is that we have over a 100 fields that go achievement1, achievement2, achievement3 and so on...
So my question is how do i optimize this ? I was thinking about storing a string in one field that would be like 1,0,1,0,1,0,1... 0 for unachieved achievements and 1 for completed. But would that not be worse since i'd have to update a very long string everytime instead of 1 integer ?
I've looked for an answer everywhere but i found nothing useful.
Answer: You can create a table that stores achievements for each user (assuming that they are related to a user in some way). There could be a foreign key for the UserID and then an integer value for the achievement number. So (15,1) would indicate that the user with the ID of 15 has completed Achievement1. If you wanted to find all the achievements that a user has completed, just do something like:
SELECT achievementNumber FROM tblAchievements WHERE UserID = 15.
The text for "achievement" is really arbitrary, it's how you use it that matters.
Comment: So something like this ? [link]http://www.part.lt/img/f8e2c5b3692175f3dacd5b4e105bce7b549.png (uzduotys means achievements)

Cause i've already done this, i'm now looking for a more optimized way of doing this if it's actually possible ?
Comment: More like this: http://jsfiddle.net/Nzqk8/ You would only have two columns in the table. One for the user that the achievement is for, and one for the number of the achievement.


On point line incidences

Question: Given a set of $n$ points $P_1, \ldots, P_n$ and $n$ lines $L_1, \ldots, L_n$ in $\mathbb{F}^2$, consider the set $I=\{(p_i, L_j)|L_j\text{ contains }p_i\}$ of point line incidences. The famous Szemeredi Trotter theorem says that if $\mathbb{F} = \mathbb{R}$ then $|I| = O(n^{4/3})$. I have read somewhere that an upper bound of $O(n^{3/2})$ is very easy to prove and works for any field. However i cannot seem to figure out how to prove this. How does one prove this? The best I got after a bit of thought is the trivial $|I| \leq \binom{n}{2}\dfrac{n}{n - 1}$.
Answer: Suppose that $L_i$ has $m_i$ points on it, for $1\le i\le n$. There are $\binom{m_i}2$ pairs of points on $L_I$. Furthermore, for $i\neq j$, there cannot exist a pair of points which lies on both $L_i$ and $L_j$ (lines intersect in at most one point). Therefore, these sets of pairs of points are actually disjoint, so we conclude
$$
\sum_{i=1}^n \binom {m_i}2\le \binom n2
$$
Since $x\mapsto x(x-1)/2$ is a convex function, you can apply Jensen's inequality to the LHS to attain $$\frac1n\sum_{i=1}^n \binom{m_i}2\ge \binom{\frac1n(m_1+\dots+m_n)}2=\binom{|I|/n}2.$$ Combining this with the previous inequality, you get $n\binom{|I|/n}{2}\le \binom n2$, which implies $|I| \in O(n^{3/2})$.
This bound is tight, and is attained when the points and lines form a projective plane.

On point line incidences


conversion bigq to mpfr with Rmpfr package

Question: The help documentation of the Rmpfr R package claims that the .bigq2mpfr() function uses the minimal precision necessary for correct representation when the precB argument is NULL :
Description:

     Coerce from and to big integers ('bigz') and 'mpfr' numbers.

     Further, coerce from big rationals ('bigq') to 'mpfr' numbers.

Usage:

     .bigz2mpfr(x, precB = NULL)
     .bigq2mpfr(x, precB = NULL)
     .mpfr2bigz(x, mod = NA)

Arguments:

       x: an R object of class 'bigz', 'bigq' or 'mpfr' respectively.

   precB: precision in bits for the result.  The default, 'NULL', means
          to use the _minimal_ precision necessary for correct
          representation.

However when converting 31/3 one gets a bad approximation:
> x <- as.bigq(31,3)
> .bigq2mpfr(x)
1 'mpfr' number of precision  8   bits
[1] 10.31

By looking inside the .bigq2mpfr() function we see the detailed procedure:
N <- numerator(x)
D <- denominator(x)
if (is.null(precB)) {
    eN <- frexpZ(N)$exp
    eD <- frexpZ(D)$exp
    precB <- eN + eD + 1L
}
.bigz2mpfr(N, precB)/.bigz2mpfr(D, precB)

Firstly I do not understand why precB is taken as follows. The exp output of the frexpZ() is the exponent in binary decomposition:
> frexpZ(N)
$d
[1] 0.96875

$exp
[1] 5

> 0.96875*2^5
[1] 31

Here we get precB=8 and the result is then identical to:
> mpfr(31, precBits=8)/mpfr(3, precBits=8)
1 'mpfr' number of precision  8   bits
[1] 10.31

I am under the impression one should rather replace precB with 2^precB but I'd like to get some advices about that:
> mpfr(31, precBits=8)/mpfr(3, precBits=2^8)
1 'mpfr' number of precision  256   bits
[1] 10.33333333333333333333333333333333333333333333333333333333333333333333333333329
> mpfr(31, precBits=8)/mpfr(3, precBits=2^9)
1 'mpfr' number of precision  512   bits
[1] 10.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333329
> mpfr(31, precBits=8)/mpfr(3, precBits=2^7)
1 'mpfr' number of precision  128   bits
[1] 10.33333333333333333333333333333333333332

Comment: What is the precision produced by your first line ( `x <- as.bigq(31,3)` )  ?  I ask because the converter is designed not to increase the precision over that given to it.
Comment: @CarlWitthoft I don't understand your question. `as.bigq(31,3)` is the rational number with numerator 31 and denominator 3. There's no precision involved.
Comment: Well, that's probably the problem. I would start by making sure you get the expected results for the examples on the help page and then follow that sequence with 31/3
Answer: I get (note the difference in my initial creation):
Rgames> fooq<-as.bigq(31/3)
Rgames> fooq
Big Rational ('bigq') :
[1] 5817149518686891/562949953421312
Rgames> .bigq2mpfr(fooq)
1 'mpfr' number of precision  104   bits
[1] 10.3333333333333339254522798000835

All this strongly suggest to me that the precision in your bigq number is in fact zero decimal places, i.e. each of "31" and "3" has that precision.  As such, your mpfr conversion is quite correct in giving you a result with one decimal place precision.
Comment: Ok but `fooq` is not the rational number 31/3 here. I set your answer as accepted but now I wonder what are the good practices with the combination of `gmp` and `Rmpfr`. Thanks !
Comment: **(Update 22/02/2014)** @Carl As I said this is not correct because your `fooq` is not the rational number 31/3. See my new answer, this works with the latest version of the package.
Answer: This has been corrected in a newer version of the package:
> x <- as.bigq(31,3)
> .bigq2mpfr(x)
1 'mpfr' number of precision  128   bits
[1] 10.33333333333333333333333333333333333332

Comment: Confirmed here.  THanks for letting me know. But be aware that `as.bigq(31,3)` is NOT the same as `as.bigq(31/3)  #5817149518686891/562949953421312`  . So  be cautious in your code.
Comment: @CarlWitthoft Yes, this is what I said: I **want** the rational number with numerator 31 and denominator 3, so it is `as.bigq(31,3)` and *not* `as.bigq(31/3)`


Are $C^0[a,b]$ and $C^0[0,1]$ isometrically isomorphic?

Question: Consider $C^0[a,b]$ and $C^0[0,1]$, each equipped with the $L^1$-Norm.
Are these (out of curiosity) isometrically isomorphic?
Comment: Yes, they are. Do you know how an isometry between the two spaces could look if they are endowed with the $L^\infty$-norm? Have you an idea how to change such a bijection to make it isometric for the $L^1$-norms?
Answer: Yes. The isomorphism is given by:
$$\begin{array}{llll}
\varphi:&C^0[a,b]&\longrightarrow&C^0[0,1]\\
&f(x)&\longmapsto&(b-a)f(a+(b-a)x)
\end{array}$$
Comment: could you provide a reference for these things?
Comment: @RudidieRennmaus What do you mean exactly by "these things"? If you want references about metric spaces, any book about topology will treat them. If you want functions spaces, then take a look at functional analysis and PDEs.
Comment: no, for this particular fact
Comment: @RudidieRennmaus I didn't use any references. Once you've seen enough similar stuff, it becomes quite intuitive.


Why NodeJs usually use MongoDB not Mysql?

Question: I heard about Mysql used big companies like Uber, Linkedin. I think NodeJs is best to use Mysql than MongoDB. Am I wrong? Maybe i don't know features about MongoDB
Comment: Once you understand the difference between SQL and NoSQL databases and their props and cons, You can use MySQL or MongoDB or Both. People usually use what works best for them and not what other big companies are using.
Answer: Like you I was in the same dilemma when I started learning NoSQL. Coming from a RDBMS background NoSQL or MongoDB is easier to scale and has a JSON-like syntax that feels home with JavaScript developers. Imagine this structure when you were developing a Todo app:
Todo Database (MySQL):
- Todo (table)
  - Id

- Todo Item (table)
  - TodoId
  - TodoName

With MongoDB you can put everything in one Table or Collection like so:
Todo: {
  Id: //some uniq id,
  Items: [
    0: {
      name: 'wash the dishes'
    },
    1: // and so on
  ]
}

And later on if you decide to break or add more details you can do so, hence the word "scale"
Todo: {
  Id: asdf
}

TodoItem: {
  todoId: asdf,
  name: 'wash the dishes',
  etc: // and so on
}

And best of all if you feel you're app is almost set in stone, you can transfer to MySql or Postgresql which the big companies you mentioned are doing.
This is just an easy example and probably using NoSql over Sql won't be that much of a benefit. But think of this, you are trying to build out a new app with unfamiliar data relationships. Yes, you can build ER Diagrams and normalize it as much as you want and when you start building your app you realized one very important field which might affect the entire relationships of your tables. OR would you rather build fast and get your hands dirty, build messy tables/collections with NoSql and see your app come alive much quicker?
Hope that helps.


python wrap text and reportlab

Question: I have a little code and I would like to wrap my long string in every 10th character and then add it into a PDF using reportlab:
This is how I try:
text = '*long_text_long_text_long_text_long_text*'
text = "\n".join(wrap(text, 10))
canvas.drawString(5,227, text)

My pdf was created but where I want to break the lines I can only see black rectangles. You can see the attached picture:

Can you help me? Thank you!
Comment: I don't know what a `canvas` is, but I bet its `drawString` method does not natively support rendering multiline strings. You'll probably need to manually iterate through each line and draw them individually, specifying the Y-coordinates of each one using your own arithmetic.
Answer: drawString draws a single line. so you will need to adjust the coordinate for each line in a loop.
y = 227
for line in wrap(text, 10):
    canvas.drawString(5, y, line)
    y += 15

Answer: An alternative to placing each line individually is using Paragraph:
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A5
from reportlab.platypus import Paragraph

text = "long text
long text
long text
"
text_width=A5[0] / 2
text_height=A5[1] / 2
x = A5[0]/4
y = A5[1]/4

pdf = canvas.Canvas(filename="test.pdf", pagesize=A5)

styles = getSampleStyleSheet()
p = Paragraph(text, styles["Normal"])
p.wrapOn(pdf, text_width, text_height)
p.drawOn(pdf, x, y)

pdf.save()

In addition to supporting manually put line breaks, the Paragraph also supports automatic line breaks.

python wrap text and reportlab


iptables - force all traffic over VPN (and drop all traffic when no VPN connection)

Question: Goal:
Ensure all traffic is forced over VPN tunnel from all network interfaces (wlan0,rmnet0,rmnet1), that is all traffic is dropped when not connected to VPN. In other words, Internet traffic should not be allowed, and only traffic over the VPN is acceptable.
So far...
Android Device with iptables binary, wlan & 3g connection
VPN gateway @ 10.10.10.10 (not real address).
iptables -P OUTPUT DROP
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -i tun0 -m conntrack --ctstate NEW -j ACCEPT
iptables -A INPUT -j DROP

iptables -A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -o tun0 -m conntrack --ctstate NEW -j ACCEPT
iptables -A OUTPUT -d 10.10.10.10 -m conntrack --ctstate NEW -j ACCEPT
iptables -A OUTPUT -j DROP

Results:
Traffic appears to be blocked - but so too is connection to VPN.
Any ideas? Appreciate this is only mobile data rmnet0 interface and doesn't have WiFi in here yet.
Answer: I wouldn't use conntrack in this scenario but a much simpler set
iptables -A INPUT  -i tun0 -j ACCEPT
iptables -A INPUT  -s 10.10.10.10 -j ACCEPT
iptables -A OUTPUT -o tun0 -j ACCEPT
iptables -A OUTPUT -d 10.10.10.10 -j ACCEPT

No need for any connection tracking. You also don't need the DROP rules at the end, by the way, the -P ... DROP takes care of that.
You'll also want to make sure that you use the IP of the VPN server in your config, otherwise, you'll have to whitelist DNS too:
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A INPUT  -p udp --sport 53 -j ACCEPT

Comment: Thanks for the help - a quick question though, and kind of the reason i was being led down the conntrack route... Will i be able to get a DHCP IP address on the WLAN interface & IP Address on the 3G connection with this? The reason i ask is i can only bring the IPtables config up on boot, as anything else needs root... so wlan & mobile data etc may be enabled post boot, but i still need the rules to apply.
Comment: Good catch! Yes, you'll have to whitelist dhcp traffic (UDP 67 to server, 68 from server) too.
Comment: No, ip addresses are negotiated over PPP there, I believe. I'm not too familiar with 3g though, so fire up wireshark and make a 3g connection. You'll see what happens :)
Comment: I know this is the accepted answer, but could you post your final string of iptables commands?


Aspas saindo no formato incorreto do JSON!

Question: Estou serializando um dicionário para JSON em Razor Pages, porém as aspas ("), estão saíndo como "
_Layout.cshtml (UTF-8)
...

    ...

    ...

Saída:
{"@context":"http://schema.org","@type":"Organization","name":"HAHA","url":"http://example.com","logo":"http://example.com/image.png"}

Como eu posso fazer com que elas saíam no formato correto? Como "
Comment: E por onde você tá vendo a informação? Pelo "inspecionar elemento" do browser?
Comment: Dê um pouco de contexto. Onde a informação está sendo mostrada?
Comment: @LINQ atualizei, estou mostrando na _Layout.cshtml
Comment: Sim, no Microsoft Edge estou vendo pelo (Inspecionar elemento e Depurador = "Exibir Origem"), no Google Chrome pelo (Inspecionar e Exibir código fonte da página)
Comment: Meu arquivo está codificado como `UTF-8`
Comment: Mas qual é objetivo disto?
Comment: Apenas representação
Answer: Encontrei a resposta em uma pergunta do SO inglês: https://stackoverflow.com/questions/9331195/json-net-serialize-c-sharp-object-to-json-issue
Utilizando @Html.Raw() eu consigo ter a saída de forma correta sem problemas.
...

    ...

    ...


CLGeocoder().reverseGeocodeLocation; what is the handler supposed to be?

Question: This is the code I am using. I am unsure of what variables should be passed into the completion handler. Every other post I view says to pass 'placemark' and 'error' but I am running into warnings and errors.
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler:{ ([placemark: CLPlacemark?], error: NSError?) in
        print(error)
    })
}

Answer: Here is the complete function:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){

    CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)-> Void in

        currentLatitude = String(manager.location!.coordinate.latitude)
        currentLongitude = String(manager.location!.coordinate.longitude)

    })
}

Hope this helps!


Salvar informações de abas

Question: Tenho minha tela, da seguinte forma:

cada aba corresponde a uma classe, e entidade do banco de dados,
e indo na sequencia existe uma referencia delas, ou seja
na 02 tem referencia(fk) da 01, na 03 tem referencia(fk) 02 e assim por diante.
Eu até então sempre salvava e retornava o id salvo para quando mudar de aba ele ter o id(fk) e poder salvar.
Entretanto se o usuário cancelar, iria ficar um registro lá vago, além de ele não poder pular as abas, tem que ir sempre em sequencia.
Alguém pode me dar uma ideia de como resolver isso?
Pode ser usando angularjs
Answer: Se seus modelos usam Guids, a solução fica natural.
Suponha os seguintes modelos:
public class ModeloPrincipal
{
    [Key]
    public Guid ModeloPrincipalId {get; set; }
}

public class ModeloAba1
{
    [Key]
    public Guid ModeloAba1Id {get; set; }
    public Guid ModeloPrincipalId {get; set; }

    public virtual ModeloPrincipal ModeloPrincipal { get; set; }
}

public class ModeloAba2
{
    [Key]
    public Guid ModeloAba2Id {get; set; }
    public Guid ModeloPrincipalId {get; set; }

    public virtual ModeloPrincipal ModeloPrincipal { get; set; }
}

public class ModeloAba3
{
    [Key]
    public Guid ModeloAba3Id {get; set; }
    public Guid ModeloPrincipalId {get; set; }

    public virtual ModeloPrincipal ModeloPrincipal { get; set; }
}

Quando o modelo principal já existe, você usa uma chave provisória para referenciar na criação:
public ActionResult Create()
{
    var modeloPrincipal = new ModeloPrincipal();
    modeloPrincipal.ModeloPrincipalId = Guid.NewGuid();

    modeloPrincipal.ModeloAba1 = new ModeloAba1 {
        modeloPrincipalId = modeloPrincipal.ModeloPrincipalId;
    };

    modeloPrincipal.ModeloAba2 = new ModeloAba2 {
        modeloPrincipalId = modeloPrincipal.ModeloPrincipalId;
    };

    modeloPrincipal.ModeloAba3 = new ModeloAba4 {
        modeloPrincipalId = modeloPrincipal.ModeloPrincipalId;
    };

    return View(modeloPrincipal);
}

A geração das chaves fica toda ao critério do programador. O banco apenas recebe a informação. Não há preocupação com geração de chave primária IDENTITY e não há necessidade de trabalhar com chaves provisórias.
Na hora de salvar, um único SaveChanges() faz tudo.
Agora, se seus modelos usam chaves primárias int com IDENTITY, você vai ter salvar o registro principal já na primeira mudança de aba, juntamente com o primeiro registro da aba, a não ser que o usuário cancele a ação já na primeira aba. Considero que para um sistema usando AngularJS isto seja bem ruim.

Salvar informações de abas


If you write down all the numbers from 1 to n, how many digits would you have written down?

Question: I've seen the question for numbers like 50, 100 or 1000, but not for $n$. Although I found a formula that might be the answer, but I don't know the name of it or the proof for it. I couldn't find it anywhere on internet as well. Here it is:
$$d\times(n+1) - \frac{10^d - 1}{9}$$
$d$ is the number of digits $n$ has.
For example, for $n = 16$:
Answer: $\displaystyle2\times (16 + 1) - \frac{10^2 - 1}{9} = 34 - 11 = 23$
Also: $12345678910111213141516\rightarrow 23 \text{ digits}$
Looking forward for replies!
Thanks!
Edit 1:
For those who also want to know how $d$ is calculated:
$d = \lfloor\log_{10}n\rfloor + 1$
Comment: Interesting result, but it doesn't seem useful so you're probably the first one to make this formula.
Comment: It'd be nice if you'd include an explanation as to how you derived that.  If you include that in your body, I will delete my answer.  It really should be *your* explanation as it was your idea.
Answer: Well, it's clear we write down a "ones" digit for each $n$.  And we write down a "tens" digit for all but the first $9$ so we do $n-9$ "tens" digits.  And $n-99$ hundreds digits and so on.
So if $d$ is the number of digits as you put it, we have the number of digits written is.
$n + (n-9) + (n-99) + ...... + (n-\underbrace{999....9}_{d-1})=$
$n\times d - (9 + 99 + ..... + \underbrace{999....9}_{d-1})=$
$n\times d- ((10-1) + (100-1) + ...... + (10^d -1))=$
$n\times d - [(10 + 100 + ..... + 10^{d-1}) -(d-1)]=$
$n\times d - [(10 + 100 + ..... + 10^{d-1})+1] + d=$
$n\times d + d - [1+10 + 100 + ..... + 10^{d-1}] =$
$(n+1)\times d - [\underbrace{111.....1}_d] =$
$(n+1)\times d - \frac {10^{d}-1}9$
Nice job!
Comment: I'll delete this if you include *your* derivation.  It really should be *your* explanation.
Comment: Thank you so much! this proof is what I was looking for! <3


Display quiz results for users

Question: I am developing an e-learning portal for a client; the client wants to be able to create quizzes and view the results of individual students, and probably draw a graph to give an overview of student performance. I am using the Quiz module to create quizzes.
The "quiz score" is not available if you use node as the view base or quiz.
I am able to list username, level, and quiz.
Answer: You would need to add a relationship which would be the Quiz Result : User.
Then you would find the quiz result : score in the fields
Answer: Use quiz as the base for view.
If you want to create a chart.
Im using views dataviz module
Code Karate have a tutorial on it here.
My view page ended up looking like this:

which created a chart based on the individual scores of the users answers (not the overall quiz:score)

Display quiz results for users


Problema com legenda no ggplot, usando duplo eixo y + geom_line()+geom_point() x geom_bar()

Question: Olá, estou com outro problema em relação a apresentação de legenda, neste caso, usando eixo y duplo (ggplot::scale_y_continuous::sec_axis), e geom_line()+geom_point() x geom_bar(), conforme observa-se na figura 1. Gostaria de apresentar a legenda como um quadrado sem linha e ponto colorido, identificando "UR" e 3 quadrados, com as legendas para "Tmáx", "Tméd" e "Tmín", com seus respectivos shape, linetype, e colour.
Obs: eu estou usando o pacote extrafont, para a fonte "Times New Roman".

Código:
library(ggplot2)
library(extrafont)

novo<-structure(list(AVA=c(1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,
11L,12L,1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L,
1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,11L,12L),variable=structure(c(1L,
1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,2L,2L,2L,2L,2L,
2L,2L,2L,2L,2L,2L,2L,3L,3L,3L,3L,3L,3L,3L,3L,3L,
3L,3L,3L),.Label=c("Tar","Tarmin","Tarmax"),class="factor"),
value=c(26.9102916666667,26.0853333333333,27.8317291666667,
28.3282083333333,27.4253958333333,30.3683196875,25.3293125,
26.888375,22.8657708333333,26.8046458333333,23.222375,
23.4121041666667,22.08,21.887,25.673,23.925,23.861,
25.705,20.45,21.919,17.265,21.49,19.581,18.251,32.012,
31.057,31.089,32.762,32.001,34.997005,30.542,31.851,
27.85,32.516,27.518,28.612)),row.names=c(NA,-36L),class="data.frame")

UR<-structure(list(AVA=1:12,variable=structure(c(1L,1L,1L,
1L,1L,1L,1L,1L,1L,1L,1L,1L),.Label="UR",class="factor"),
value=c(74.4006458333333,74.8331458333333,78.3165833333333,
73.8219375,78.0607708333333,68.2176286458333,69.2232916666667,
67.881625,64.4237916666667,64.3282083333333,66.3142916666667,
70.0928125)),row.names=c(NA,-12L),class="data.frame")

ggplot(novo,aes(x=AVA,y=value,group=variable,colour=variable))+geom_point(aes(shape=variable),cex=1.5)+geom_line(aes(linetype=variable),cex=1.2)+
  scale_y_continuous(name = expression("Temperatura do ar("^"o"*"C )"),limits=c(0,40),
                     sec.axis = sec_axis(~ . *2,name=expression("Umidade relativa do ar (%)")))+
  geom_bar(data=UR,aes(x=AVA,y=value/2,colour=variable),alpha=.2,stat="identity",width = .25)+
  scale_shape_manual("",breaks=c("Tar","Tarmax","Tarmin","UR"),values=c(15,16,18),labels=c("Tméd","Tmáx","Tmín","UR ar"))+
  scale_linetype_manual("",breaks=c("Tar","Tarmax","Tarmin","UR"),values=c(1,2,4),labels=c("Tméd","Tmáx","Tmín","UR ar"))+
  scale_fill_manual("",breaks=c("Tar","Tarmax","Tarmin","UR"),values=c("purple"),labels=c("Tméd","Tmáx","Tmín","UR ar"))+
  scale_colour_manual("",labels=c("Tméd","Tmáx","Tmín","UR ar"),breaks=c("Tar","Tarmax","Tarmin","UR"),values=c("black","red","blue","purple"))+
  theme(panel.background = element_rect(fill=NA),
        panel.border = element_rect(fill=NA),
        axis.title.y = element_text(size = rel(1.5), angle = 90),text=element_text(family="Times New Roman", face="bold", size=12),
        legend.text = element_text(size=12,face = "bold"),
        axis.text = element_text(size=12,face="bold"),
        legend.position = "bottom")

Answer: Você está definindo cor e grupo na estética global, o que fará com que sejam aplicadas à todas geometrias. Coloque na global os parâmetros que valem para todas e nas estéticas das geometrias o que se aplica apenas à cada uma delas. O mesmo vale para as escalas.
labs <- c("Temperatura", labels = c("média", "mínima", "máxima"))

ggplot(novo,aes(AVA, value)) +
  geom_col(data = UR, aes(y = value/2, fill = variable), colour = "black", alpha=.3, width = .25) +
  geom_point(aes(shape = variable, colour = variable), cex = 1.5) +
  geom_line(aes(linetype = variable, colour = variable), cex = 1) +
  scale_fill_manual(NULL, values = "#6baed6") +
  scale_color_manual(labs, values = c("black", "blue", "red")) +
  scale_shape_manual(labs, values = c(15, 16, 18)) +
  scale_linetype_manual(labs, values = c(1, 2, 4)) +
  scale_y_continuous("Temperatura (ºC)", sec.axis = sec_axis(~.*2, "Umidade relativa (%)"))

Removi o tema para facilitar a reprodução. Algumas observações:

geom_col é o atalho para usar barras com stat = identity
para barras, color representa a cor da linha externa, use fill para a cor da barra em si
as geometrias são plotadas na ordem; coloque geom_col primeiro se quiser que ela fique de fundo.
use NULL ao invés de "" nos títulos de legenda; isso corresponde à usar element_blank
cores, formatos, etc que serão exibidos em legenda vão dentro do aes() e a personalização vai na scale_* correspondente. Os que não variam e não serão exibidos em legenda vão fora do aes
Comment: Atualizei a resposta.
Comment: Obrigado, embora seja intuitivo de usar o `ggplot2` tem umas particularidades, que as vezes nos faz quebrar a cabeça, não seria tão mais fácil se eles tivessem colocado uma forma de editar a legenda, como no `lattice`, que você faz o que precisa dentro de `key=list()`.
Comment: Cheque a ajuda para `guides`. GGplot é modular, todo componente pode ser armazenado em objeto.


Switching between views

Question: I am a beginner in android, what I have to do is I have an audio playing with images. Also in the bottom bar, I have a button to map. Now I need to change my view to the map when clicked on map button. But the audio should not be stopped, it should keep playing in the background.
Can any one tell me the way to do this?
Thanks in advance,
Tejaswi
Comment: For audio play in background you have to use service....so go for it!!
Answer: Use ViewAnimator to switch between views without changing activity.

Switching between views


bayes probability for consecutive tests

Question: Looking for some guidance for using Baysian probability for consecutive independent tests.
Using the traditional example of disease testing efficacy (say the 1% of the population are infected and the test is 95% accurate), I would like to understand the approach should a person chose to get a second test.

What is the probability of having the disease given both tests are positive?
What is the probability of having the disease if they get a different test and that test is only 90% accurate?

My intuition says that the first test result is not part of the input (prior) to the second test but I can't get it right in my head. For the second test, should I partition the sample space based on the probability of being infected based on the first test? =:-/
Thanks
Answer:
My intuition says that the first test result is not part of the input (prior) to the second test but I can't get it right in my head. For the second test, should I partition the sample space based on the probability of being infected based on the first test? =:-/

The assumption should be that the two test results are conditionally independent when given the disease state of the same person. Otherwise, you cannot solve the problem.  So if we let the two test results be Bernoulli variables $T_1,T_2$, and disease state be $D$, then: $$\mathsf P(T_1{\,=\,}s,T_2{\,=\,}t\mid D{\,=\,}d)~=~\mathsf P(T_1{\,=\,}s\mid D{\,=\,}d)\,\mathsf P(T_2{\,=\,}t\mid D{\,=\,}d)$$
The rest is just the usual applications of Bayes' Theory and substitution for provided values.

say the 1% of the population are infected and the test is 95% accurate)

That is $\mathsf P(D{\,=\,}1)=0.01$ and for each $k\in\{1,2\}$: $~\mathsf P(T_k{\,=\,}1\mid D{\,=\,}1)=0.95, \mathsf P(T_k{\,=\,}0\mid D{\,=\,}0)=0.95$.

What is the probability of having the disease given both tests are positive?

$\mathsf P(D{\,=\,}1\mid T_1{\,=\,}1,T_2{\,=\,}1)$

What is the probability of having the disease if they get a different test (results) and that test is only 90% accurate?

$\mathsf P(D{\,=\,}1\mid (T_1{\,=\,}1,T_2{\,=\,}0)\cup(T_1{\,=\,}0,T_2{\,=\,}1))$
Comment: Thanks. I see it now. I forgot about the fact it is a repeated trial of an independent test with only two possible outcomes. So hard to remember how to connect all these probability concepts! :-)
(Note: In your answer, the second case wasn't different test results, it was a completely different test provider that has a different test sensitivity. But I get your point.)
Comment: Actually, for the second case, is a Bernoulli trial the correct approach? In the second case the probability of the two outcomes is different. Shouldn't there be a different approach?
Comment: They are still conditionally independent Bernoulli variables, they are just not identically distributed.  All you have to do is adjust for the different success rate. @Bryon
Comment: So P(TaTb|D) will be P(Ta|D) x P(Tb|D) in both cases? 0.95^2 and 0.95x0.9?

bayes probability for consecutive tests


Date validator that validates if the date is greater than or equal to today with Zend Framework

Question: $form = new Zend_Form();

$mockDate = new Zend_Form_Element_Text('mock');

$mockDate->addValidator(???????);

$form->addElements(array($mockDate));

$result = $form->isValid();

if ($result) echo "YES!!!";
else echo "NO!!!";

Assumption that the element is in a date format. How do I determine that the date given is greater than or equal to today?
Answer: You can create a simple validator to do this:
class My_Validate_DateGreaterThanToday extends Zend_Validate_Abstract
{
    const DATE_INVALID = 'dateInvalid';

    protected $_messageTemplates = array(
        self::DATE_INVALID => "'%value%' is not greater than or equal today"
    );

    public function isValid($value)
    {
        $this->_setValue($value);

        $today = date('Y-m-d');

        // expecting $value to be YYYY-MM-DD
        if ($value < $today) {
            $this->_error(self::DATE_INVALID);
            return false;
        }

        return true;
    }
}

And add it to the element:
$mockDate->addValidator(new My_Validate_DateGreaterThanToday());

You probably want to check the date with Zend_Date for localization of dates and further benefits.
For creating custom validates, take a look at writing validators from Zend´s manual.
Comment: Should be `<=' for `not greater than or equal`
Answer: The question is rather old. In the current version of ZF2 it is not necessary to write new validators. Simply add a filter / validator like this:
public function getInputFilter()
{
    if(!$this->inputFilter){
        $inputFilter = new InputFilter();
        $inputFilter->add(array(
            'name' => 'mock',
            'validators' => array(
                array('name' => 'Date'),
                array(
                    'name' => 'GreaterThan',
                    'options' => array(
                        'min' => date('Y-m-d'),
                    ),
                ),
            ),
        ));
        $this->inputFilter = $inputFilter;
    }
    return $this->inputFilter;
}

And it does the job. There is also an option called 'inclusive' which if set to 'true' (in the 'options' of GreaterThan), will allow 'today' to be a valid date
Answer: class My_Validate_DateGreaterThanToday extends Zend_Validate_Abstract
{
    const DATE_INVALID = 'dateInvalid';

    protected $_messageTemplates = array(
        self::DATE_INVALID => "'%value%' is not greater than today"
    );

    public function isValid($value) {
        $this->_setValue($value);

        $date = new Zend_Date($value);
        $date->addDay(1);
        $now = new Zend_Date();

        // expecting $value to be YYYY-MM-DD
        if ($now->isLater($date)) {
            $this->_error(self::DATE_INVALID);
            return false;
        }

        return true;
    }
}

that's better because uses standardized Zend_Date methods to check dates, the other awsner user a string comparison that can evaluate to impredictable values...
Comment: Your post should probably include a description of "why" you think this is better.
Comment: It's not better you just added another file to include with Zend_Date. What do you think Zend_Date calls.


Show specific field(s) from created content-type

Question: Question might be easy, but I have a problem. I created a content-type (page), made it as a block with Node Block module, put this block in content. But it prints all stuff: title, authored by, date and so on. But what I nead is to print only body. But there might be another case, when I want to print also a title.
So the question is in general, how to print fields that I want from content-type,  maybe there is a module for this or a more convenient way.
I'm using latest Drupal 7.
Thanks!
Answer: You can configure this as a per content type level, not for each node in particular.
Edit the content type, go to Node Block settings and under Default view mode select a convenient value. Then, click on Manage presentation tab and select the same value you set previously under Default view mode, and finally configure the fields and positions you want to be rendered.
Comment: Yes, I'm still learning Drupal, so no coding needed in this case. Thank you for your answer anyway!
Comment: There is no coding involved in this procedure.


admin for editing particular user

Question: I have users signed up to my site. I want to be able to edit their "bids". Basicaly, I want to be able to go to admin/user/user-bid/73 where 73 is a particular user's id and be able to edit their bid info. How can I do that?
I have the following in admin.py:
class UserBidAdmin(admin.ModelAdmin):
    def queryset(self, request):
        return self.model.objects.filter(user = request.user)

create_modeladmin(UserBidAdmin, name='user-bid', model=Bid)

def create_modeladmin(modeladmin, model, name = None):
    class  Meta:
        proxy = True
        app_label = model._meta.app_label

    attrs = {'__module__': '', 'Meta': Meta}

    newmodel = type(name, (model,), attrs)

    admin.site.register(newmodel, modeladmin)
    return modeladmin

Thanks.
Answer: class BidInline(admin.TabularInline):
    model = Bid

class UserWithProfileAdmin(UserAdmin):
    ..........

    inlines = [BidInline]

admin.site.unregister(User)
admin.site.register(User, UserWithProfileAdmin)

Comment: how do you access the bidinline? by url?
Comment: No, you don't have to access it by url. I put the Bid inside the User information. Let say, go to admin and you will see "Users", click that. Inside of that is the list of the users register in your site. Click any user on the list, you will see below the bid information
Comment: this allows me to changes user's bids. How do I display the bids and not change them? Thanks.
Comment: use readonly in admin, like this: readonly_fields = ('field_name', 'field_name', 'field_name')

admin for editing particular user


Total variation does not take into account large distances.

Question: Let $(X,\Sigma,\mu)$ be a measure space, then define
$$|\mu |(E):=\sup\limits_{\pi }\sum _{A\in \pi }|\mu (A)|\qquad \forall E\in \Sigma $$ where the supremum is taken over all partitions $\pi$ of the set $E$.
I have two questions with respect to this total variation norm.
First, I am not so  sure why for probability measure we are left with :
$${\displaystyle |\mu -\nu |(X)=2\sup \left\{\,\left|\mu (A)-\nu (A)\right|:A\in \Sigma \,\right\}}$$
Second, I read that "total variation does not take into account large distances" but I don't really understand how to interpret this sentence.
Comment: For the question about probability measures, note that $|\mu(A)-\nu(A)|=|(1-\nu(A))-(1-\mu(A))|=|\mu(A^C)-\nu(A^C)|$ for every measurable set $A$ if $\mu$ and $\nu$ are probability measures.
Comment: What's $\nu$? Your initial definition only uses $\mu$.
Comment: Ahh, nevermind, I see what you did there. Taking $\mu$ as a potentially signed measure in the initial definition.
Comment: @MichaelGreinecker, thank you. This gives us the part ${\displaystyle |\mu -\nu |(X)\ge 2\sup \left\{\,\left|\mu (A)-\nu (A)\right|:A\in \Sigma \,\right\}}$ right? (by considering partitions $(A,A^c)$ of $X$).
Comment: @edamondo Exactly. Though that you only need partitions into two sets (a set and its complement) is not trivial and follows from the [Hahn-decomposition](https://en.wikipedia.org/wiki/Hahn_decomposition_theorem).
Comment: @MichaelGreinecker I see, the partition $(X_-,X_+)$ given by the Hahn decomposition seems to be a minimizer among all partitions so we get the other inequality.
Answer: For your first question: suppose $\pi$ is a partition of $X$. For each $A\in\pi$, we must have either $\mu(A)\geq\nu(A)$ or $\mu(A)<\nu(A)$. Let $\pi_{\geq}$ and $\pi_{<}$ represent the subsets of the partition with each of these properties.
Then define
$$
P_\pi:=\bigcup_{A\in \pi_{\geq}}A\qquad N_\pi:=\bigcup_{A\in\pi_{<}}A.
$$
A few things to note:

We have $\mu(N_\pi)=1-\mu(P_\pi)$ and $\nu(N_\pi)=1-\nu(P_\pi)$.

Note that
$$
\begin{align*}
\sum_{A\in\pi}\lvert\mu(A)-\nu(A)\rvert&=\sum_{A\in\pi_{\geq}}\lvert\mu(A)-\nu(A)\rvert+\sum_{A\in\pi_{<}}\lvert\mu(A)-\nu(A)\rvert\\
&=\sum_{A\in\pi_{\geq}}(\mu(A)-\nu(A))+\sum_{A\in\pi_<}(\nu(A)-\mu(A))\\
&=\sum_{A\in\pi_{\geq}}\mu(A)-\sum_{A\in\pi_{\geq}}\nu(A)+\sum_{A\in\pi_{<}}\nu(A)-\sum_{a\in\pi_{<}}\mu(A)\\
&=\mu(P_\pi)-\nu(P_\pi)+\nu(N_\pi)-\mu(N_\pi).
\end{align*}
$$
(There are some steps to justify there!)

Now, note that $X$ is the disjoint union of $P_\pi$ and $N_\pi$, and therefore
$$
\mu(P_\pi)-\mu(N_\pi)=\mu(P_\pi)-(1-\mu(P_\pi))=2\mu(P_\pi)-1
$$
and similarly $\nu(P)-\nu(N)=2\nu(P)-1$. So, we have
$$
\sum_{A\in\pi}\lvert\mu(A)-\nu(A)\rvert=2(\mu(P_\pi)-\nu(P_\pi))=2\lvert\mu(P_\pi)-\nu(P_\pi)\rvert.
$$
So, we can now conclude that
$$
\sup_{\pi}\sum_{A\in\pi}\lvert\mu(A)-\nu(A)\rvert=2\sup_{\pi}\lvert\mu(P_\pi)-\nu(P_\pi)\lvert.
$$

What remains is to show that
$$
\sup_\pi\lvert\mu(P_\pi)-\nu(P_\pi)\rvert=\sup_{A\in\Sigma}\lvert\mu(A)-\nu(A)\rvert.
$$
On the one hand, $P_\pi\in\Sigma$ for all $\pi$, so that
$$
\sup_{\pi}\lvert\mu(P_\pi)-\nu(P_\pi)\lvert\leq\sup_{A\in\Sigma}\lvert\mu(A)-\nu(A)\rvert.
$$
On the other hand, for any $A\in\Sigma$ you can note that $X=A\dot\cup(X\setminus A)$ is a partition, which proves the other direction.
For your second question around 'large distances', it really depends a lot on what the context is. But there is definitely an asymmetry to total variation.  Take $\nu$ and $\mu$ to be probability measures. Then the total variation distance is basically about finding an event on which the two measures disagree as much as possible. So total variation distance $0$ tells you a whole lot: the distributions are essentially identical.  But total variation distance 1 tells you that you can basically partition the event space into one where $\mu$ reigns and one where $\nu$ does; this might or might not be important depend on what is happening downstream of your probability distribution.  Maybe it is, for instance, latching on to some property that isn't actually relevant to the question you're trying to ask.


How do I maintain aspect ratio of scaled image with max-width?

Question: When I use an Image Style that scales the original image, Drupal 7 (now 7.14) prints the height and width attributes in the img tag whereas before it didn't.
So before, my CSS img {max-width: 100%;} preserved the images aspect ratio when displayed in a small box (i.e. on a mobile screen), but now clashes with height and width attributes. Drupal generates enclosing boxes with no explicit height so the result is an elongated distortion.
What can I do - preferably with CSS alone, but in a template file's php if necessary - to preserve the aspect ratio?
Comment: To clarify, this problem started after you upgraded to Drupal 7.14 because img tags now specify height and width attributes?
Comment: For reference, see http://drupal.org/node/1345744
Comment: @JonathanElmore Yes.
Answer: It's as simple as just adding height:auto;
img {
max-width:100%;
height:auto;
}

Answer: I haven't tried it but using CSS you might just get away with:
img {max-width: 100% !important;}

If not, I think the simplest solution would be just to stop the theme_image() function from outputting the width and height attributes (in template.php as you suggest). There are couple of ways you could do this.
Firstly, you could implement hook_preprocess_image() to remove the attributes from the theme vars:
function MYTHEME_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    if (isset($variables[$key])) {
      unset($variables[$key]);
    }

    if (isset($variables['attributes'][$key])) {
      unset($variables['attributes'][$key]);
    }
  }
}

That method may have the potential to be overridden by something else in the system though. To get around that you can simply override the theme_image() function altogether (it's not a long function):
function MYTHEME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  // 'width' and 'height' have been removed here
  foreach (array('alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '';
}

Comment: I use the `theme_image()` method with good results.
Answer: I use this technique for responsive images with fitting into its container (and aligned to whatever point in it) which is also responsive. With this technique you can make miracles. Responsive miracles.
https://stackoverflow.com/a/28073729/1663572


How do i proof that that the map $ \varphi: Aut(F_n) \to GL_n(\mathbb{Z})$ is homomorpism?

Question: I'm trying to proof that a map  $ \varphi: Aut(F_n) \to GL_n(\mathbb{Z})$ is a homomorphism but i can't exactly define which is the function  to show that.
The map $ \varphi $ is a map with for any $ \alpha \in Aut(F_n)  $ the $(i,j)$-th entry of the matrix $ \varphi(a) $ is the sum of exponents of the letter $x_j$ in the $ a(x_i)$.
$F_n$ denotes the non-abelian free group generated by $n$ elements
Comment: What does $F_n$ denote? The abelian free group generated by $n$ elements, or the (non-abelian) free group generated by $n$ elements, or something else?
Comment: $F_n$ denotes the non-abelian free group generated by $n$ elements. Sorry i didn't mentioned that.
Answer: The easiest way to see this is to note that this map factors through an abelianization of $F_n$. Namely, if we quotient by the commutator subgroup then an element $x_{i_1}x_{i_2}\cdots x_{i_n}$ reduces to $x_1^{m_1}x_2^{m_2}\cdots x_n^{m_n}$, where $m_i$ is the sum of the exponents of $x_i$ in the expression. For any automorphism $\alpha:F_n\to F_n$ there is a corresponding automorphism $\alpha':\mathbb{Z}^n\to\mathbb{Z}^n$ where $\alpha'(x_i)$ is the element obtained by combining the powers of each generator. But $\alpha'$ is exactly the element of $\mathrm{GL}_n(\mathbb{Z})$ that $\alpha$ is mapped to.
Comment: Thanks for your Reply .i have one more question and maybe silly.
Is possible to define a function directly from $Aut(F_n) $ to $GL_n(\mathbb{Z})$ and with easy calculations show that induce a homomorphism ?
This question because your way shows the result by different map $ Aut(F_n) \to Aut(F_n/[F_n,F_n])$ which is isomorphic to $ GL_n(\mathbb{Z})$ . Thank you.
Comment: Compose with an isomorphism with the matrix group using the generating set as a basis?
Comment: The abelianization is isomorphic to $\mathbb Z^n$ in such a way that you get the homomorphism you want. Map the generating set to the basis elements of $\mathbb Z^n$.
Answer: In general, if $\kappa \colon G \to G/K$ is natural projection where $K$ is characteristic in $G$, then the map $\kappa$ induces a homomorphism $\tilde{\kappa} \colon \mathop{Aut}(G) \to \mathop{Aut}(G/K)$ given by $$\tilde{\kappa}(\phi)(g K) = \phi(g)K$$ for every $g\in G$ and $\phi \in \mathop{Aut}(G)$.
By setting $G = F_n$ and $K = [F_n,F_n]$ you can check that the map you get exactly the one have described.


Why isn't DragDrop enabled textbox accepting files?

Question: AllowDrop is enabled on both Form1 and textBox1. The events are enabled and start when DragDrop and DragEnter are performed. I've already tried rearranging the code so that textBox1_DragEnter is located before textBox1_DragDrop, but that doesn't work. What is wrong with this code?
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
    FileInfo fi = new FileInfo((string)e.Data.GetData(DataFormats.FileDrop));
    byte[] ba = Encoding.Default.GetBytes(fi.OpenText().ToString().ToCharArray());
    textBox1.Text = ba.ToString();
}

private void textBox1_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        string file = (string)e.Data.GetData(DataFormats.FileDrop);
        if (Path.GetExtension(file) != "dat")
        {
            s = "broken file";
        }
    }
}

Comment: You have to show us your "unshown" code.
Comment: I added it. Sorry.
Comment: If you have UAC turned on and you're running the program as an Administrator, you won't be able to drag and drop something from Windows Explorer onto your form.
Answer: You have to set the Effect property in the DragEnter event:
void textBox1_DragEnter(object sender, DragEventArgs e) {
  e.Effect = DragDropEffects.Copy;
  // your code...
}

Comment: Thanks. That allows it to accept data, but it doesn't show up. That's a separate problem, though. I'll work on debugging that.


Why won't this quadratic equation return negative numbers?

Question: This quadratic equation will not return negative numbers in the string that I've determined it to return.
Here's the equation:
public class QuadraticEquation  {

    String final0;
    public String calculate(int a, int b, int c) {
        double done1 = ((-1 * b) + Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
        double done2 = ((-1 * b) - Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
        final0 = "x = " + (done1) + " or x = " + (done2);

        return final0;
    }
}

imagine an equation with a, b, and c values like -3, 13, and -4. The returning value of this would be -0.3(repeating) and -4. But this equation only returns positives, so in this case it would return 0.3(repeating) and 4. Why is this, and what can I do to fix it?
Note: I do believe that this is a Java error and not a math error. If it is a math error, let me know in the comments and I will promptly put it in the proper forums. Thanks.
Comment: Isn't the right answer just 0.3? (-1 * 13 + sqrt(13 * 13 - 4 * -3 * -4)) / (2 * -3) = (-13 + 11) / (-6) = 0.333
Comment: I know it won't handle imaginary numbers. I dont want to deal with that. I still don't understand this.
Comment: @assylias sqrt returns double.
Comment: @ZiyaoWei But you then divide by `(2 * a)`, which is an int. Also this will not handle imaginary numbers. a, b and c should probably be doubles.
Comment: @ZiyaoWei Yes indeed. You should post it as an answer.
Comment: It's the right answer.
Comment: This equation does not return just positive numbers, try `3, 13, -4`, which returns `0.29, -4.62`.
Comment: @assylias Thanks for the suggestion, but people are doing that, so I won't add to the noise:)
Answer: I would have thought
-3*x^2 + 13 *x + -4 = -3 * (x - 0.33333) * (x - 4) = 0

so two positive answers is correct.
Try instead
1 * x^2 + 0 * x -1 = (x - 1) * (x + 1) = 0

i.e. x = -1 or +1

Here is how I would write it.
public static String calculate(int a, int b, int c) {
    double sqrt = Math.sqrt((b * b) - (4 * a * c));
    double done1 = (-b + sqrt) / (2 * a);
    double done2 = (-b - sqrt) / (2 * a);
    return "x = " + (done1) + " or x = " + (done2);
}

Answer: public static void main(String[] args) {

    String final0 = calculate(-3, 13, -4);
    System.out.println(final0);

}
public static String calculate(int a, int b, int c) {
    String final0 ;
    int i = -1 * b; // -1 * 13 = -13
    System.out.println(i);

    int j = 4 * a * c; // 4 * -3 * -4  = 4 * 12  = 48
    System.out.println(j);

    double sqrt = Math.sqrt((b * b) - j); // sqrt ((13 * 13) - 48) = sqrt(169 - 48) = sqrt(121) = 11
    System.out.println(sqrt);

    double d = i + sqrt; // -13 + 11 = -2
    System.out.println(d);

    int k = 2 * a; // 2* -3 = -6
    System.out.println(k);

    double done1 = d / k; // -2 / -6 = 1/3 = 0.3333333333
    System.out.println(done1);

    double done2 = (i - sqrt) / k;
    final0 = "x = " + (done1) + " or x = " + (done2);

    return final0;
}

If you decompose your method to more local variables, you will see that math in java works correctly.
Answer: The code is working correctly with your input. If you changed b to be -13 for example, you would get
x = -4.0 or x = -0.3333333333333333
Math.sqrt will always return a positive number ignoring complex numbers. But that is somewhat besides the point.


Set default fill & stroke colors in Raphael.js

Question: Is it possible to set a default fill and stroke color in Raphael so that I don't have to specify it every time I create a new shape?
Comment: Could you just set some css on the svg, or elements, like svg { fill: blue; } ?
Answer: You can use a set and apply the colours to the set
<code>var st = paper.set();
st.push(
    paper.circle(10, 10, 5),
    paper.circle(30, 10, 5)
);
st.attr({fill: "red"}); // sets the fill of both circles
</code>


Trigger delete cache of url

Question: I've two api url

/api/v1/get-list
/api/v1/post-item

In API url /api/v1/get-list I was set cache like this:
<code>$build = [
  '#cache' => [
    'contexts' => ['url','url.query_args'],
    'max-age' => 3600,
  ],
];

$res = new ResourceResponse($response, 200);
$cache_metadata = CacheableMetadata::createFromRenderArray($build);
$res->addCacheableDependency($cache_metadata);
</code>
Response will be cache in one hour with url /api/v1/get-list?_format=josn. When I use api /api/v1/post-item response of /api/v1/get-list will changed value. But response was cached in one hour. So how to trigger delete cache of url when use orther url. I find some code
<code>\Drupal::service('page_cache_kill_switch')->trigger();
</code>
but just for current request.
Answer: Add a cache tag to the response of /api/v1/get-list:
<code>$build = [
  '#cache' => [
    'contexts' => ['url','url.query_args'],
    'max-age' => 3600,
    'tags' => ['api-v1-list'],
  ],
];
</code>
and then invalidate this tag in /api/v1/post-item:
<code>\Drupal\Core\Cache\Cache::invalidateTags(['api-v1-list']);
</code>

Trigger delete cache of url


Jquery slide down only if not already visible

Question: I have a simple problem using Jquery. I want to display detailed information under menu headings, but the interface isn't so smooth. After a few hours of trying some things out, I've come back to the beginning to see if there is a simple answer
Look at this example
Two problems:

If you mouse over several categories at once to get to the category you want, the animation still runs through all of the other animations instead of stopping the other ones and only animating the one that the mouse is currently hovered over.
If you mouse over a category that is already open, it still runs the animation, but I only want the animation to run if the content is not already visible. Is there a simple if statement that can do this?
Comment: You get this figure out, you have two/three very usable answers?
Answer: $('.content').hide();
var $elms = $('.fruit, .vegetable, .dairy');
$elms.hover(function() {
    var $content = $(this).next('.content');
    $content.stop(1, 1).slideToggle(400);
});

http://jsfiddle.net/elclanrs/GBkMB/1/
Edit:
To prevent the content from sliding back up you can nest the divs like so:

fruit

apple
bannana
orange

vegetable

celery
lettuce
cucumber

dairy

milk
cheese
butter

jQ:
$('.content').hide();
var $elms = $('.fruit, .vegetable, .dairy');
$elms.hover(function() {
    var $content = $(this).children('.content'); //<-`children()` not `next()`
        $content.stop(1,1).slideToggle(400);

});

Example: http://jsfiddle.net/elclanrs/GBkMB/5/
Comment: a very elegant way! (I saw what was there before your edit...)
Comment: There's a problem with this... If you hover off to the following content it slides back up...
Comment: He's example works like that too. I don't know if this is the expected behavior. It's pretty easy to fix, just nest the divs and done. See edit.
Comment: nesting the divs is an okay way to do it, but if he can't change the HTML structure if he's in a rigid framework, he'll have to use event detection
Comment: What about just wrapping them with jQ? `$elms.each(function(){ var $content = $(this).next('.content').detach(); $(this).append($content); });`
Comment: Also, the use of "hover()" vs "on()" should be inspected by the OP
Comment: If there's no event delegation then either of those is fine. `hover` is just a shortcut.
Comment: @elclanrs this adds a tun of processing, as it has to parse each and set more event listeners. On the fiddler scale this poses no issue. but in a production environment it can be very heavy anytime you parse the DOM then use a .each() also on multiple elements where usually the closure handles that.
Comment: actually if you AJAX a list in, or you add a ".content" to the DOM after the document.ready, the "hover()" won't work on the new elements, you need to use .on() the correct way, I'll edit my answer to show an example.
Comment: @elclanrs I like your elegant answer, and you're right, it's just one example of many on how to accomplish what he's doing... I was just trying to give a little insight into performance for the OP as well.
Answer: I've edited your fiddle now to look like this. Should give you an idea of what you want to move forward:
http://jsfiddle.net/GBkMB/4/
$("body").on("hover", ".fruit, .vegetable, .dairy", function(event){
  if(event.relatedTarget != $(this).next(".content")[0]){
      if(event.type == "mouseenter"){
         $('.content').slideUp('slow');
         $('.'+$(this).attr("class")+'_types').slideDown('slow');
      }else if(event.type == "mouseleave"){
         $('.content').slideUp('slow');
      }
  }
});
$("body").on("mouseleave", ".content", function(event){
    if(event.relatedTarget != $(this).prev("div")[0]){
      $(this).slideUp('slow');
    }
});

or: http://jsfiddle.net/GBkMB/6/ @elclanrs answer ++
$('.content').on("mouseleave", function(event){
   if(event.relatedTarget != $(this).prev("div")[0]){
      $(this).slideUp('slow');
    }
});
var $elms = $('.fruit, .vegetable, .dairy');
$elms.on("hover", function(event) {
    var $content = $(this).next('.content');
    if(event.relatedTarget != $content[0]){
        $content.stop(1,1).slideToggle(400);
    }
});


How do I determine if a PowerShell Cmdlet parameter value was specified?

Question: In PowerShell 1.0, if I have a cmdlet parameter of an enum type, what is the recommended method for testing whether the user specified that parameter on the cmdlet command line?  For example:
MyEnum : int { No = 0, Yes = 1, MaybeSo = 2 }

class DoSomethingCommand : PSCmdlet
...
private MyEnum isEnabled;

[Parameter(Mandatory = false)]
public MyEnum IsEnabled
{
    get { return isEnabled; }
    set { isEnabled = value; }
}

protected override void ProcessRecord()
{
    // How do I know if the user passed -IsEnabled <value> to the cmdlet?
}

Is there any way to do this without having to seed isEnabled with a dummy value?  By default it will equal 0, and I don't want to have to seed every parameter or add a dummy value to my enum. I've potentially got many cmdlets with 100's of parameters, there's got to be a better way. This is related to this question but I was looking for a cleaner way of doing this.
Thanks.
Comment: [How to determine if a parameter is passed to a Powershell Cmdlet](http://www.reza-aghaei.com/how-to-determine-if-a-parameter-is-passed-to-a-powershell-cmdlet/)
Comment: @RezaAghaei It is best to also include the point that you're making in your comment in case you delete your blog post later. In this case, that the code`$PSBoundParameters.ContainsKey("paramater name")` can be used to check if the parameter was specified.
Comment: @Jack Straw
If you have "potentially got many cmdlets with 100's of parameters", you might want to look at breaking some of that functionality up.  One of the key benefits of PowerShell is discoverability and having large numbers of parameters makes self discovery that much more difficult.
Comment: @Steven, sorry I may have been misleading - it's not each cmdlet that has 100's of params :), but many cmdlets which result in many parameters.  Thank you for your comment.
Comment: @DaveF I see another answer is pointing to the same solution in short. Anyway, I added a summary of the blog post here as an answer, including the example.
Answer: In this case, I would use a nullable wrapper around the enum type e.g.
[Parameter(Mandatory = false)]
public MyEnum? IsEnabled { get; set; }

Note the ? modifier on MyEnum.  Then you can test if it is set like so:
if (this.IsEnabled.HasValue) { ... }

Comment: That's exactly what I was looking for.  Thanks.  I actually made the local variable, not the property the nullable type, which also works.
Answer: PowerShell aside, it's never good style to use 0 in that way. You should always use 0 for the most appropriate default. In this case, the most appropriate default should be something like "Unset."
Ultimately, this is nothing to do with PowerShell and everything to do with good coding practices for .NET.

Oisin
Comment: In v2.0 of powershell, a new property was added: this.MyInvocation.BoundParameters where "this" is PSCmdlet. This is a hashtable of key/value pairs of the parameter names and values that were bound to the cmdlet. If your enum was specified, it will be in this dictionary. If it defaulted, it won't be there. I'm not aware of anything other than string hacking that will do the same in v1.0
Comment: @x0n: Thank you for your response.  Whether using 0 or not for enum values is an arguable point, but either way my existing product does have many 0 values for enums.  I guess my broader question is, is this the pattern cmdlet developers use in this situation?  Use a default, 'unspecified' value for each parameter, and test against that before applying the parameter values to the object in ProcessRecord()?  This could get a bit unwieldy for large products with many parameter types.
Comment: x0n, thanks, I saw that 2.0 property.  Unfortunately I need to code against 1.0 for now.  I think Keith's answer below, using a nullable wrapper, is exactly what I am looking for.
Answer: As an option you can use $PSBoundParameters collection to check whether passed to the method.
Let's suppose we have a json file like following { "p1": "value1", "p2": "value2" } and we want to create a function which accepts parameter p1 and p2 and update value of p1 and p2 in the file, if they are passed to the function. Let's say those values can be null and and having those values as null is not equivalent to not passing them.
For example Update-Values -p1 $null should update p1 to null and should not change p2.
To do so, we should be able to detect if the parameter has been passed to the method or not.
Example - How to detect if a parameter is passed, for an optional parameter which can accept null as value?
Function Update-Values ($p1, $p2) {
    If($PSBoundParameters.ContainsKey("p1")) {
        Write-Host "p1 passed"
    }
    else {
        Write-Host "p1 not passed"
    }
    If($PSBoundParameters.ContainsKey("p2")) {
        Write-Host "p2 passed"
    }
    else {
        Write-Host "p2 not passed"
    }
}

Then if you run the function using the following parameter:
Update-Values -p1 $null
# Update-Values -p1 "something"

As a result you will see:
p1 passed
p2 not passed

You can read the blog post here: How to determine if a parameter is passed to a Powershell Cmdlet.
Comment: This does not work when you are writing binary commands, the PSBoundParameters variable is not present in C#
Comment: @ShawnMelton feel free to suggest a better answer. - The sample code in the answer  is obviously for PowerShell functions for those who reached to this page by search.
Answer: I know this thread is a little old now, but the best way to do this is to declare your parameter using the SwitchParameter type. Then your users don't have to pass -IsEnabled , they would just add something like -Enabled as a parameter.
You then test the .IsPresent property of your parameter to see if the caller added -Enabled to the call to the cmdlet.
Comment: @Darren: that definitely works for bool params, but I was looking for a solution for optional non-bool params.  The nullable type seems to work well.  Of course PS v2 now has a dictionary of params available in the cmdlet, so that's probably the way to go.  Thanks.
Answer: Only thing I can see is to modify your enum so that value 0 is named Unknown or something like that.
Problem is that enums are just integers in background and integers are value types. Unfortunate consequence is that they need to have value and that value is 0 by default.
Answer: bool wasSpecified = MyInvocation.BoundParameters.ContainsKey("IsEnabled");

Comment: Note that this doesn't work correctly with Positional parameters. They are not found by Name in the BoundParameters, but are specified and have a value.


Trying to replace a break but keep the same result in python

Question: I am new to coding and was told that using breaks is a bad form of programming. I was wondering if anyone knew a good way to change the break without changing how the program functions? I have attached the code I am working with.Code in question
Comment: There is nothing inherently wrong with using `break`, especially in a case like this.  Whoever told you that is doing you a disservice.
Comment: Welcome to Stack Overflow! It's a lot easier to help when you post code as text, not as an image.
Answer: Running your code I don't see any problems. What I would change is that you can make a an argument for the function and return True or False, like this:
def isprime(a):
    c=a-1
    for i in range(2, c):
        b=a%i
        if b == 0:
            return False
    else:
        return True

isprime(4)
isprime(7)

In this example I replaced break with return, this will break the loop but also return whether the number is prime or not.
To clarify, there is nothing wrong with using break and I think it is a very usefull possibility when looping.
Comment: It's especially useful in Python because of the `else:` clause of its loops.
Comment: I never knew that was a thing, dont even really know how it works.
Comment: The `else:` block is executed if the loop runs to completion rather than being exited with `break`. It's not really needed in your version, because you return instead of breaking. You can simply put `return true` after the loop.
Comment: I wasn't going for neatness, per say, just for useability and understandability as in copying the format of the questioner


d3 Sankey assign fixed x,y position

Question: I have a sankey diagram in which the user can move and position the nodes freely. I want to save the exact pixel-position selected by the user and use it in the next regeneration of the diagram.
The only way I have managed to approach this until now was to use the "x layer" of the node instead of the exact x-position (not the x-coordinate in pixels but the x-coordinate in layers/levels - 1,2,3 etc...).
Is there a way to use the pixel coordinate instead?
Comment: Could you explain precisely what happens between each "regeneration"? The solution is going to be rather different if you insert or delete nodes, etc. And if your data doesn't change too much, and you want to keep the same node positions, why let sankey move the nodes in the first place?
Comment: The data changes a lot. Users can add and remove nodes, but should also be able to position them. So nodes have to have a fixed position. This is why I think the transform proposition below would not work, since adding a new node is not taken into account and the existing nodes with transforms will be moved to a saved position that doesn't fit in the new arrangement.
Comment: How would you go on about inserting a node in a sankey graph when all the rest have fixed positions? Sankey is designed to build a layout from scratch, so you'd basically end up editing the whole Sankey file. Why not use Sankey for the first layout, then a force diagram to place new nodes (where every old node is fixed)?
Answer: I guess you're using transform when the user moves the nodes.
If you assign each node an id, you could save pairs like [ (#id, transformation) ..; ] and apply it again after.
I could try something if you show your code :)
Comment: Hey pltrdy, I'm using a code similar to the accepted answer here http://stackoverflow.com/questions/21539265/d3-sankey-charts-manually-position-node-along-x-axis?rq=1

At the moment I'm using the 'xPos' attribute for a node to position it on the x-axis, but it's not sufficiently accurate. I'm curious if the transform idea would work well when new nodes are added or existing nodes are removed. For this, the transformation should not be relative to the node's position, but instead bring the node to a fixed coordinate. I hope this makes sense.
Comment: Hello pltrdy, I awarded you the bounty for the idea, but I sadly didn't have time to talk to you in more detail about it. Would you be so kind to help me follow this line of thought a bit further these days?
Comment: sure, was a bit busy. I'll be back to you asap ;) And thx for the bounty!
Comment: You definitely should make a jsfiddle, then we could practically discuss your issue. I could only speak about the idea just because I dont have access to your code. I guess I won't be able to give better anwser without code
Comment: Hi pltrdy, do you have any means of communication outside Stackoverflow?
Answer: The sankey plugin acts as your data model.  All it does is calculations of x for the 'rect's and 'dx' for the paths and many other position calculations.  You can capture those positions with the 'dragend'.
Once you have the data you can get and set with pattern
var getNodes = sankey.nodes();
//do something here to set the position
sankey.nodes(getNodes);

Then you would doe the same with the links. Then recalculate everything.
sankey.layout()

Without seeing your code I am sure there will bet another step to make sure this works, but you will find it is an easy module to update.
You might want to check the actual source code because I have a custom version that might have different variable names, but it works the same.
Answer: You can extract the x and y values and save them into an array as follows:
var savedCoordinates = sankey.nodes().map(function(d) {
        return {x:d.x, y:d.y};
});

Of course, this must be used after the layout has been computed, otherwise x andy values are undefined.
To return to your saved coordinates, you can use the following:
sankey.nodes().forEach( function(d,i) {
      d.x= savedCoordinates[i].x;
      d.y= savedCoordinates[i].y;
});

Finally, you'll need to update the drawing with whichever drawing function you are using (updating the transform attributes of g nodes and the path attributes for the links).
PS: You notice that I'm assuming the node order doesn't change. If it does, you need to provide an id field, or similar to your data... do you have one?

d3 Sankey assign fixed x,y position


Writing Karma + Mocha tests with both dependency injection and `done`?

Question: What's the most elegant way to write Karma unit tests in mocha that both have dependency injection and done?
Dependency injection:
describe('cows', function(){
  it('farts a lot', inject(function(cow){
    // do stuff
  }))
})

Done:
describe('cows', function(){
  it('farts a lot', function(done){
    // do stuff
  })
})

What if I want both cow and done available in my unit test? Right now, this is what I'm doing, and it's unsatisfactory.
beforeEach(inject(function(cow){
  this.cow = cow;
}))

it('farts a lot', function(done){
  this.cow // etc
})

Answer: You can nested function inject into test function
it("should nested inject function into test function", function(done) {
    inject(function($timeout) {

      $timeout(function() {
        expect(true).toBeTruthy();
        done();
      }, 10);

      $timeout.flush(10);

    });
  });

inject is global function defined in ngMock module and can be used anywhere in the test.


1988 AIME Problems/Problem 15. Problem related to ordering of letters and typings...

Question: 1988 AIME Problems/Problem 15
Problem:
In an office at various times during the day, the boss gives the secretary a letter to type, each time putting the letter on top of the pile in the secretary's in-box. When there is time, the secretary takes the top letter off the pile and types it. There are nine letters to be typed during the day, and the boss delivers them in the order $1, 2, 3, 4, 5, 6, 7, 8, 9$.
While leaving for lunch, the secretary tells a colleague that letter $8$ has already been typed, but says nothing else about the morning's typing. The colleague wonders which of the nine letters remain to be typed after lunch and in what order they will be typed. Based upon the above information, how many such after-lunch typing orders are possible? (That there are no letters left to be typed is one of the possibilities.)
I am unable to think of a proper way to frame the answer. Could someone kindly provide a simple answer, with a lot of explanation. Binomial coefficient-related methods or, if possible, a generating function approach would really be helpful and instructive. Thanks for your help!
Answer: You know $8$ has already been typed, so from $1$ to $7$ have been added to the pile at some point. And about $9$ you don't know if it has been added to the pile or not.
Given a subset $P$ of $\{1,2,3,4,5,6,7\}$, if the number of elements in $P$ is $p$, you can add the $9$ before typing the first element of the subset, before typing the second element of the subset, ..., before typing the last element of the subset, after typing the last element of the subset or you can have the $9$ been added already, what gives us $p+2$ different possibilities for each subset $P$ . So for a subset $P$ of length $p$, there are $p+2$ different typing orders. If you multiply this for the number of ways you can arrange $p$ elements of a set of length $7$, and do this for all $p\in \{1,2,3,4,5,6,7\}$ you get the answer:
$$ \sum_{p=0}^7{7 \choose p}(p+2)=704$$
Comment: I'm sorry for disturbing you but could you clarify this: So, basically you get (p+1) from P ∪ {9} and the other +1 from the case wherein 9 is absent? So, finally, we get (p+2)? But thanks for the answer anyway! Really appreciated.
Comment: Am I right that the number of typing orders *from the start of the day* is just $9!$ ?
Comment: I have edited it, I am not good at explaining these things, but if you don't get it, I'll try to explain it better.
Comment: @Vasu090 No, for example you cannot type the $6$, then the $4$ and then the $5$.
Comment: So, what is the answer to that question? Seems quite puzzling. :)
Comment: Thanks, so much @Alfredo! You're an angel! Really, man, much obliged!


How did I make this noise?

Question: This is a really specific question, but I was fooling around on bass guitar and made a really cool (imo) noise which I couldn't replicate afterwards. I happened to record it. If someone could tell me what I did I would be immensely grateful. I'm referring to a buzzing/beeping/sliding sound after the eleventh note.
Link here:
https://drive.google.com/open?id=0B8hQAZ8FmWcfZ3I1UU9TSmFZT0k
BTW bass is not my primary instrument.
Answer: Sounds to me like you inadvertently produced a natural harmonic, albeit for a fraction of a second. It seems that you pluck near to the bridge, which will always produce harmonics best, and the trebly tone helps too.
Harmonics are made when a string is touched gently on a node point. At the bottom end of the string, they're more difficult to produce accurately, so well done!
Try touching the string over the 12th fret, and plucking near to the bridge. You'll hear a ringing sound an octave higher than the open string. There are two other easy ones, above 7th and 5th frets.
As you touch getting closer to the nut, there are more, getting higher each time you move the finger to the left. One of those is your 'culprit'. Because you moved your finger along the string just after, it got killed, but to make it last, take your finger tip away. Or not - as at that point, the string is not moving anyway, so it really doesn't matter. Prove this at 12th fret. Touch, play, then touch again. The harmonic will still ring out!
EDIT: It bugged me a little, so on replay, I guess it might even be a pinched harmonic, produced by simultaneously touching the A string at a point about 2 frets away from the bridge. Sounds weird - but count the first 2 and a bit frets, and measure that distance from the bridge. Touch with a finger/thumb, and pluck with a thumb/finger. Whilst pressing down fret 3! You won't be so lucky now - it'll take a bit of fiddling, especially to find the exact spot for that node. Move along the string slowly.
Comment: +1 for the harmonic. I guess the OP accidentally put their right hand over the 5th fret, because the harmonic seems to be 2 octaves above the base tone. I imagine (never played bass guitar though) that they were playing empty, occasionally fingering it on 2nd-4th fret. And by the way, the harmonics on the 5th fret are not easy to do, so I second the "Well Done"!
Comment: Pretty sure it's both fret noise and a harmonic, as in the fret noise happened to activate the harmonic. Happens to me all the time.
Answer: It's just your finger sliding across the bass string really fast. It's called string noise and is actually an undesirable sound for both guitar and bass players.
There is a practical use that doesn't sound completely the same, but still within the harmonic spectrum (sounds similar). It's called Artificial Harmonics.
Comment: What you did is hard to replicate on command. You actually released the string too slow and the string vibrated on your finger as it was leaving.
Comment: @PhillipBrandel again it is hard to replicate the pitch of string finger noise. Since you'd need the exact same frequency of vibration to hit your finger at the exactly the same time in the exactly the same location on the fretboard. I did re-edit my answer to contain a bass player who has mastered this harmonical technique that shows a practical use to harmonics.
Comment: Do you know how exactly I made it though? I tried sliding my fingers along the strings and I couldn't make that exact sound. Undesirable or not, I would like to be able to replicate it.
Comment: To clarify: in the recording, the sound definitely has a discernible pitch, but when I tried to replicate it by sliding my finger on the string, I could not recognize any pitch associated with the string noise.
Comment: "Undesirable"? Umm Tom Morello [begs to differ](https://youtu.be/0W6WZK3AfKE#t=2m31s).
Comment: @ToddWilcox Hahahha, I'd love to see that on bass. That'd hurt so bad for the audience I'm dying hahaha.

How did I make this noise?


Classical Newton method for minimization

Question: For a quadratic convex function Classical Newton method for unconstrained optimization reaches the minimum point in one iteration. It this true?
If so, what is the proof ?
Comment: In one iteration.
Comment: The minimum of a quadratic convex function, even in multiple variables, amounts to the root of a linear system, which the Newton iteration finds (using the inverse Jacobian in the multivariable case).
Comment: In how many iteration does it find ?
Comment: Can you suggest the proof of getting it in one iteration for multivariate case
Answer: Recall that a quadratic convex function, $f(\overline{u}) = \overline{u}A\overline{u}^T + \overline{u}b^T$, has a unique global minimum characterized by the vanishing of first partial derivatives.
Thus if $\nabla_f$ is the gradient of $f$, the minimizing point $\overline{u}$ is also the solution of the system $\nabla_f = 0$.  Minimizing $f(\overline{u})$ by Newton's method means to solve the system $\nabla_f = 0$ by Newton iterations.
However one such iteration suffices because the gradient of $f$ is a linear function of $\overline{u}$, and the Newton iteration step is simply to solve the corresponding system.
Comment: The Hessian of $f$ is the matrix of second partial derivatives, and when we apply Newton's method to solve $\nabla_f = 0$, the "correction" to our initial value $\overline{u}$ is computed using the Hessian inverse.  For some background see [these class notes](http://www.math.udel.edu/~angell/Opt/conv_fcn.pdf) by Prof. Tom Angell at Univ. of Delaware, but your case is the simple one where the Hessian is a constant matrix (the same for every $\overline{u}$).
Comment: I got the idea clearly. Can you suggest me some good material about this to read ?


Customizing atom package snippets

Question: I downloaded a Laravel syntax package for Atom (atom-laravel).
The tiny problem I just discovered, is that when I trigger "section", the output is:
@section('...')
@endsection

Now, I've read, that @endsection is outdated since Laravel 4. The proper directive to use is now @stop
How can I customize the package, for that trigger to return:
@section('...')
@stop

Is there a file I can modify to do so?
Answer: Under Settings -> Packages in Atom, you can click the Package and then View Code, which opens a new Atom instance with the downloaded package. Any changes you make will be instantaneous after you save.
Specifically you're looking for /snippets/laravel.cson file, and I think the section directive, which is line 628.
Edit: According to my copy of atom-laravel, which I just downloaded, the snippet should be outputting stop:
 section:
    prefix: "section"
    body: '''
      @section('${1:name}')
        $2
      @${3|stop,show,overwrite|}

Comment: Updated it. Works fine. Although I wonder what causes the atom-laravel syntax not to appear in the editor. But that's a different problem. I appreciate your help.
Comment: I've checked my code, and It looks exactly the same on my machine. What I discovered, is that the trigger uses the syntax from the other package that I have (language-blade) which returns @endsection. Should I just modify the other one, the way you described, and delete the section code from language-blade?
Comment: @manjii If `language-blade` is conflicting with `atom-laravel`, you might not be able to have both installed. I'd recommend either removing `language-blade` or modifying `language-blade` so it no longer outputs the `@endsection`, allowing `atom-laravel` to do its job. Consider raising an issue on `language-blade`'s GitHub and let them know that blade is interfering with laravel like that.
Comment: I disabled the language-blade package for now but I don't really know how to toggle the atom-laravel syntax on now. WIth language-blade I just had to choose "Blade" in the bottom-right corner of atom editor and I don't see any name related to atom-laravel syntax. BTW, reported an issue on language-blade GitHib, as you recommended.
Comment: @manjii Laravel's code snippets should appear when you start typing in a PHP file. I am surprised that the two plugins didn't work together, as [this link](http://www.mybelovedphp.com/2015/06/30/laravel-5-1-development-with-the-atom-editor/) recommends using `language-blade` with `atom-laravel`. Perhaps revert to your original idea of editing `language-blade` instead?

Customizing atom package snippets


Using the fetch() method in database query to get an array

Question: I have a very simple query that does the job, to get a collection of a specific content type's node id and title, that's it.
$connection = \Drupal::database();
$query = $connection->select('node_field_data', 'n');
$query->condition('n.type', 'employee');
$query->condition('n.status', 1);
$query->fields('n', ['nid', 'title']);
$results = $query->execute()->fetchAll();

And what i get is an array filled with objects (for each individual results) with two properties the nid and title values. But i want to have an single layer/dimension array filled with key => valued pairs (nid => title). Example bellow.
$results = [
  0 = {stdClass} (
     nid => 123,
     value => Susan Green
  )
];

And what i want:
$results = [
  123 => Susan Green,
  567 => Bob Young
];

I've tried fetchAllAssoc, fetchAssoc, etc but either the result is empty or i get something completely opposite of what i want.
Any ideas? without using a parses to convert objects into what i want, that's what i'll do if none one can find an appropriate answer.
Answer: You can use fetchAllKeyed try with:
  $connection = \Drupal::database();
    $query = $connection->select('node_field_data', 'n');
    $query->condition('n.type', 'employee');
    $query->condition('n.status', 1);
    $query->fields('n', ['nid', 'title']);
    // use fetchAllKeyed
    $results = $query->execute()->fetchAllKeyed(0,1);

Comment: Gives this person a cookie, you are correct, thank you!
Comment: you are welcome, i'm glad that help :)


PowerShell won't rename an export .csv file

Question: I am trying to rename the file export.csv to the $name but with a .csv extension instead of .file. The output is still $name.file.
Import-Module ActiveDirectory
$name = Read-Host "Enter Group Name"
Get-ADGroupMember -identity "$name" -Recursive |select name, SamAccountName| export-csv -path C:\export.csv -NoTypeInformation

get-childItem *.file | Rename-Item -newname {$name.name -replace '\.file', '.csv'}

So I did this and it works:
Import-Module ActiveDirectory
$name = Read-Host "Enter Group Name"
Get-ADGroupMember -identity "$name" -Recursive |select name, SamAccountName| export-csv -path h:\groups\export.csv -NoTypeInformation
rename-item "h:\groups\export.csv" $name
Dir h:\groups\ | Rename-Item -newname {$_.name + '.csv'}

But how do I get it to rename the file as I run the command instead of doing it for the whole directory every time? What keeps adding .csv?
Comment: Do you get any errors?
Comment: No it runs and exports the file and adds the .csv to the end but it dows it for the whole folder so when i start doing multiple groups i get file names like group3-name.csv, group2-name.csv.csv, group1name-.csv.csv.csv
Comment: Do you mean (export-csv -path "h:\groups\$Name.csv" -NoTypeInformation) ?
Comment: Import-Module ActiveDirectory
$name = Read-Host "Enter Group Name"
Get-ADGroupMember -identity "$name" -Recursive |select name, SamAccountName| export-csv -path h:\groups\$Name.csv -NoTypeInformation

this worked
Comment: Thank you I thought i had tried that, but I guess not.
Answer: The solution is to change this line:
export-csv -path h:\groups\export.csv -NoTypeInformation
to this:
export-csv -path "h:\groups\$Name.csv" -NoTypeInformation