Evaluate the limit $\lim _{x\to e}\left(\frac{1-\log _e\left(x\right)}{x-e}\right)$ without l'Hôpital's Rule

Question:
$\lim _{x\to e}\left(\frac{1-\log _e\left(x\right)}{x-e}\right)$

I have tried to use this fact: $\lim _{x\to 0}\left(\frac{\left(a^x-1\right)}{a}\right)\:=\:\ln a$.
Comment: There is a typo in your "fact".
Answer: Hint Identify the expression in the limit as the difference quotient of a particular function $f$ at a particular point $x_0$, and hence as the value $f'(x_0)$.
Answer: $$\lim_{x\to e}\dfrac{1-\ln x}{x-e}=-\dfrac1e\cdot\lim_{x\to e}\dfrac{\ln\left(1+\dfrac{x-e}e\right)}{\dfrac{x-e}e}=?$$ as $1=\ln e$
Answer: Let $f(x):= \log_e(x)$. Then:
$\frac{1-\log _e(x)}{x-e}= -\frac{f(x)-f(e)}{x-e} \to -f'(e)$.
We have not used Lopitals rule, we only used the definition of the derivative.
Answer: $$
\begin{align}
\lim _{x\to e}\frac{1-\log _e(x)}{x-e}&= -\lim _{x\to e}\frac{\log_{e}(x)-1 }{x-e} \\
&= -\frac{d}{dx}\Bigg\vert_{x=e} \log_e(x) \\
&= -\frac{1}{e}
\end{align}
$$
Comment: The downvotes are usually a mystery for me, but the upvotes reach the unfathomable..
Comment: @RafaBudría  Understanding Mathematics may be difficult, but understanding the market can be impossible.
Answer: I'll try a different approach actually not related to L'Hôpital rule.
Suppose the limit $L$ exists, then calculate $e^L$
$$e^L=\lim _{x\to e}\exp\left(\frac{1-\ln x}{x-e}\right)=$$
$$=\lim _{x\to e}\exp(1-\ln x)^{1/(x-e)}=\lim _{x\to e}\left(\dfrac{e}{x}\right)^{1/(x-e)}=$$
$$=\lim _{x\to e}\left(1+\dfrac{e}{x}-1\right)^{1/(x-e)}=\lim _{x\to e}\left(1+\dfrac{e-x}{x}\right)^{(-1/x)(x/(e-x))}=$$
$$=\lim _{x\to e}\left[\left(1+\dfrac{e-x}{x}\right)^{x/(e-x)}\right]^{-1/x}=$$
$$=e^{-1/e}$$
Then $L=\ln e^L=\ln e^{-1/e}=-1/e$
Answer: With the change of variable $x=e^{t+1}$,
$$\lim_{x\to e}\frac{1-\ln x}{x-e}=\lim_{t\to0}\frac{-t}{e^{t+1}-e}=-\frac1e\lim_{t\to0}\frac{t}{e^{t}-1}=-\frac1e\frac1{\lim_{t\to0}\dfrac{e^{t}-1}t}.$$
Then use the given fact with $a=e$.


Arranging $8\times 8$ square so that every $2\times 2$ square satisfy $|ab-cd|=1$.

Question: Is it possible to arrange an $8\times 8$ square with numbers $1,2,\ldots,64$ once each so that for every $2\times 2$ square, if the numbers on one diagonal is $a,b$ and the other diagonal $c,d$, then $|ab-cd|=1$?
The condition $|ab-cd|=1$ means that one of $ab$ and $cd$ is odd and the other even. So there are two odd numbers in one diagonal and at least one even number in the other diagonal. But we have an equal number of odd and even numbers to fill in.
Comment: Have you tried it for smaller values of $8$?  It doesn't work for the numbers $1,2,3,4$ in a $2\times2$ square.
Answer: With that condition, two numbers $a,d$ in the same line can never both be even, since otherwise you could simply take the two numbers $b,c$ of any line in the same rows as $a,d$, and $|ab-cd|$ would be even, thus not $1$.
So you can only put one even number by line, thus at most $8$ even numbers in total, which means you can't put all numbers from $1$ to $64$.
Comment: It is possible that by $2\times2$ square, the OP does _not_ mean a $2\times2$ minor matrix. So it would actually have to be a contiguous $2\times2$ square. That just means that you can't have two even numbers _next_ to one another.
Comment: Arthur is right
Comment: ah ok, sorry for the misunderstanding.


K-theory - dependence of algebraic structure: What is the K-theory of a direct product?

Question: I want to figure out the dependence of K-class of an finitely generate projective ring and its algebraic struture.
For example consider $K_0(\mathbb{C})\cong \mathbb{Z}$ and $K_0(\mathbb{R}\times\mathbb{R})$,
where the algebraic on $\mathbb{C}$ is the standard multiplication and on $\mathbb{R}\times\mathbb{R}$ the multipation is given by: $(r_1,r_2)\times (r_1',r_2')\mapsto (r_1*r_1',r_2*r_2')$.
Are  $K_0(\mathbb{C})$ and $K_0(\mathbb{R}\times\mathbb{R})$ isomorphic?
What can we say in general?
Comment: What makes you think there could be any relationship of the kind you suggest?
Answer: Presumably algebraic K-theory preserves finite direct sums. In that case $K_0(\mathbb R\times\mathbb R)$ cannot be $\mathbb Z$.
Answer: The grothendieck group of a field $k$ is always equal to $\mathbb{Z}$ - the ring of integers. The isomorphism is as follows:
$i: K_0(k) \cong \mathbb{Z}$ with $i([V]):=dim(V)$.
In general there is for arbitrary comutative unital rings $A_j, j=1,..,l$ an isomorphism
D1. $K_i(A_1\oplus \cdots \oplus A_l)\cong K_i(A_1)\oplus \cdots \oplus K_i(A_l)$
for any integer $i\geq 0$, hence $K_0(\mathbb{R}\times \mathbb{R})\cong \mathbb{Z}\times \mathbb{Z}$.
Question: "Are K0(C) and K0(R×R) isomorphic? What can we say in general?"
Answer: The following holds:
$K_0(\mathbb{C})\cong \mathbb{Z} \neq K_0(\mathbb{R}\times \mathbb{R})$.


Show $\text{Gal}(L/\mathbb{Q}(\omega))\cong C_3 \times C_3$ with $L$ splitting field of $X^6+3X^3+3$

Question: Given the splitting field $L$ of $f(X)=X^6+3X^3+3$ over $\mathbb{Q}$. Let $\omega$ be a third primitive root of unity, so $\omega^3=1, \omega\neq 1$. Suppose $\omega^k\alpha,\omega^l\sqrt[3]{3}/\alpha\in L$, with $l,k\in\{0,1,2\}$ are the six zeros of $f$. Then I proved that $L=\mathbb{Q}(\alpha, \sqrt[3]{3})$.
I know $\alpha^3\in\mathbb{Q}(\omega)$.
Let $\sqrt[3]{3}\notin\mathbb{Q}(\alpha)$. Show $\text{Gal}(L/\mathbb{Q}(\omega))\cong C_3 \times C_3$.
My reader starts by picking $\sigma\in\text{Gal}(L/\mathbb{Q}(\omega))$. It then concludes that there are $k,l\in\{0,1,2\}$ such that $\sigma(\sqrt[3]{3})=\omega^k\sqrt[3]{3}$ and $\sigma(\alpha)=\omega^l\alpha$. Which are nine possibilities.
I know that elements of $\text{Gal}(L/\mathbb{Q}(\omega))$ permute zeros of $f$, but why in this way? Why can't we have $\sigma(\alpha)=\omega^k\sqrt[3]{3}$ and $\sigma(\sqrt[3]{3})=\omega^l\alpha$.
It then concludes that those nine possibilities are all elements of $\text{Gal}(L/\mathbb{Q}(\omega))$ since $[L:\mathbb{Q}(\omega)]=9$. But I thought $[L : \mathbb{Q}]=[L:\mathbb{Q}(\omega)][\mathbb{Q}(\omega):\mathbb{Q}]$. I have previously proven that $[L:\mathbb{Q}]=18$. But then, to get to the 9, we must have $[\mathbb{Q}(\omega):\mathbb{Q}]=2$. But I thought that the minimal polynomial of $\omega$ would be $X^3-1$, because then $\omega^3-1=1-1=0$, which would mean that $[\mathbb{Q}(\omega):\mathbb{Q}]=3\neq 2$.
Comment: $\omega^2+\omega+1=\dfrac{\omega^3-1}{\omega-1}=0$ so indeed $[\mathbb Q(\omega):\mathbb Q]=2$
Comment: It need not be the case that $[\mathbb{Q}(\zeta_n):\mathbb{Q}]=(n-1)$, for instance take $\zeta_4=i$, but $\mathbb{Q}(i):\mathbb{Q}$ has degree 2. It is always the case though that $[\mathbb{Q}(\zeta_p):\mathbb{Q}]=(p-1)$, for *prime p*. In general, the minimal polynomial of $\zeta_n$ has degree φ(n).
Comment: If $\zeta^n=1$ and $\zeta\ne1$ then $\dfrac{\zeta^n-1}{\zeta-1}=\zeta^{n-1}+...\zeta^2+\zeta+1=0$
Comment: If $\alpha$ is a root of $X^6+3X^3+3=0$ then $\alpha \mapsto \sqrt[3]{3}$ is not an automorphism because  $ \sqrt[3]{3}^6+3  \sqrt[3]{3}^3+3\ne0;$ $ \sqrt[3]{3}$ is not a zero of $X^6+3X^3+3$
Comment: @J.W.Tanner Does this type of equation extend to other roots of unity?
Comment: @J.W.Tanner O wow, that clears up a lot for me. So elements of $\mathbb{Q}(\omega)$ are mapped to itself. Roots are permuted, and other elements can do what they want as long as they go by the rules of automorphisms, e.g. $\sigma(a^2)=\sigma(a)\sigma(a)$?
Answer: If $\alpha$ is a root of $X^6+3X^3+3$, then so are $\omega\alpha, \omega^2\alpha , \sqrt[3]3/\alpha, \omega\sqrt[3]3/\alpha, $ and $\omega^2\sqrt[3]3/\alpha,$ where $\omega^3=1$ but $\omega\ne1$, i.e., $\dfrac{\omega^3-1}{\omega-1}=\omega^2+\omega+1=0.\;$  ($\omega$ is a primitive cube root of unity.)
The map you suggested, which takes $\alpha$ to $\sqrt[3]3$, is not an automorphism,
because $\alpha$ is a root of $X^6+3X^3+3$, but $\sqrt[3]3$ is not.
Finally, as indicated, the minimal polynomial for $\omega$ is a quadratic, so indeed $[\mathbb Q(\omega):\mathbb Q]=2$.
Comment: Hmm I see. But I have difficulty confirming automorphisms. When we have $L/\mathbb{Q}$ a splitting field of $X^3-2$, my book says that there is an automorphism that maps $\omega=e^{2\pi i/3}$ to $\omega^2$. But that is not a ring homomorphism under addition right? Since $\sigma(\omega+\omega)=4\omega^2$, but $\sigma(\omega)+\sigma(\omega)=2\omega^2$.
Comment: Automorphism that maps $w$ to $w^2$ maps ($2$ to $2$ and) $2w$ to $2w^2$


arclength of vector r

Question: $$r(t) = \langle 2t, t^2, \ln t \rangle.$$
I know that to find arclength you do
$$L = \int_a^b \|r'(t)\| ~dt.$$
I found $r'(t)$ to be $r'(t) = \left\langle 2, 2t, \dfrac{1}{t} \right\rangle$.
To find $\|r'(t)\|$ I did
$$\sqrt{(2)^2 + (2t)^2 + \dfrac{1}{t^2}}$$
but how do I integrate that?
Comment: Isn't the term that you want to integrate just $|2t+t^{-1}|$?  And the fact that $\ln t$ is defined means that $t$ must be positive; so you can lose the $| |$ signs.
Comment: I'm not sure what you mean.
Comment: oh! my bad. I fixed it now. There was a typo in the question: there were 3 components.
Comment: I mean, isn't $\sqrt{4+4t^2+t^{-2}}$ exactly the same thing as $|2t+t^{-1}|$.  Try squaring the latter; you'll see.
Comment: $r'(t)$ should be $\left\langle 2, 2t, \dfrac{1}{t} \right\rangle$
Comment: yeah. Typo again sorry
Answer: As you have shown,
$$\|r'(t)\|=\sqrt{4t^2+4+\frac{1}{t^2}}
=\sqrt{\left(2t+\frac{1}{t}\right)^2}=2t+\frac{1}{t}.$$
Therefore, the arclength is given by
$$L=\int_a^b \|r'(t)\| ~dt=\int_a^b\left(2t+\frac{1}{t}\right)dt
=(t^2+\log t)\Big|_a^b=b^2-a^2+\log b-\log a.$$
Comment: You should mention that you can drop the absolute value because $t$ has to be positive.
Comment: @JavierBadia: Oh yes, I should mention that. Thanks for pointing it out.

arclength of vector r


UWP border wont use maximum space

Question: Here I am again...
I have a ListView which loads items and prints them in the screen.
Everything is fine except I can't really make the XAML to work as I want it to.
The ListView outputs the content according to the DataTemplate which is supposed to output a "chat-like" display.
<code>    <DataTemplate x:Key="MessageListDataTemplate" x:DataType="disc:IMessage">
        <Border Background="#2C2F33" BorderThickness="0,1,0,1" BorderBrush="Transparent" CornerRadius="5">
            <StackPanel>
                <StackPanel Orientation="Horizontal" Margin="5,2,0,0">
                    <TextBlock TextAlignment="Left" Text="{x:Bind Author,Mode=OneWay}" Foreground="White" FontSize="14"/>
                    <TextBlock TextAlignment="Left" Margin="5,3,0,0" Text="{x:Bind Timestamp,Mode=OneWay,Converter={StaticResource TimeToStringConverter}}" Foreground="LightGray" FontSize="10"/>
                </StackPanel>
                <TextBlock TextAlignment="Left" Margin="10,2,0,0" TextWrapping="WrapWholeWords" Text="{x:Bind Content, Mode=OneWay}" Foreground="#99AAB5" FontSize="20" />
            </StackPanel>
        </Border>
    </DataTemplate>
</code>
The code is functional and it outputs this:

Instead of having the board to be sized according to the size of the message I would like it to be equal to the size of the screen. I have tried everything I know. Thank you!
Answer: Try adding the following style for the ListView:
<code><ListView.ItemContainerStyle>
   <Style TargetType="ListViewItem">
       <Setter Property="HorizontalContentAlignment" Value="Stretch" />
   </Style>
</ListView.ItemContainerStyle>
</code>
Comment: Thank you very much, something I didn't though of. Was that possible to be set in the DataTemplate ? Why couldn't I go to the border and set horizontal alligment to stretch ? Thanks again!
Comment: @KonKarapas DataTemplate is for the element represents the data item. While it is wrapped by an element called ListViewItem which could be styled through ItemContainerStyle. The default value of the HorizontalContentAlignment of a ListViewItem is Left. So the problem is about the ListViewItem, not something else. You can view the visual tree by debugging your app for more detail.

UWP border wont use maximum space


Is there a name for this kind of guitar chord - not open, no barre, strings dampened?

Question: It's so convenient to say "open chord..."

or "barre chord..."

but then there are chords like these...

...where they are not open, not barred, and importantly require dampening of some of the strings.
Technique-wise they feel like a distinct category of chord fingering.
Is there a common name for this type?
I want to tell my son: "practice your ______ chords!"
"Jazz" chords seems vague, and "not-open-non-barre-muted-seventh-chords" doesn't roll off the tongue!
Comment: Since with chords with open strings are _open_ chords, I generally see these chords without open strings as _closed_ chords.
Comment: Not an answer, so a comment: I usually refer to them as "movable" chords. I know this might seem incredibly simple, but in fact it sums them up quite well. In the end, these are shapes that can be transposed, but without having to use a barre... BTW, that's just what I call them; I'm interested to see what others think, and if someone can suggest a generally recognised term.
Comment: @DaveJacoby - that would include all barre chords as well. Not what's in question. Since all the chords mentioned have already been chritened, I suggest '*other shapes*'.
Comment: @BobBroadley - the essence of all barre chord shapes is they're 'movable' - and most guitarists see them as such. So that category would include them along with the OP's shapes. '*Other shapes*' would do.
Comment: Yes, of course that's right, barre chords and these other chords are all movable. So I tell pupils that movable chords can be either barred or non-barred. But then, the movable aspect of barre chords is implicit, so I describe the other ones as movable. Maybe I should talk about "non-barred-movable-chords". Arrrrrrgh!
Comment: 'Twould appear that the best answer to this question is - no.
Answer: Howard Wright categorizes the shapes as "other moveable" chord shapes
http://hakwright.co.uk/guitarchords/index.html
http://hakwright.co.uk/guitarchords/explain.html#order
That's one of three categories:

(1) Barre shapes
(2) Other moveable shapes
(3) Open string shapes

Without listing all three categories I would call them non-barre moveable shapes. "Practice your non-barre moveable chords!"

Before this question I had never heard a clearly distinguished name for those kinds of chord voicings or grips. But then again, I hadn't searched for one either.
Here's a really beautiful A7/C# voicing

In my mind I actually see that as a variation or modification of the regular A shape.

But since there's no "bar", I wouldn't label it as a barre. So let it be "other moveable shape" or "non-barre moveable".
Fun fact: that A7/C# chord "X4X253" doesn't seem to be found in Howard Wright's chord shape catalog, but it is the name of a sneaker by Emporio Armani. Maybe Howard Wright didn't want names of shoes in his library.
Answer: How about: "chords that won't make you a rich guitar player"???
All joking aside, I would and do call these jazz chords. I know they are not exclusive to jazz but then again cowboy chords are not exclusive to country music. The fact is jazz (in its all encompassing form, swing, big band, Dixieland, bop, etc.) is where these types of chords are used the most by far. When you hear them in pop or other styles it is usually because they are going for a "jazzy" sound or vibe.
A name isn't always a definition. Michael, you say "jazz chord" is vague. Maybe so but these types of chords and voicings are primarily used in jazz and they have a very specific makeup for the most part, 3rds, 7ths and upper tensions are favored, roots are sometimes omitted, P5ths and doubled notes are used sparingly and there are usually not more than 4 or 5 notes in a chord.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/117878/discussion-on-answer-by-john-belzaguy-is-there-a-name-for-this-kind-of-guitar-ch).
Answer: It is referred to as an open form chord and all 5 open chords, C, A, G, E, and D, form the "CAGED" system.  So you can call this the G-shape, just as you referred to the bar chord as an E-shape.  In fact you can move the open form G chord up to other positions by barring with your index finger and using fingers 3, 2, and 4 to get the other notes.
The other chords you have listed are not specifically "jazz" chords as they appear in all forms of music.  The ones that have a large interval on the bottom are sometimes call "fat" chords and are common in Big Band.  We sometimes refer to the voicing as "open" because the lower notes are far apart, usually a 6th or 7th, whereas other chord forms that have 3rds in the bass might be called "closed" form, due to the small or compressed intervals.
Quite frankly I don't think it's fair to box them up in neat categories (pun intended) as you will always find outliers, and it doesn't really help to practice only open chords today then closed chords next week.  The beauty of these forms is that many of them have a common three note shape in them allowing one to move through large jumps like a 5th, e.g. I7-->V7, etc, while keeping a large portion of the shape in tact and this creates small intervalic movement in the upper voice harmony.  So it helps more to see how many chords in a given key or progression can be fingered with some common subgroup of notes and practice moving these around.  There are some good exercise book for Jazz-Blues guitar chord progressions that emphasize this point.
Comment: I googled for "open form chord" and the search returned a grand total of three (3) pages from the whole of Internet. "Open form chords", in plural, gives 238 pages. I'm not entirely convinced that it's an actually used term. I'm not saying it's impossible though.
Comment: I'll look at my old guitar chord book collection when I get time.  Maybe I substituted another term with open.
Comment: I don't understand your first paragraph. "It's referred to as an open form chord...you can call this the G-shape." So, `3x343x` would be an open form G-shape, is that what you meant?
Comment: The "open" refers to the natural chord shapes (whatever they are) in the open position which refers to those keys and chord forms that allow opens strings to be used.  This is a common term.  So, YES, and open G-shape.  I don't know why it's causing so much confusion.  The open positions chord forms are NOT movable with standard open position fingering.  Altered fingering makes them moveable, but standard open position forms are not.  Similarly for scales in the open position.
Comment: But also, there is a concept of open voicing in harmony which I also mentioned for completeness.


Ηow can I replicate the sound οf this instrument?

Question: If you go ahead and watch this video, the guy with the drums has a percussion instrument with his right hand that produces the shaky sound, kind of like the maracas.
What is it called?

Is it possible for me to produce the same sound with my maracas? I'm not sure if I'm just not skilled enough with the maracas or I need to buy a separate instrument for that.
Comment: @BenMiller I disagree - at least where I'm from, 'rainstick' refers to a much longer instrument, where the beans aren't 'shook' but allowed to fall through the gaps inside the tube - playing in a different way, and creating a totally different sound. [Youtube Example](http://youtu.be/riQNqpwXkvE)
Comment: That looks like a [rainstick](http://en.m.wikipedia.org/wiki/Rainstick), which is one type of [shaker](http://en.m.wikipedia.org/wiki/Shaker_(instrument)).
Comment: @Chris I've seen short rainsticks played this way, but you are probably right that it is a simpler shaker that does not have the rainstick pegs inside.
Comment: I've asked [a meta question](http://meta.music.stackexchange.com/q/981/6851) about whether or not this question is on-topic.
Comment: @ben: it is on topic.
Answer: This instrument is specifically a ganzá [gahn-ZAH], a kind of shaker of African origins and very common in Brazil. It is fairly inexpensive and can be easily found at music instrument stores around the world.
You can ghetto-replicate its sound by putting some small pebbles or large-grained sand into any Aluminium canister (cocktail shakers make for a very nice visual and sounding effect!).
Answer: This is generally just called a 'shaker'.
In terms of creating the same sound with maracas: the sounds are pretty close anyway! Try holding the maracas the wrong way up (with your hand around the bulb), which will dampen the sound a little, and sound closer to the shaker in this video. Doing this will create basically the same thing as an egg shaker, which are often used interchangably with the cylindrical ones, such as in this video.
Failing that, they're not expensive, you can pick them up for a few quid - or make you're own if you're feeling adventurous!


Derivative and Integral of inverse of $x^x$

Question: If $x^x = a$ then define $f(a) = x$.$f$ is the inverse of $x^x$. What is then f? And what is the derivative and antiderivative of f? What is the derivation for the answer?
Comment: One rewrite it as $(\ln x)e^{\ln x}=\ln a$ ($a>0$) then use Lambert's function.
Comment: You can search for Lambert function
Comment: See for example [here](http://www.wolframalpha.com/input/?i=Inverse+function+of+x%5Ex).
Answer: The solution is given on the Wikipedia of the Lambert W function, which states that
$$x^x=a\implies x=\frac{\ln a}{W(\ln a)}=e^{W(\ln a)}$$
where $W(x)$ is the Lambert W function.

If you wish to take the derivative of $f(x)$, use the inverse function derivative rule:
$$f'(x)=\frac1{g'(f(x))}$$
where $g(x)$ is the inverse of $f(x)$.  Thus,
$$g'(x)=g(x)(1+\ln x)\implies g'(f(x))=x\left(1+\ln\left(e^{W(\ln x)}\right)\right)=x(1+W(\ln x))$$
the $x$ in front is due to $f$ and $g$ being inverses.
$$f'(x)=\frac1{x(1+W(\ln x))}$$

To take the antiderivative, use the antiderivative of the inverse function formula.
$$\int f(x)\ dx=xf(x)-G(f(x))+c$$
where $G$ is the antiderivative of $g=x^x$.  Unfortunately, there is no closed form for $G$.  However, some information as to a series expansion and such is found in this question.
Comment: And that's about all you can do. Nice answer.


Make request just after the initialization using Spring Boot

Question: I have two http services. First one is online and it can get request SEND_DATA and than it sends data to second one using post request SAVE_DATA. I want to make second service when it starts to be able to make request SEND_DATA to first one and than get it by request SAVE_DATA. The problem is, if I send request from second one in autowired, first gets this request and sends it to second, but the second isn't fully initialized by that time and it can't get this request. What is the best solution to this?
first
<code>@GetMapping(value = SEND_DATA)
public ResponseEntity<String> sendData() {
    ...
    postRequest(SAVE_DATA)
    ...
}
</code>
second
<code>@Autowired
public Second() {
    ...
    getRequest(SEND_DATA)
    ...
}

@PostMapping(value = SAVE_DATA, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> saveData(@RequestBody String value) {
     save(value)
}
</code>
Answer: Use <code>@PostConstruct</code>:
<code>@Service
public class MyService {

    @Autowired
    private OtherService otherService;

    @PostConstruct
    private void postConstruct() {
        otherService.doSomething();
    }
</code>
The method, which must be void but can have any visibility, is called after this bean is initialized, and that means of course that the injected bean is initialized too.
Answer: If you have a distributed system, you cannot rely on internal communication between 2 beans(services). I suggest you having code to check availability before calling.
<code>@Service
public class FirstService {

   private AtomicBoolean isSecondServiceOk;

   @Scheduled(fixedDelay = 1_000L)
   void checkingSecondServiceAvailability(){
       ... check response from SecondService if it respond,
                           isSecondServiceOk.set(true)
   }

   ... check isSecondServiceOk available before calling SecondService

}
</code>


Ruby: Map process arugments to hashmap

Question: I have a tricky problem. I try to map some process arguments to a hash map in Ruby. I want to compare process configurations from parameters (first example) and config files (such as json - from the second example).
I have something like this:
<code>/usr/bin/dockerd-current \
--add-runtime docker-runc=/usr/libexec/docker/docker-runc-current \
--seccomp-profile=/etc/docker/seccomp.json \
--selinux-enabled \
--storage-driver overlay2
</code>
And I would like to have a hashmap like:
<code>{
  'add-runtime' => {
     'docker-runc' => '/usr/libexec/docker/docker-runc-current'
  },
  'seccomp-profile' => '/etc/docker/seccomp.json',
  'selinux-enabled' => '',
  'storage-driver' => 'overlay2'
 }
</code>
EDIT:
I made a script that generically maps the parameters into a hashmap. The problem is, that this script is not able to detect and map nested elements properly. Here is what I have:
<code>params = "/usr/bin/dockerd-current     --add-runtime    docker-runc=/usr/libexec/docker/docker-runc-current --default-runtime=docker-runc --exec-opt native.cgroupdriver=systemd --userland-proxy-path=/usr/libexec/docker/docker-proxy-current --init-path=/usr/libexec/docker/docker-init-current --seccomp-profile=/etc/docker/seccomp.json --selinux-enabled --log-driver=journald --signature-verification=false --storage-driver overlay2"

args = params.split("--")

# Remove process binary from args.
args.shift

# Remove multiple whitespaces and replace equals sign with single whitespace.
args.map! { |item| item.split.join(" ") }
args.map! { |item| item=item.gsub('=',' ') }

# Single word params implicit boolean flags with value true
# Adding true here.
args.map! do |item|
  if item.split(" ").size == 1
    item+" true"
  else
    item
  end
end

# Map results to hashmap.
# TODO: substructures are not mapped properly...
args.map! do |x|
  s = x.split(" ", 2)
  [s[0], s[1]]
end

puts args.to_h
</code>
I'm glad for any kind of help.
Thanks a lot!
Comment: That second part isn't valid Ruby code. What is your intent here? If each argument was either a string, an array or a hash that could work: `{ 'add-runtime' => { 'docker-runc' => '/usr/libexec...' }, ... }`
Comment: Hint: The best way to parse command-line arguments is with a command-line parser and *not* a regular expression. The syntax is often subtly complex. For example, Ruby has a [robust parser](https://docs.ruby-lang.org/en/2.5.0/OptionParser.html) built-in. There will also be a level of shell parsing on top of that to tease out individual arguments that's complicated by the fact that things can be quoted, escaped, or both.
Comment: Thanks for your feedback. I did not specify the question good enough. I want to compare configurations - either from process args or from config maps. My goal is to bring both in a hashmap-form to compare (or even merge) them.
Comment: It looks a lot better now as that's a Ruby structure we can actually help you generate.
Answer: As suggested in the comments, https://docs.ruby-lang.org/en/2.1.0/OptionParser.html is the way to go.
Build up your options hash then diff them with active support if you have it (http://api.rubyonrails.org/v2.3/classes/ActiveSupport/CoreExtensions/Hash/Diff.html), or the hashdiff gem if you can. If all else fails, you can check the keys of the left compared to the right, then vice versa.
Comment: So with the optionParser I would have to declaire all flags by myself, right? I was acutally looking for a more generic approach...

Ruby: Map process arugments to hashmap


Memory leak when using std::shared_ptr to std::vector

Question: I have an Image class :
class Image{

   public:

    Image()
    {
      vector_ptr = std::make_shared<std::vector<Feature>>(feature_vector);
    }

    std::shared_ptr<std::vector<Feature>> calculate_vector()
    {
      // iterates over a space of possible features, calling
      // vector_ptr->push_back(Feature(type, i, j, w, h, value))

      return vector_ptr;
    }

    std::shared_ptr<std::vector<Feature>> get_vector()
    {
      return vector_ptr;
    }

    void clear_vector()
    {
      vector_ptr->clear();
    }

  private:
    std::vector<Feature> feature_vector;
    std::shared_ptr<std::vector<Feature>> vector_ptr;
};

Where Feature is given by :
struct Feature
{
    Feature(int type, int i, int j, int w, int h, double value);
    void print();

    int type;

    int i, j;
    int w, h;

    double value;
};

But after successively calling calculate_vector(), and then clear_vector(), htop indicates there is a memory leak.
How do I resolve this problem?  (The feature vector is very large)
Answer: vector_ptr is a copy of feature_vector, it isn't a shared wrapper around it. So you'd need to call feature_vector.clear(); as well if you wanted to free up its memory.
Comment: So, make_shared creates a copy of the object given to it?
Comment: then, the feature_vector is redundant if I only manipulate the vector_ptr within the class?
Comment: @Kalessar: make_shared creates a new object. As it is it's calling the vector copy constructor. You should be able to use `std::move` to invoke the move constructor. But yes, from the code above it appears that `feature_vector` is redundant.


firing RadioButton checked event in ListView.View Gridview

Question: I have a ListView using a GridView as it's view and each item in the list has a DataTemplate with a RadioButton.  I'm trying to figure out how to have the first (or any) RadioButton be checked and actually fire the Checked event.  Here is my xaml:

                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Selected">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <RadioButton    Name="selectedFoo"
                                                    Checked="selectedRadio_Checked"
                                                    IsChecked="True"

                                                    Tag="{Binding Id}"/>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
                        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
                    </GridView>
                </ListView.View>
            </ListView>

Answer: I ended up attaching a handler to the radio buttons loaded event and calling it's Checked handler.  Not the best solution but it works for me.
Answer: private void RadioListBox_SelectionChanged(object sender, RoutedEventArgs e)
{
    var button = sender as RadioButton;
    MessageBox.Show(button.Tag.ToString());
}

<ListView Margin="18,32,20,45" Name="lstVW" ItemsSource="{Binding}">
    <ListView.View>
        <GridView>
             <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" Width="50"/>
             <GridViewColumn Header="Drug Generic Name" DisplayMemberBinding="{Binding Name}" Width="700"/>
             <GridViewColumn Header="Status" DisplayMemberBinding="{Binding Status}" Width="100"/>
             <GridViewColumn Header="Status">
                 <GridViewColumn.CellTemplate>
                      <DataTemplate>
                           <StackPanel>
                                <RadioButton x:Name="rad" GroupName="optionsStatus" IsChecked="False" Tag="{Binding Id}" Background="WhiteSmoke" Height="30"  Click="RadioListBox_SelectionChanged"/>
                           </StackPanel>
                      </DataTemplate>
                 </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>


Drupal security ACL

Question: I have a client having website in Drupal . He need to create user and want to assign rights for edit and delete on every column displayed in webpage. I have tried ACL but that didn't work, so Iam planing to have my own code and tables in DB to save table and column permission for each user. But my senior told me that this is security compromise and advise me to use ACL.
What is security risk and what issues can be raised in future if I use my own code and tables to do the job? Plz help me understand this .
Also recommend me how to use ACL or some other work for this scenario....
Answer: You should use a specific ACL module for Drupal, such as Content Access.
The ACL module does nothing on its own:

The ACL module, short for Access Control Lists, is an API for other modules to create lists of users and give them access to nodes. It has no UI of its own and will not do anything by itself; install this module only if some other module tells you to.

Here are basic instructions for setting up the permissions, content types and content access:

Install Content Access module. Note: you will be asked to rebuild the content access permissions. If you have a lot of content on your site, this action may take a while.
Create necessary user roles at Admin -> People -> Permissions -> Roles
Create necessary content types.
Go to: Admin -> Structure -> Content types -> Edit [Your content type] -> Access Control tab
You can there setup specific permissions for viewing, editing or deleting nodes according to the group a user belongs to.

To elaborate more the security risks in handling permissions manually: your senior is right - it is always better to have a centralized system which will manage access control on a website. This way maintenance is easier and you do not need to predict all possible outcomes in order to prevent access to sensitive data at all places.
At some points in custom implementation you might reinvent the wheel, which is completely unnecessary, especially if you can already use an existing framework for setting up those rules.
Imagine the following situations: you blocked direct access to particular nodes using a custom module. What happens if a user goes to /node page and your node is listed there? RSS feed page? What happens on category pages? What happens if you use a contributed module which shows nodes and might possibly expose your sensitive data? What if the modules are updated with a security bugfix and you need to update all your code?
If you are writing those rules manually, you would need to write a solution for all possibilities and still you/someone else be able to maintain that.
Not all problems will be solved by using centralized system, but the risk is significantly reduced; all third party modules are made according to that system. You can call it a convention.

By saying that you want them to be able to edit a column I guess that you are speaking about nodes. If this is not what you mean, elaborate your question a bit more.
Answer: Not totally sure what you mean by columns either, but if you are referring to fields on an entity, you can use Field Permissions (https://www.drupal.org/project/field_permissions).

Drupal security ACL


What's the safest way to define short function name aliases in C++?

Question: Suppose I have a class Utility in a file utility.h:
class Utility {
public:
    static double longDescriptiveName(double x) { return x + 42; }
};

And then I find that I use the function longDescriptiveName(...) a LOT. So like an irresponsible C++ programmer that I am when I've had too much coffee, I create a new file utilitymacros.h and add the following there:
#define ldn Utility::longDescriptiveName

Now I include "utilitymacros.h" in any *.cpp where I use ldn(...) and my heart is filled with joy over how much more convinient it is to type 3 letters vs 28.
Question: Is there a safer (more proper) way of doing this than with #define?
I've noticed that I have to include "utilitymacros.h" after including boost headers, which I obviously don't like because it's a sign of clashes (though the Boost errors I get are not very clear as to what the clash is).
Clarification 1: On Code Readability
In case you might say that this negatively affects code readability, I assure you it does not, because it's a small set of functions that are used A LOT. An example that is widely know is stoi for stringToInteger. Another is pdf for probabilityDensityFunction, etc. So if I want to do the following, stoi is more readable in my opinion:
int x = stoi(a) + stoi(b) + stoi(c) + stoi(d);

Than:
int x = Utility::stringToInteger(a) + Utility::stringToInteger(b)
        + Utility::stringToInteger(c) + Utility::stringToInteger(d);

Or:
int x = Utility::stringToInteger(a);
x += Utility::stringToInteger(b);
x += Utility::stringToInteger(c);
x += Utility::stringToInteger(d);

Clarification 2: Editor Macro
I use Emacs as my IDE of choice and a Kinesis keyboard so you KNOW I use a ton of keyboard macros, custom keyboard shortcuts, as well as actually modifying what I see in the editor vs what's actually stored in the h/cpp file. But still, I feel like the simplicity and visual readability (as argued above) of using a function abbreviation in a few select cases really is the result I'm looking for (this is certainly subject to a degree).
Comment: I don't really think this is a good idea, since it harms code readability.
Comment: I would assume that `pdf` was a file format, and be *really* confused. Characters are free and you don't save the environment by not using them.
Comment: Well, maybe short names are readable for YOU, but it's hard for others, even (or especially) when they are used everywhere. On my old there were alot of 3 character function names and it was one of many reasons why I quit there: The code was an unreadable mess. Sure, not only because of the function and variable names, but it was a part of it.
Answer: Instead of macro, you could write inline function that forwards the call to the actual function:
inline double ldn(double x)
{
   return Utility::longDescriptiveName(x);
}

That is certainly safer than macro.
Comment: +1 definitely inline functions are safer as there type checking and i think it is recommended to be used (C++ style) instead of #define (C style and less safe). Aside note: unlike Macros inline lacks using any data type which is accomplished by using templates with inline !
Comment: @Nawaz, I'm assuming that the inline function is not part of class `Utility`, correct? In that case, would you suggest to put the inline definition in the same header as `utility.h` or create a separate header for them like `utilityhelpers.h`?
Comment: @LexFridman: Yes. It is outside the class `Utility`. You can put it in the same header, but outside the class. It depends on you.
Answer: You could use a function reference:
double (&ldn)(double) = Utility::longDescriptiveName;

Comment: In C++11, `auto &&ldn = Utility::longDescriptiveName;` which is very idiomatic. What's the advantage of `static` in any case?
Comment: Using a function reference may have an impact on the ability of the function calls to be inlined.
Comment: @Potatoswatter: It is in a header file; `static` is used to avoid multiple-definition error.
Comment: Should not it be `static double (&ldn)(double) = ...`?
Comment: @Nawaz `static` is used to define multiple different objects with the same name. It might be better to use `extern`. Anyway, an unnamed namespace is generally preferred.
Comment: @Potatoswatter: `static` would work as fine; doesn't matter if it defines multiple because its not modifying it.
Comment: @jogojapan: I was thinking the same, but I'm not sure.
Answer: How about configuring a snippit/macro/similar thing in your text editor?  This way you only have to type ldn or something like that and the code doesn't have to run through the preprocessor risking difficult to find bugs later.
Comment: Plus, it will be comprehensible after being typed out.
Answer: I don't know if this helps, but I think part of the problem may be the use of overly general namespaces (or class names, in this case), such as Utility.
If instead of Utility::stringToInteger, we had
namespace utility {
  namespace type_conversion {
    namespace string {
      int to_int(const std::string &s);
    }
  }
}

Then the function could locally be used like this:
void local_function()
{
  using namespace utility::type_conversion::string;

  int sum = to_int(a) + to_int(b) + to_int(c) + to_int(d);
}

Analogously, if classes/structs and static functions are used (and there can be good reasons for this), we have something like
strut utility {
  struct type_conversion {
    struct string {
      static int to_int(const std::string &s);
    };
  };
};

and the local function would look something like this:
void local_function()
{
  typedef utility::type_conversion::string str;

  int sum = str::to_int(a) + str::to_int(b)
              + str::to_int(c) + str::to_int(d);
}

I realize I am not telling you anything about syntax you didn't know already; it's more a reminder of the fact that the organization and structure of namespaces and classes itself plays an important role in making code more readable (and writable).
Answer: One alternative is to rename your function and put it in a namespace instead of a class, since it is static anyway. utility.h becomes
namespace Utility {
    // long descriptive comment
    inline double ldn(double x) { return x + 42; }
}

Then you can put using namespace Utility; in your client code.
I know there are lots of style guides out there saying short names are a bad thing, but I don't see the point of obeying some style and then circumventing it.
Answer: You can use alias template (since C++11).
  using shortName = my::complicate::function::name;

Comment: can just use class name, but not function name


Views exposed filter error "An illegal choice has been detected. Please contact the site administrator."

Question: I am having a very odd problem with an exposed filter in one of my Views. The page I am talking about is here: http://epsindustry.org/eps-packaging-map2
When I select one of the last 2 options in the menu (EPS Packaging Recyclers or Loose Fill Recycling Drop-off) I get an error that says An illegal choice has been detected. Please contact the site administrator. This is really weird to me because it only happens with these 2 options. I don't believe they are set up any differently than the other taxonomy terms. There's nothing all that special about them, its just a term that the admin selects when creating a location for the map.
Any ideas as to why this is happening or how to fix it?
Comment: You can apply this patch, It will be resolve your problem.
https://www.drupal.org/files/views_fix-illegal-choice-exposed-group-filters_1177882-64.patch
Answer: I was having the same issue. In my case the 'illegal choice' message was displayed when changing the country from 'United States' (the default value) to 'United Kingdom' and selecting 'North Yorkshire' as state/province and saving.
I did the following to fix it:

Go to the Configure page of the Location field (by editing the node type and going to 'Manage fields').
In the 'Events settings' section (not the 'Locative information' section), there is a drop down group called 'Default value'. I set 'Country' to United Kingdom.
Save field settings.
Done.

Using:

Drupal 6.28
MySQL 5.1.72
PHP 220.127.116.11+squeeze17
Location: 6.x-3.3-rc3+6-dev (2013-Oct-25)
GMap Location: 6.x-2.0-beta5+1-dev (2013-Sep-30)

Hope it helps.
Answer: I also faced the same problem i used query alter
I have used node reference as my select field. you can dynamically chance and set the value for select list
STEP 1: uncheck select all option and select any one item in the drop down.
Step 2: alter your value based on what page you are in with use of arg() values.
We used to change the select based in the node id for every node we select one option dynamically.
Below is the sample code we used to alter
function modulename_views_query_alter(&$view, &$query) {
    if($view->name == "view_name"){
          if($view->current_display == "block_name"){
        $query -> where[4]['conditions'][1]= array('field' => 'field_data_field_field_name.field_selectlist_id', 'value' => $passthevaluetobesent, 'operator' => '=');
            }
    }
}

alter the condition class in query alter according to your need dynamically
hope it will be helpful dude.
Answer: This can also be caused by a reference to an entity that is set to Unpublished. If you reference an entity and want the options to be visible to Anonymous users the entity will need to be published.
Answer: Generally this issue is coming when the exposed form is getting undefined value, if you limit the items to the selected list it will not be taken any other undefined values.
So go to the corresponding filter criteria field and if you check the exposed checkbox you can there is a checkbox "Limit list to selected items". Now check it and save the view.
Thats all.


UART Raspberry pi Windows IoT Core Arduino

Question: UART data transmission Raspberry pi UART (RX TX) Arduino
I know should avoid async void. They are only used for event handling. For other methods return Task. async and await
Where can there be a mistake? Why the data does not come?
Who knows the link where it is shown how to receive data on the UART?
<code>using Windows.Storage.Streams;
using Windows.Devices.Enumeration;
using Windows.Devices.SerialCommunication;

public async void Serial()
{
string aqs = SerialDevice.GetDeviceSelector("UART0");                   /* Find the selector string for the serial device   */
var dis = await DeviceInformation.FindAllAsync(aqs);                    /* Find the serial device with our selector string  */
SerialDevice SerialPort = await SerialDevice.FromIdAsync(dis[0].Id);    /* Create an serial device with our selected device */

/* Configure serial settings */
SerialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
SerialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
SerialPort.BaudRate = 9600;                                             /* mini UART: only standard baudrates */
SerialPort.Parity = SerialParity.None;                                  /* mini UART: no parities */
SerialPort.StopBits = SerialStopBitCount.One;                           /* mini UART: 1 stop bit */
SerialPort.DataBits = 8;

/* Write a string out over serial */
string txBuffer = "Hello Serial";
DataWriter dataWriter = new DataWriter();
dataWriter.WriteString(txBuffer);
uint bytesWritten = await SerialPort.OutputStream.WriteAsync(dataWriter.DetachBuffer());

/* Read data in from the serial port */
const uint maxReadLength = 1024;
DataReader dataReader = new DataReader(SerialPort.InputStream);
uint bytesToRead = await dataReader.LoadAsync(maxReadLength);
string rxBuffer = dataReader.ReadString(bytesToRead);
</code>
}
Comment: Yes, https://learn.microsoft.com/en-us/windows/iot-core/learn-about-hardware/pinmappings/pinmappingsrpi
Comment: read carefully the headlines, then minus :)
Comment: A similar answer is here http://www.iot-developer.net/windows-iot/uwp-programming-in-c/uart-serial-port/rpi-using-the-uart
Comment: oh.. You using `Winodws IOT Core`.. I thought trying to develop app in windows to read data from serial port which connected to `R-PI`
Comment: @SergeyKuntsevich, did you cross over RxTx wires connected with the other serial port end?
Comment: Michael Xu - MSFT  Of course, I accept data, but only once) By this code:   https://learn.microsoft.com/en-us/windows/iot-core/learn-about-hardware/pinmappings/pinmappingsrpi
Comment: @SergeyKuntsevich, if possible  please connect the device to your computer via any terminal to verify that the serial port on that device works as expected.
Comment: Майкл Сюй - MSFT, The code is working, I wrote it from below. When checking, I did not correctly send data from the Arduino Serial3.println ("String"); Thank you.
Answer: Working code for communication UART (RX TX) arduino and Raspberry pi
It works through a voltage converter 5V -> 3.3V. RX TX do not forget to swap.
<code>    public sealed partial class MainPage : Page
{
    private SerialDevice SerialPort;
    private DataWriter dataWriter;
    private DataReader dataReader;
    string rxBuffer;
    CancellationTokenSource ReadCancellationTokenSource = new CancellationTokenSource();

    public MainPage()
    {
        this.InitializeComponent();
        InitSerial();
    }

    private async void InitSerial()
    {
        string aqs = SerialDevice.GetDeviceSelector("UART0");
        var dis = await DeviceInformation.FindAllAsync(aqs);
        SerialPort = await SerialDevice.FromIdAsync(dis[0].Id);
        SerialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
        SerialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
        SerialPort.BaudRate = 9600;
        SerialPort.Parity = SerialParity.None;
        SerialPort.StopBits = SerialStopBitCount.One;
        SerialPort.DataBits = 8;

        dataWriter = new DataWriter();
        //dataReader = new DataReader(SerialPort.InputStream);
        Listen();
    }

    public async void SerialReceived()
    {
        /* Read data in from the serial port*/
        const uint maxReadLength = 1024;
        dataReader = new DataReader(SerialPort.InputStream);
        uint bytesToRead = await dataReader.LoadAsync(maxReadLength);
        rxBuffer = dataReader.ReadString(bytesToRead);
        receivedData.Text = rxBuffer;
    }

    public async void SerialSend(string txBuffer2)
    {
        /* Write a string out over serial */
        string txBuffer = txBuffer2;
        dataWriter.WriteString(txBuffer);
        uint bytesWritten = await SerialPort.OutputStream.WriteAsync(dataWriter.DetachBuffer());
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        SerialSend("Hello Serial");
    }

    private async void Listen()
    {
        try
        {
            if (SerialPort != null)
            {
                dataReader = new DataReader(SerialPort.InputStream);

                // keep reading the serial input
                while (true)
                {
                    await ReadAsync(ReadCancellationTokenSource.Token);
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Uart Error", ex);
        }
    }

    private async Task ReadAsync(CancellationToken cancellationToken)
    {
        Task<UInt32> loadAsyncTask;
        uint ReadBufferLength = 1024;
        // If task cancellation was requested, comply
        cancellationToken.ThrowIfCancellationRequested();
        // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
        dataReader.InputStreamOptions = InputStreamOptions.Partial;
        // Create a task object to wait for data on the serialPort.InputStream
        loadAsyncTask = dataReader.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
        // Launch the task and wait
        UInt32 bytesRead = await loadAsyncTask;
        if (bytesRead > 0)
        {
            receivedData.Text = dataReader.ReadString(bytesRead);
        }
    }
}
</code>


Egit - commit message shortcut key not working

Question: I've installed Egit on my Eclipse Kepler.
When I press Ctrl+#,the commit message window doesn't open.
I've checked Eclipse, Git - Keyboard Shortcut, How to use?

The keyboard shortcut Ctrl+# only works for me after activating command group in Window > Customize Perspective > Command Groups Availability > Git

But still commit message window isn't opening.
Comment: Cmon, just use right click -> commit, right?
Answer: It's my fault.
3 and # is in same key in keyboard.
Now its working when pressing Ctrl+Shift+3


Is login required is available for class based view in Django?

Question: I cant use the login required in class based view in django rest frame work
How can i authenticate backend in django rest frame work
Answer: Here the doc has specified the method for authentication. https://www.django-rest-framework.org/api-guide/authentication/


Show there is a set $H$ which is the intersection of countable many open sets containing $A$ with $\mu(H \setminus A)=0$

Question: Let $A \subset [0,1]$ be a Lebesgue measurable set and let $\mu$ denote the Lebesgue measure.
I am trying to show that there is a set $H$ which is the intersection of countable many open sets containing $A$ with $\mu(H \setminus A)=0$
This is the proof.

For each $n=1,2,\ldots$ there is an open set $G_n$ containing $A$ such that
  $\mu(G_n \setminus A) < \frac{1}{n}$
This follows from the fact that the Lebesgue outer measure $\mu(A)$ is
  the infimum of $\mu(G)$ over open sets $G$ containing $A$, and from
  measurability of $A$, $\mu(G_n \setminus A) = \mu(G_n)-\mu(A)$.

Why is $\mu(G_n \setminus A) < \frac{1}{n}$? Where does $\frac{1}{n}$
come from? And what is the explanation above trying to say?

Let $H=\bigcap^\infty_{n=1} G_n$. $H$ need not be open but it is the
  intersection of countably many open sets containing $A$ in particular it
  is Borel and Lebesgue measurable.

Why does $H=\bigcap^\infty_{n=1} G_n$? And how do we know it is Borel and Lebesgue measurable?

$\mu(H \setminus A) <\frac{1}{n}$ for every $n$ so $\mu(H \setminus A)=0$

In general what is this proof trying to say?
Answer: It looks as if you're trying to read a proof without knowing the basic definitions and without knowing some basic conventions.
As for "Why does $H=\bigcap^\infty_{n=1} G_n$?", the answer is that they just said "Let $H=\bigcap^\infty_{n=1} G_n$".  That just means they're giving a name to this intersection of sets; they're calling it $H$.
You quoted a definition: Lebesgue outer measure $\mu(A)$ is the infimum of $\mu(G)$ over open sets $G$ containing $A$.  That means $\mu(A)$ is the largest number that does not exceed the measure of any open set $G$ "containing" $A$. To say $G$ "contains" $A$ means that $A\subseteq G$, i.e. every member of $A$ is a member of $G$.  To say that $\mu(A)$ is the largest number not exceeding the measure of any open set $G$ containing $A$ implies that every number larger than $\mu(A)$ does exceed the measure of some open set $G$ containing $A$.  Thus for every number larger than $\mu(A)$ there is an open set $G$ containing $A$ whose measure is less than that number larger than $\mu(A)$.  In particular, if $n\in\{1,2,3,\ldots\}$, then there is an open set $G_n$ containing $A$ whose measure is less than $\mu(A)+\frac 1 n$.  The reason for concerning ourselves with $1/n$ for $n\in\{1,2,3,\ldots\}$ rather than with arbitrary positive numbers is that we want a set of positive numbers that is countably infinite rather than uncountable.  Any for reasons that appear later in the proof, we want a set of such numbers that is bounded below by $0$ but is not bounded below by any positive number.  The set $\{1/1, 1/2, 1/3,\ldots\}$ qualifies.
To understand how we know $H$ is Borel measurable, you need to recall what "Borel measurable" means.  A Borel-measurable set, or "Borel set", is any set that can be made by starting with open sets and applying complementation, countable unions, and countable intersections.  $H$ was defined to be a countable intersection of open sets.
Say the measure of $A$ is $0.8$.  Then the outer measure of $A$ and the inner measure of $A$ are both $0.8$.  That outer measure is $0.8$ means that for every number $0.8+\varepsilon$ bigger than $0.8$, there is some open set containing $A$ whose measure is less than $0.8+\varepsilon$, but there is no open set containing $A$ whose measure is less than $0.8$.  That means in particular

There is some open set $G$ containing $A$ whose measure is less than $0.8+ \dfrac 1 2$; and
There is some open set $G$ containing $A$ whose measure is less than $0.8+ \dfrac 1 3$; and
There is some open set $G$ containing $A$ whose measure is less than $0.8+ \dfrac 1 4$; and
There is some open set $G$ containing $A$ whose measure is less than $0.8+ \dfrac 1 5$;
and so on.

The intersection of all of these must have measure at least $0.8$ since it contains $A$.  But the measure of the intersection must be less than $0.8 + \frac 1 2$, and less than $0.8+\frac13$ and less than $0.8+\frac14$, and so on.  The only number not less than $0.8$ that is less than all of those, is $0.8$.  Hence the measure of the intersection must be $0.8$.  And the intersection is the intersection of countably many open sets.
Answer: Infimum means greatest lower bound. The infimum of a set of real numbers can be approximated arbitrarily closely with elements from that set, in particular, more closely than the reciprocal of arbirarily large natural numbers $n.$
$H$ is defined in that way, it does not appear earlier in the proof. Countable intersections of measurable sets are measurable in any $\sigma$-algebra.
A nonnegative real number that is less than the reciprocal of arbitrarily large natural numbers must be zero.
Answer:
You should think of $\frac1n$ as a "small quantity"; as $n$ increases, $\frac1n$ gets smaller and smaller. So, the first part of the proof is just telling you that your set can be approximated from above in measure with open sets whose measure is closer and closer to the one of $A$ (that is $\mu(G_n\setminus A)<\frac1n$). This is true by the fact that $\mu(A)$ is the infimum of the measures of the open sets containing $A$.
The set $H$ is defined to be the intersection of the $G_n$'s. Why? Because we need it to be such a set. $H$ contains $A$ because every $G_n$ does. By definition, $H$ is a $G_{\delta}$ set, i.e. a countable intersection of open sets. $H$ needs not to be open, but it is a Borel set (as open sets are Borel sets) and hence is Borel measurable. It is automatically Lebesgue measurable, as all Borel measurable set are Lebesgue measurable. Since the intersection os over all $n$, by taking the limit you get that $\mu(H\setminus A)=0$.
The proof is "trying to tell you" that such a set $H$ exists. Indeed, the proof is a construction of such set. Sometimes in measure theory it might be handy to have a Borel set containing your set with the same measure.


Como alocar uma quantidade imensa de memória?

Question: Criei um algoritmo de criptografia OnFly que encripta bytes sem a necessidade de copiar-los para uma nova cópia destes mesmos bytes. Isso é tanto para encriptar e para decriptar estas listas de bytes. Como no esquema abaixo, a mesma cadeia que entra será a mesma que irá ser descriptada, fiz isso pensando no custo de memória que teria ao usar arquivos largos.

Por exemplo, considere o arquivo fileBytes cujo há uma imagem PNG de 4 MB (4.194.304 bytes) armazenados nela. O meu algorítimo aumenta apenas 1 byte do tamanho original, e encripta os demais bytes do arquivo, mantendo seu tamanho e aspecto.
Tanto para descriptografar, é descontado 1 byte neste arquivo.
A minha dúvida é a seguinte, se eu usar um arquivo arbitrariamente grande na criptografia, além de usar um enorme uso de processador a memória do aplicativo será somada junto com o tamanho do arquivo, e se eu usar um arquivo de 10 GB num computador de 4GB de RAM será atirada uma exceção OutOfMemoryException.
Veja no exemplo abaixo como isso iria ocorrer:
// as keys em CRYRAZ também são outras Arrays de bytes.
byte[] key = new byte[] { 12, 51, 63};
// cria uma nova instância de CRYRAZ.
Cryraz clientCriptografia = new Cryraz(key);

// a mensagem que será usada para encriptar
string Mensagem = "Olá, mundo!";
// bytes da mensagem
byte[] Mensagem_bytes = System.Text.Encoding.Default.GetBytes(Mensagem);

// Mensagem_bytes será o nosso alvo. Atualmente ela se encontra decriptada e original, vamos encriptar ela agora.
Cryraz.EncryptData(ref Mensagem_bytes);

// Pronto, Mensagem_bytes está encriptado.

É assim que funciona Cryraz, diferente dos outros métodos de criptografia que você copia os bytes, assim obtendo a versão original e encriptada no mesmo código, diferente do Cryraz, ele encripta diretamente o original.
Esse é o corpo do método para encriptar (cortei partes desnecessárias de verificações e opções de segurança do algoritmo):
public void EncryptData(ref byte[] entryByteData) {
    // ...
    for (int i = 0; i <= entryByteData.Length - 1; i++) {
        // ação recursiva em todos os bytes de entrada
        // é aqui a ação de criptografia
        // no final, o byte é atribuído à array:
        entryByteData[i] = ((byte)a);
        // obs: "a" é o novo byte encriptado
    }
    // aumenta o tamanho original da array para inserir o hash de segurança
    Array.Resize(ref entryByteData, entryByteData.Length + 1);

    // cria o hash de segurança e insere-o na array, sem esse hash, não há
    // descriptografia, é parte do algoritmo
    byte hash_x = performKeyHash(key);
    entryByteData[entryByteData.Length - 1] = hash_x;

    // coleta as variáveis inutilizadas
    GC.Collect();
}

Código completo: https://pastebin.com/wKQn0S5N

Mesmo com o GC.Collect(); no final do método fica uma enorme quantia de memória sendo usada no aplicativo, por causa de ler os bytes dos arquivos que serão usados.

Para o algoritmo funcionar, é necessário saber o índice do byte em relação à array que está sendo criptografado e ter o tamanho exato da entrada e da saída.

Em suma, como faço para que o aplicativo consiga "cachear" todos os bytes de um arquivo muito grande sem que haja problemas com memória? Existe uma maneira para "driblar" isso?
Answer: Óbviamente voce está proibido de ler o seu ficheiro inteiro duma só vez. A única alternativa que lhe resta é processar o ficheiro em blocos:
public static void Encripta(string src, string dest){
    Directory.CreateDirectory(dest);
    File.Create(dest);
    var buffer = new byte[4096];
    using(var reader = File.OpenRead(src))
    using(var writer = File.OpenWrite(dest))
    {
        int bytes;
        while((bytes = reader.Read(buffer, 0, buffer.Length)) > 0){
            //chama o seu encryptData com buffer aqui
            writer.Write(buffer, 0, bytes);
        }
    }
}

Voce também terá que adaptar o seu algoritmo atual. Quer a parte de encriptacao quer a parte de desencriptacao. Por aquilo que percebi sempre que encripta um array, o algoritmo adiciona um byte no fim (uma especie de checksum). Mas o problema agora é que voce só quer que isso seja feito no último array.
public static void Encripta(string src, string dest){
    Directory.CreateDirectory(Path.GetDirectoryName(dest));
    var buffer = new byte[4096];
    var cipher = new Cryraz(new byte[]{10, 11, 12});

    using(var reader = File.OpenRead(src))
    using(var writer = File.Create(dest))
    {
        int bytes;
        while((bytes = reader.Read(buffer, 0, buffer.Length)) > 0){
            Array.Resize(ref buffer, bytes);
            //O algoritmo de encriptacao tem que ter um parametro adicional que indica se este é ou nao o último bloco.
            cipher.EncryptData(ref buffer, reader.Position == reader.Length);
            //chama o seu encryptData com buffer aqui
            writer.Write(buffer, 0, buffer.Length);
        }
        writer.Flush();
    }

}

Do mesmo modo o algoritmo de desincriptacao le sempre o último byte do array para obter o checksum. O problema é que o checksum só está presente no último array. O que isto quer dizer é que tem que ler o valor de antemao.
public static void Desencripta(string src, string dest){
Directory.CreateDirectory(Path.GetDirectoryName(dest));
var buffer = new byte[4096];
var cipher = new Cryraz(new byte[]{10, 11, 12});

using(var reader = File.OpenRead(src))
using(var writer = File.Create(dest))
{
    reader.Position = reader.Length - 1;
    //le o checksum do fim do ficheiro, para decriptar todos os blocos
    var checkSum = reader.ReadByte();
    reader.Position  = 0;
    int bytes;
    while((bytes = reader.Read(buffer, 0, buffer.Length)) > 0){
        Array.Resize(ref buffer, bytes);
        cipher.DecryptData(ref buffer, (byte)checkSum);
        writer.Write(buffer, 0, buffer.Length);
    }
    writer.Flush();
}

Código completo
Comment: @CypherPotato Atualizei a resposta
Comment: `int bytes` seria a atual posição do byte que foi corrido?
Comment: @CypherPotato Nao. É o tamanho de bytes que foi lido para o buffer. Se o ficheiro tiver por exemplo apenas 1000 bytes entao ele só vai entrar no `while` 1 vez e `bytes` terá o valor 1000
Comment: Fiz a implementação deste método na classe, mas não deu certo, o tamanho de saída do arquivo ficou maior que o tamanho original e a descriptografia descriptou o arquivo porém ele ficou corrompido. Não sei o que houve.
Comment: @CypherPotato Só o posso ajudar se publicar o código completo para encriptar e desencriptar.
Comment: Atualizei a pergunta com um link.
Comment: Houve quebra. Implementei as mudanças na classe `Cryraz` e coloquei a classe `Sample` na classe de testes. Usei um vídeo de 25MB, então decifrei ele usando o código nativo, e o arquivo foi corrompido. Código: https://pastebin.com/5bCt4XRf
Comment: Gostei da ideia dos streams, mas não sei manipular streams. A minha ideia sugere ler todos os itens do stream normalmente, ignorando o último que seria o Hash, e no final da leitura, a validação do checksun seria feita. A mesma coisa seria para a decriptografia, fazer a operação byte-por-byte, e quando chegar no último byte, descarta-lo, pois já iria saber o que fazer com ele.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/61799/discussion-between-bruno-costa-and-cypherpotato).


How to prevent admin role from changing "Updated date" of content

Question: The updated date of the content is displayed on each node with this code in template file.
<?php print strftime( "%Y-%m-%d", $node->changed) ?>

Now when I save the content with admin role the date displayed is the date I updated (of course). But I only want to display the date updated by the author of the content. So how can I prevent admin role from changing "updated date" and only keep the date updated by the content author?  Or is there a way to display only the updated date by the author of content?
Answer: You can't really, it's hard coded into the node_save() function with this bit of code:
$time = time();
if (empty($node->created)) {
  $node->created = $time;
}

// The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
$node->changed = $time;

Short of implementing your own node form which bypasses node_save() there's not really much you can do (except hacking the core node.module file which is never advised).
Comment: Thanks for letting me know. So then probably the only way I can do is to replace "last updated date" with "last login date of the user" ..
Answer: <?php if (($logged_in)&&($user->uid != "1")): ?>
<?php print $submitted; ?>
<?php endif; ?>

Comment: I'm not talking "who is logged in" but "who has updated the content".. Sorry I had the wrong code by mistake above so I edited it. and what I have on my template now is changed) ?>
Answer: Like Clive mentioned there is no good/easy way to prevent the node change timestamp from being updated, but as a possible alternative you could use node creation time instead:
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op) {
    case 'presave':
      global $user;
      if ($node->type == 'mynodetype' && !in_array('administrator', $user->roles)) {
        $node->created = time();
      }
      break;
  }
}

This implementation of hook_nodeapi() would set the 'mynodetype' node creation time to the current time when a non-administrator saves it. You'll have to keep in mind that users can manually set the creation time when editing nodes and this will override it for non-administrators. It will also mean that in those cases the actual node creation time will be lost even if the user isn't modifying it.
Comment: Thanks. I'm not sure if I understand this or not.. So basically the original updated time will be kept as usual and the node creation time will be something like "the updated type by none admin users" then original node creation time will be lost as a consequence. If I got it right I might be able to achieve what I've been looking for. Because this content type is "content profile" so I don't really need to keep the node creation time as user creation time is nearly the same thing. By the way it's also possible to implement this only to one content type?
Comment: Yeah you understand that correctly and you can restrict it to a specific content type by checking the `$node->type` value (I added this to my answer).
Comment: Can you help me a bit more please? I don't know why but also admin role is changing the "node creation time" when save the content.. So what about letting only "node author" change "node creation time"?
Comment: It's working for me so you may want to recheck that the names used in the code fit with the ones on your site. Anyway to check for node author instead you should switch out the current `if` statement with `if ($node->type == 'mynodetype' && $node->uid == $user->uid)`.
Comment: Now it works perfectly for my need. I realized letting only the node author makes more sense than preventing the admin role.Because like sub admin role also will not change it. Thanks a lot !
Answer: In order to prevent changes to nodes by administrators from updating the changed date, you can make a module with the following code. The way this works is when an administrator saves a node, the new changed date is replaced with the old changed date.
<?php

/**
 * Implements hook_node_presave().
 * @param $node
 */
function YOURMODULE_node_presave($node) {
  global $user;
  if (in_array('administrator', $user->roles)) {
    $node->changed = $node->original->changed;
  }
}

The above code will prevent the date from updating on all node types. If you only want this to apply to specific node types, try something like the code below. You might want to extract the $types array into a module configuration form.
<?php

/**
 * Implements hook_node_presave().
 * @param $node
 *
 * Add node types to $types array to freeze their changed date.
 */
function YOURMODULE_node_presave($node) {
  $types = array(
    'your_node_type',
    'node_type_2'
  );
  if (in_array($node->type, $types)) {
    $node->changed = $node->original->changed;
  }
}

Answer: In Drupal 9 (and a while before), the changed field of the node entity is of type ChangedItem (see BaseFieldDefinition::create('changed') in Node.php).
In Drupal\Core\Field\Plugin\Field\FieldType\ChangedItem, you'll find the following:
public function preSave() {
    parent::preSave();
    ...
      if (!$entity->isNew() && $original && $original->hasTranslation($langcode)) {
        $original_value = $original->getTranslation($langcode)->get($this->getFieldDefinition()->getName())->value;
        if ($this->value == $original_value && $entity->hasTranslationChanges()) {
          $this->value = REQUEST_TIME;
        }
      }
    }

So, if you change the changedTime in hook presave of your content type to +1 second, the change timestamp will stay "about" the same...
This is what I do in my hook preSave:
if (Drupal::currentUser()->id() == 1) {
      $this->setChangedTime($this->original->getChangedTime()+1); // +1 sek. fakes ChangedItem to not fire update
    }

Then it won't appear in like "changed recently" lists at my pages.


Running a linux command against Icinga2 macro variable in mail script?

Question: It looks like some macros have been dropped between Icinga1 and Icinga2?
For example, I can only add "HOSTDURATIONSEC" = "$host.duration_sec$", to my template to then use it in the mail-host-notification script like: State: $HOSTSTATE for $HOSTDURATIONSEC which tells me how long the host has been in that state. But it only gives me seconds and that's not very helpful at a glance when receiving alerts.
Because HOSTDURATION is no longer available or not yet implemented, I've tried converting the seconds to something more readable using functions and other bash attempts within that mail-host-notification but it doesn't seem to work.
I'd like to be able to create a new variable in that script maybe using a command from a linux package timetrans like this:
#!/bin/sh
SECS=$HOSTDURATIONSEC
CONVERTSECONDS=`timetrans -c $SECS`
eval $CONVERTSECONDS
$HRTIME=`eval $CONVERTSECONDS`

template=`cat <<TEMPLATE
Date/Time: $SHORTDATETIME (EST)

Notification Type: $NOTIFICATIONTYPE

Host: $HOSTALIAS
Address: $HOSTADDRESS
State: $HOSTSTATE for $HRTIME

------------------------------------------
New Jersey DC Icinga Monitoring

Additional Info: $HOSTOUTPUT

Notes on this device:
$HOSTNOTES

Comments: $NOTIFICATIONAUTHORNAME $NOTIFICATIONCOMMENT
TEMPLATE
`

...but like the attempts I've tried using functions to convert the seconds variable $HOSTDURATIONSEC, it's not working. I'm tried in many ways, but it seems to me that Icinga isn't passing those env's set in the template.
  env = {
    "NOTIFICATIONTYPE" = "$notification.type$"
    "HOSTALIAS" = "$host.display_name$",
    "HOSTADDRESS" = "$address$",
    "HOSTSTATE" = "$host.state$",
    "HOSTNOTES" = "$host.notes$",
    "HOSTDURATIONSEC" = "$host.duration_sec$",
    "LONGDATETIME" = "$icinga.long_date_time$",
    "SHORTDATETIME" = "$icinga.short_date_time$",
    "HOSTOUTPUT" = "$host.output$",
    "NOTIFICATIONAUTHORNAME" = "$notification.author$",
    "NOTIFICATIONCOMMENT" = "$notification.comment$",
    "HOSTDISPLAYNAME" = "$host.display_name$",
    "USEREMAIL" = "$user.email$"
  }

Of course, anything I added to this list like "SHORTDATETIME" = "$icinga.short_date_time$",, "HOSTNOTES" = "$host.notes$",, etc. are working, but I'm having trouble trying to run linux commands against those variables in the script. Am I missing something? Anyone know where I'm going wrong? Any/All help is appreciated.
Comment: Care to explain the downvote? If my logic is flawed. I'd appreciate fair reasons and consideration. That doesn't help anyone.
Comment: By philosophy and design voting happens unattributed and **neither voting up nor voting down requires any mandatory additional explanation**. Without a comment to the contrary one or more *possible* reasons for a down vote can be found in the tooltip that appears when your mouse pointer hoovers over the down button: *"this question does not show any research effort; it is unclear or not useful"*. That may or may not reflect the actual & private reason of whoever did cast a vote.
Answer: I'd leave such calculation tricks inside the notification scripts. Since you are not working with Icinga 2 internals, it doesn't makes sense to fiddle with a function.
What I noticed in your script is:
$HRTIME=`eval $CONVERTSECONDS`

Corrent would be:
HRTIME=`eval $CONVERTSECONDS`

Btw. if you are using timetrans by the package dnssec-tools, it is in /usr/sbin, so not in path of the icinga/nagios user.
Modified working example:
#!/bin/sh
SECS=$HOSTDURATIONSEC
TIMEREADABLE=`/usr/sbin/timetrans -c $SECS`

template=`cat <<TEMPLATE
Date/Time: $SHORTDATETIME (EST)

Notification Type: $NOTIFICATIONTYPE

Host: $HOSTALIAS
Address: $HOSTADDRESS
State: $HOSTSTATE for $TIMEREADABLE

------------------------------------------
New Jersey DC Icinga Monitoring

Additional Info: $HOSTOUTPUT

Notes on this device:
$HOSTNOTES

Comments: $NOTIFICATIONAUTHORNAME $NOTIFICATIONCOMMENT
TEMPLATE
`
/usr/bin/printf "%b" "$template"

To be called via:
HOSTDURATIONSEC=123 sh test.sh

P.S.(1) If you are missing a macro in Icinga 2, open an issue to suggest it
P.S.(2) Don't call other users a coward, that is not nice!


Como conectar a uma rede Wi-Fi específica a partir do meu aplicativo?

Question: Galera, estou seguindo o tutorial abaixo para listar as redes Wi-Fi disponíveis no meu aplicativo Android.

http://www.tutorialspoint.com/android/android_wi_fi.htm

Gostaria de saber se é possível que meu aplicativo faça meu Android conectar a uma rede específica quando o usuário clicar na mesma.
É possível fazer isso a partir do meu aplicativo?
Comment: Allef, acho que essa pergunta pode te ajudar: http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically
Answer: É so chamar essa função passando o login e senha em String mais essa função so funciona para Wifi WPA_PSK e WPA2_psk
<code>  public void Connection(String ssid, String password){

    WifiConfiguration wfc = new WifiConfiguration();

    wfc.SSID = "\"".concat(ssid).concat("\"");
    wfc.status = WifiConfiguration.Status.DISABLED;
    wfc.priority = 40;

    wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

    wfc.preSharedKey = "\"".concat(password).concat("\"");

    WifiManager wfMgr = (WifiManager)   mGap.getSystemService(Context.WIFI_SERVICE);
    int networkId = wfMgr.addNetwork(wfc);

    if (networkId != -1) {
        // success, can call wfMgr.enableNetwork(networkId, true) to connect
        wfMgr.enableNetwork(networkId, true);
    }
}
</code>
Comment: Só faltou uma função para listar as redes para resposta ser "perfeita", pois pelo que entendi o autor quer listar as redes e clicar na desejada.
Comment: Obrigado! Eu já havia conseguido utilizando o conteúdo de alguns posts deste site http://www.tutorialspoint.com/
Comment: Guilherme, se ele quiser listar pode usar o próprio gerenciador do Android, não tem muito sentido recriá-lo apenas para selecionar a rede. Se quiser abrir o gerenciador é só usar um intent `contexto.startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));`


Multiplas conexões com o Banco

Question: Em um sistema PHP que se comunica com o BD (MySQL) para recuperar as informações e retorna-las ao usuário que o acessa é necessário estabelecer múltiplas conexões com o Banco? Ou somente uma?
Answer: Diz o manual do PHP que ...

A conexão com o servidor será fechada assim que a execução do script
  terminar, a menos que tenha sido fechada anteriormente usando-se
  explicitamente...

Verdade, mas não 100%. Não nos podemos esquecer do lado do servidor pode existir definições como Connection Lifetime ou Connection pooling.
De forma simplista a uma instância correspoderá uma conexão à base de dados. Hoje em dia e a partir da versão 5 do PHP, a utilização da biblioteca PDO, permite de forma implicita utilizar a gestão da conexão à base de dados, reaproveitando a mesma "conexão" a cada HTTP Request consequente.
Desta forma e no caso de um acesso simples de uma instância a uma base de dados é pacifico, mas a localização geográfica de ambos os pontos vai interferir, como o tempo que decorrer entre Request.
Se formos um pouco mais a fundo na questão percebemos que lidar com a criação de uma conexão é um processo lento. E por isso é que ao invés de fazer uma nova conexão para cada solicitação, o servidor SQL utiliza uma POOL de, digamos a titulo de exemplo, 100 conexões "ativas/permanentes".
Na prática você no PHP quando precisa de uma conexão, solicita-a (instanciando o PDO) e usa, e usa... Você pode ajustar o tamanho da POOL para mudar a forma como o seu aplicativo se comporta. Maior POOL = mais conexões = mais "threads" permitindo fazer mais "coisas" ao mesmo tempo, mas isso também pode sobrecarregar o lado do servidor.
Ao escrever estas linhas vem um projeto recente à memória onde...
A uma instância do objecto PDO irá corresponder a uma conexão à base de dados, mas várias instâncias podem utilizar as mesmas conexões quando a implementação "salte" permanentemente entre base de dados como por exemplo num mecanismo de Sharding, mais precisamente em FEDERATED TABLE. Trata-se de um mecanismo muito simples pois a base mantém-se onde a reutilização de conexões cabe ao servidor gerir, sendo que pode e deve o seu código ser um pouco inteligente e dar uma ajuda.
Na prática resulta em instâncias do PDO entre "requets consecutivos". Mais uma vez e na prática é mantido o mecanismo de uma instância do "objeto" para uma conexão, mas não necessariamente conexões distintas se por exemplo um servidor alojar várias base de dados ou em casos em que o request utiliza o mesmo servidor de um request anterior.
Os recursos não são infindáveis e é por isso que chamamos servidor a um servidor/serviço de SQL, pois além de "arrumar" a informação, tem também a seu cargo muitas outras tarefas como a de gerir e optimizar as conexões.
Answer: No seu código apenas uma basta.
O que pode ocorrer é sua aplicação ser chamadas múltiplas vezes pelo mesmo usuário ou usuários diferentes. Seriam várias instâncias da aplicação, cada uma vai estabelecer uma conexão própria com o banco de dados. Então neste cenário o banco de dados estará atrelado à várias sessões de comunicação de dados com as instâncias da aplicação.
Mas cada instância só precisa ter uma conexão, não importa quantas coisas diferentes você queira fazer com no banco de dados.
Isto não quer dizer que não possa ter várias conexões. Se houver um motivo para ter várias, não há problema também.
Em alguns casos a conexão permanece aberta mas em estado de espera, então quando a mesma instância manda criar uma nova conexão que foi "fechada" ela aproveita a conexão já existente.
Coloquei no GitHub para referência futura.
Answer: Apenas uma por banco de dados. Normalmente você irá abrir a conexão no início do processamento da requisição, e esta irá ser reaproveitada até o final.
Algo como:

Inicia a execução do script;
Chama o script de configuração;
Inclui demais scripts necessários;
Abre conexão com o banco;
Executa queries;
Gera a resposta da requisição (HTML, XML, Json, JPG, ou qualquer outra coisa);
Encerra a conexão;
Fim do script.

Em alguns casos você pode querer que a conexão seja persistente entre várias requisições, mas desconheço de um caso onde isso será útil. Verifique a documentação do driver utilizado para verificar o suporte a este recurso.
Algumas características do driver que você utilizar poderão influenciar no ciclo de vida da conexão.
Por exemplo, o driver PDO irá manter a conexão aberta até que o destrutor do objeto seja chamado (atribuindo null à referência do objeto).
Outros drivers, como o pg irá fechar a conexão ou quando uma chamada a pg_close acontecer ou quando encerrar a execução do script. Do contrário, chamadas ao pg_connect irão reaproveitar conexões criadas, desde que a string de conexão seja a mesma.
Observação: Sei que colocou a tag mysql na sua questão, mas ela é um tanto genérica. Acabei citando o PostgreSQL por eu ter mais experiência com ele.
Comment: Seria uma conexão por requisição, então se dois usuarios fizerem 10 requisições cada serão abertas e fechadas 20 conexões, ou poderia aproveitar a mesma conexão durante o tempo em que o usuario ficar logado?
Comment: O ideal, por incrível que pareça, é abrir e fechar as 20 conexões, uma por requisição (pelo menos nos casos tradicionais). O motivo disso, é que uma conexão aberta consome recursos do servidor, o que pode causar inclusive problemas de DoS (imagine se ao invés de 2 usuários, fossem 2000 usuários... seriam 2000 conexões mantidas abertas a todo momento!). Além disso, normalmente o banco de dados esta "próximo" do servidor web, e portanto a conexão pode ser estabelcida em meros milissegundos, ou menos.
Comment: Entendi, Obrigado

Multiplas conexões com o Banco


Visual Studio 2015 vs 2012

Question:
Can a static library compiled in VS 2015 can be used in VS 2012? The C compiler of VS 2012 is very old. The most common problem I encounter is the variable declaration location. A variable has to be declared in the beginning of its scope in VS 2012.
If there is such a compatibility then I just need to fix compilation errors in header files and call the functions from the library. Is that right?
Answer: In general, static libraries are not compatible between different versions of Visual Studio.
https://en.wikipedia.org/wiki/Visual_C%2B%2B#Compatibility

The Visual C++ compiler ABI have historically changed between major
  compiler releases. This is especially the case for STL containers,
  where container sizes have varied a lot between compiler releases.
  Microsoft therefore recommends against using C++ interfaces at module
  boundaries when one wants to enable client code compiled using a
  different compiler version. Instead of C++, Microsoft recommends using
  C or COM interfaces, which are designed to have a stable ABI
  between compiler releases.

I have not specifically tried doing VS2015 -> VS2012, but going the other way definitely has some issues (VS2012/VS2013 -> VS2015). However, in VS2015, there are undocumented libraries (legacy_stdio_definitions.lib and legacy_stdio_wide_specifiers.lib) which attempt to mitigate some specific problems, but they aren't a catch-all for compatibility.
The best solution is to compile the static library with the version of Visual Studio you intend to consume it in.

Visual Studio 2015 vs 2012


Animação da div, sem CSS3 para posição futura

Question: Tenho uma suposta galeria de produtos, com divs alinhadas usando {display: block; float: left;}
Eu fiz com que algumas divs desapareçam dependendo do menu selecionado usando fadeOut() e reapareçam com fadeIn().
Criei esse código para que isso aconteça:
var tipo="all";
$('a.type').click(function(){
    $('a.type').removeClass('Bolding');
    $(this).addClass('Bolding');

    tipo=$(this).attr('id');
    $(".imagem").each(function(){
        if($(this).hasClass(tipo) || tipo=="all"){
            $(this).fadeIn();
        }else{
            $(this).fadeOut();
        }
    })

})

JSFiddle
Quando as divs somem elas ganham o valor {display:none} desaparecendo da página. o problema é que as outras divs simplesmente pulam para a posição futura. E eu queria que elas fizessem uma animação até a próxima posição se encaixando. Tomem como exemplo este plugin, só que ele é pago.
Não quero usar CSS3 pela compatibilidade.
Comment: Ok, vou preparar aqui e posto.
Comment: Seria bom colocar um trecho de código no jsFiddle para facilitar a busca da solução por outras pessoas. Acho que fica até melhor pois facilita a integração da resposta com seu código.
Comment: http://jsfiddle.net/williammustaffa/Sn46E/
Aqui está :D
Comment: Show, vou dar uma olhada.
Comment: Achei um plugin externo, tem problema? Caso não tenha vou adapta-lo ao seu código e posto uma resposta.
Comment: Se for um plugin free, facilitaria muito! Não tem problema! Agradeceria! :D
Comment: Pode me mandar o nome do plugin? :D
Comment: Ah sim, eu tava tentando fazer o source sem utilizar html5 (já que não quer css3).

Achei 2 plugins: o QuickSand (http://razorjack.net/quicksand/) e o Shuffle (http://vestride.github.io/Shuffle/)

Além disso tem o Isotope (http://isotope.metafizzy.co/) mas ele é pago para uso comercial (barato)
Answer: Crie uma array de posições. Cada item da array tem valores de posição (top e left). Ao reorganizar, anime os elementos para a posição alvo.
Se você puder colocar um id em cada elemento facilitará muito, por dois motivos: a lógica fica mais simples e o código fica mais rápido, pois recuperar elementos pela id demora menos.
Com as ids, crie uma array com a ordem dos elementos. Ao esconder um elemento, remova-o desta lista. No final, pegue a lista com os elementos que sobraram e mova-os!
Você também vai notar que no seu exemplo as divs possuem posição absoluta. Você vai precisar dessa propriedade para mover os elementos livremente.
http://jsfiddle.net/vzCj7/
var tipo="all";
var posicoes = [[0,0],[0,80],[80,0],[80,80]];

    $('a.type').click(function(){

        var elementos = ['a','b','c','d'];
        var alterados = [];

        $('a.type').removeClass('Bolding');
        $(this).addClass('Bolding');

        tipo=$(this).attr('id');
        $(".imagem").each(function(){
            if($(this).hasClass(tipo) || tipo=="all"){
                $(this).fadeIn();
            }else{
                $(this).fadeOut();

                var elId = $(this).attr('id');
                var meuIndice = elementos.indexOf(elId);
                elementos.splice(meuIndice,1);

            }
        })

        for (i in elementos){

            var meuIndice = elementos.indexOf(elementos[i]);

            alvoY = posicoes[meuIndice][0];
            alvoX = posicoes[meuIndice][1];

            console.log('elemento '+elementos[i]+' deve ir para '+alvoX+' e '+alvoY);

             $('#'+elementos[i]).animate({
                 top: alvoY,
                 left: alvoX,
             }, 1000);

        }

    })


php/mysql search for multiple values

Question: I have a table homes with (country,city,area,published) fields. I have a search form where someone can enter country or city or area. I want to get all homes which are published = 1 and any of the search terms matches any of their fields.
This is what I have so far:
SELECT * FROM homes
WHERE published = 1
AND
LOWER(country) LIKE '$search%'
OR
LOWER(city) LIKE '$search%'
OR
LOWER(area) LIKE '$search%'

The problem is that it return homes that have published = 0...
Answer: I would suggest parentheses.
SELECT * FROM homes
WHERE published = 1
AND
(
 LOWER(country) LIKE '$search%'
 OR
 LOWER(city) LIKE '$search%'
 OR
 LOWER(area) LIKE '$search%'
)

Answer: SELECT *
FROM   homes
WHERE  published = 1
       AND ( country LIKE '$search%'
              OR city LIKE '$search%'
              OR area LIKE '$search%' )

Like already does the case-insensitive stuff so you don't need it.
The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a.  http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html
Comment: My default character set is UTF-8 and collation is utf_general_ci. I think I need the LOWER()

php/mysql search for multiple values


Probability Question - An elevator & 5 Passengers

Question: I'm working on this problem:

An elevator in a building starts with 5 passengers and stops at seven
  7 floors. If each passenger is equally likely to get an any floor and
  all the passengers leave independently of each other, what is the
  probability that no two passengers will get off at the same floor?

I figure you could do 7 P 5 - since the first guy has 7 floors he can get off on, the second 6, etc. But do I need to account for the order that the people can choose their floor, and therefore multiply that by 5 factorial? Or am I approaching this incorrectly in the first place?
Thanks
Answer: The number of ways to assing $7$ floors to $5$ passengers is $7 \cdot 7 \cdot 7 \cdot 7 \cdot7$ beacuse for each passenger you can choose one of the $7$ floors.
The number of ways to assign $7$ floors to $5$ passengers without repetition of floors is $7 \cdot 6 \cdot5\cdot 4\cdot3$ because for the first passenger you have $7$ option, for the second you will have $6$ and so on. Note that this number count all possible orders betwen passengers too.
Then, you will guess it, the result is
$$\frac{7 \cdot 6 \cdot5\cdot 4\cdot3}{7^5}.$$
Answer: Call the people $A$ to $E$.  Consider the floors where they get off. It doesn't matter where $A$ gets off. The probability $B$ gets off at a different floor is $\dfrac{6}{7}$.
Given that $A$ and $B$ get off at different floors, the probability $C$ gets off at a different floor than $A$ and $B$ is $\dfrac{5}{7}$.
So the probability that $A,B,C$ all get off at different floors is $\dfrac{6}{7}\cdot\dfrac{5}{7}$.
Given they all got off at different floors, the probability $D$ gets off at a different floor from $A,B,C$ is $\dfrac{4}{7}$. Continue. Soon we get to
$$\frac{6}{7}\cdot\frac{5}{7}\cdot\frac{4}{7}\cdot\frac{3}{7}.$$
Answer: By way of a general formulation - if there are $k$ people and $n$ floors (where $ n \ge k$):
If we want to calculate the probability that all $k$ people go to the same floor, observe that there are only $n$ possible options, where each person can land on the same floor. So probability that all $k$ people land on the same floor is
$$
\frac{n}{\underbrace{n\cdot n\cdot n\dots}_\text{$k$ times $n$}}\text{ or }\frac{n}{n^k} = \frac{1}{n^{k-1}}.
$$
By law of probabilities - the probability that at least one pair of persons out of $k$ [$k \ge 2$] does NOT land on the same floor is $1 - 1/n^{k-1}$.
Also probability that no pair of persons lands on the same floor requires you to observe that the first person has $n$ choices, 2nd person has $(n-1)$ choices and so on till the $k$-th person who has $(n-k+1)$ choices and therefore the required probability is
$$
\frac{n\cdot(n-1)\cdot(n-2)\dots(n-k+1)}{n^k}
$$
Comment: Thanks for improving the answer @taroccoesbrocco
Answer: You calculate the possibilities of them not getting of at the same floor.

The first person can get off at any floor, there are 7 possibilities
The second person can get off at any floor other than the floor the
first person got off at, there are 6 possibilities
The third person can get off at any floor other than the floor the first two people got off at, there are 5 possibilities
The fourth person can get off at any floor other than the floor the first three people got off at, there are 4 possibilities
The fifth person can get off at any floor other than the floor the first four people got off at, there are 3 possibilities

There are $7*6*5*4*3=2520$ possibilities that they dont get off on the same floor
Now you calculate the total number of possibilities for them to get off. All the people can get off at any floor, there are $7^5=16807$ possibilities
The probability that no two passengers will get off at the same floor is the first possibility divided by the second, which is $\dfrac{2520}{16807}=\dfrac{360}{2401}$ which is approximately 15%


Should I correct for multiple comparisons if I generate hypothesis?

Question: While reading papers on my research topic I came across multiple paper formulating sentences similar to this:

Because of the hypothesis-generating nature of these analyses, no correction for multiple comparisons was performed.

I am a bit confused, what makes an analysis hypothesis-generating? If I run tests without having a hypothesis? And why does this mean, that I don't have to correct for multiple comparisons?
Could I perform a hypothesis testing analysis on data, and then on top of it run hypothesis-generating analysis?
Answer: This is a complex issue. I have written something about multiple testing here, and the baseline is that corrections for multiple comparisons have advantages and disadvantages and the issue is not "black-and-white" as if in some situations you'd "have to" do this and not in others. Particularly, the answer to this cannot be prescribed by any theory, but is rather of a pragmatic or even philosophical nature. Ultimately it depends on how results are interpreted. Surely, by running many tests without multiple testing correction there is a high probability to find false rejections of null hypotheses, much higher than the nominal level, and this is dangerous and should be avoided if you intend to assign a strong meaning to a significant result. What the cited authors apparently mean by "hypothesis generation" is that if they find something significant, the interpretation is not that "there is strong evidence that something meaningful is going on", but rather that "it may be worthwhile to have a deeper look into this on new data". In such a case, if the authors run, say, 20 tests, they'd be happy to have, say, 4 significant outcomes to investigate further (well taking into account that 2, 3, or even all 4 of them could be meaningless), so what this does is that it narrows the scope for future research, which may be fine, even if these results don't say anything reliable about any specific one of the outcomes, which would require new data and more research. (Conversely this means that if you want to make reliable statements about any of these hypotheses, don't do it like this.)
When reading such work, I'd advise to keep a skeptical attitude though, because occasionally one finds such remarks made by authors in the methodological part of their papers, and then in their conclusions they treat the significant results as if they were indeed really meaningful anyway, and no further research on new data is really intended. In this case talking about "hypothesis generating" research is just a cheap excuse to get around multiple testing corrections. (Personally I doubt by the way that testing lots of hypotheses and then investing those further that more or less randomly come out significant is a very convincing research program, at least in absence of a proper subject matter justification of what exactly to investigate; however I occasionally comment on non-corrected significances in exploratory data analysis, for example looking at a correlation matrix, as "things to have an eye on" or similar.)