Python @property same id as field returned by it

Question: I made this simple snippet to understand properties better:
class foo:
def __init__(self, val):
    self.val = val

@property
def val(self):
    return self._val

@val.setter
def val(self, value):
    if value < 0:
        raise ValueError("Value has to be larger than 0")
    else:
        self._val = value

f1 = foo(2)
print(id(f1._val) == id(f1.val)) #print true

Right now I undestand less than before I wrote that code. How is it, that both f1._val and f1.val are the same object? Is it some magic done in backstage? Also, why type(f1.val) is int when it is a function?
Another thing is that I though to change both val functions (one decorated by @property, second by @val.setter) to return self.val not return self._val. When trying to instantiate object I got:
RecursionError: maximum recursion depth exceeded in comparison

What is quite obvious as I return pointer to function (not sure if pointer is proper in this context?) with no condition. But here, how my first snippet worked fine even though both self._val and self.val are same object?
Comment: "How is it, that both `f1._val` and `f1.val` are the same object?" Because the `val` property getter simply returns `self._val`... I'm not sure what it is that you don't understand. Do you understand taht when you do `f1.val` it *calls* the getter and evaluates to that value?
Comment: `foo.val` is *not a function any more*. It is a `property`. `property` objects implement the [descriptor protocol](https://docs.python.org/3/howto/descriptor.html). Basically, a descriptor on some class, `MyClass.some_desriptor` can define a `__get__`, `__set__` and `__delete__` method.  When you create an instance, `myinstance = MyClass()` then that descriptors `__get__`, `__set__`, and `__delete__` methods will be called for `myinstance.my_descriptor`, `myinstance.my_desriptor = foo`, and `del myinstance.my_descriptor` respectively
Comment: When there is another method defined in the class, e.g. `func` that returns an `int`, and I would instantiate class in the very same way `type(f1.func)` is method, while `type(f1.func())` is int. It makes sense to me. Then `type(f1.val())` should also be an int, while `type(f1.val)` should be a method as far as I understand (I may be wrong however)
Comment: **it isn't a method, it is a `property` object*. Do you understand what `@property` is doing? Do you know what decorators are? I explained descriptors above, `property` is *also* a decorator, but that is mostly syntactic suguar. Basically `@property def val(self): ...` is equivalent to `def val(self): ...` then `val = property(val)`. So the `val` attribute on the class *is not longer a function/method*. It is a `property` descriptor. Note, *functions are also descriptors*, that is how they "magically" provide the instance as the first argument
Comment: Yes, yes, thank you. My comment was published before webpage had refreshed and I saw your second comment.
Comment: A `function` is *also* a descriptor, so (for instance) what you get when you use either `foo.__init__` or `foo().__init__` is defined by `function.__get__`, just as what you get from either `foo.val` or `foo().val` is defined by `property.__get__`.
Answer:
How is it, that both f1._val and f1.val are the same object?

Because you are setting them to the same object in your code. You take your value, in this case 2 and assign it to both self.val & self._val
What you did is the equivalent of
a = 2
b = 2
a == b
True

Also, why type(f1.val) is int when it is a function?

When using the @property decorator, the method no longer is callable. You can think of it almost like an attribute.
Answer: In your example, val is a descriptor as described in 22.214.171.124. Implementing Descriptors. With a descriptor, access to a variable is replaced with calls to its __get__, __set__ and __delete__ methods. The property function is a shortcut to creating descriptors. Since "property" and "descriptor" amount to the same thing, I don't know why two different names are used.
With
@property
def val(self):
    return self._val

val is bound to an object whose __get__ executes the body of the function. It gets the local variable _val.
With
@val.setter
def val(self, value):
    if value < 0:
        raise ValueError("Value has to be larger than 0")
    else:
        self._val = value

The object bound to val is updated so that its __set__ executes the body of the function, setting _val.
When python executes f1.val, it gets the object referenced by "val" but before returning, it checks to see if the object has a __get__. If so, instead of returning the object, it calls __get__ and uses its return. In your case, "_val" is returned, so naturally they are equal.
If you change your property function to get "val" instead of "_val", python still follows the same rule. "val" is a descriptor so its __get__ is called, which tries to get "val" again, but its a descriptor ... and on and on.


One matrix identity implies the other

Question: I have matrices $A\in\mathbb R^{n\times n}$, $C\in\mathbb R^{m\times m}$, and $B\in\mathbb R^{n\times m}$. I know that $A$ and $C$ are symmetric and positive semidefinite and that $K_A = A^2+BB^T$ and $K_C = C^2+B^TB$ are positive definite. Now assume that $AB = BC$. I can prove indirectly that
$$
AK_A^{-1}B = BK_C^{-1}C,
$$
but I can't prove it. Can I maybe express $AK_A^{-1}B = BK_C^{-1}C$ by using $AB-BC$?
Here is the indirect proof: We have
\begin{align}
Q
&:=\begin{pmatrix}AK_A^{-1}A+BK_C^{-1}B^T & AK_A^{-1}B-BK_C^{-1}C\\B^TK_A^{-1}A-CK_C^{-1}B^T & CK_C^{-1}C+B^TK_A^{-1}B\end{pmatrix}\\
&= \begin{pmatrix}A & B\\B^T & -C\end{pmatrix}\begin{pmatrix}K_A^{-1}A & K_A^{-1}B\\K_C^{-1}B^T & -K_C^{-1}C\end{pmatrix}\\
&= \begin{pmatrix}A & B\\B^T & -C\end{pmatrix}\begin{pmatrix}K_A^{-1} & 0\\0 & K_C^{-1}\end{pmatrix}\begin{pmatrix}A & B\\B^T & -C\end{pmatrix}.
\end{align}
Hence, $Q = MR^{-1}M$ with the matrices $M$ and $R^{-1}$ in the last row. Now,
$$
M^2 = \begin{pmatrix}A & B\\B^T & -C\end{pmatrix}\begin{pmatrix}A & B\\B^T & -C\end{pmatrix} = \begin{pmatrix}K_A & AB-BC\\(AB-BC)^T & K_C\end{pmatrix}.
$$
Hence, if $AB=BC$, then $M^2 = R$. Therefore, we have
$$
M(Q-I)M = MQM-M^2 = M^2R^{-1}M^2-M^2 = 0.
$$
Now, the fact that $K_A$ and $K_C$ are positive definite implies that $M$ is invertible (easy proof). Therefore, we get $Q = I$. But then the upper right corner in the matrix $Q$ must be zero.
Answer: I have it! If $AB=BC$, then also $B^TA = CB^T$ and thus $CB^TB = B^TAB = B^TBC$. Also,
$$
BK_C = BC^2 + BB^TB = A^2B + BB^TB = K_AB.
$$
Hence, $BK_C^{-1} = K_A^{-1}B$. Therefore,
$$
AK_A^{-1}B = ABK_C^{-1} = BCK_C^{-1} = BK_C^{-1}C,
$$
where the last identity follows from $CB^TB = B^TBC$.

One matrix identity implies the other


Slide in another div, from right to left, and adjust the height animated (jQuery)

Question: I have a div with a login form and a button for "forgot password".
I have another div with the forgot password form, i want to slide in, in front of the login div and adjustig the height, when "forgot button" is clicked.
The entire box should be positioned
Illustration:

The HTML:

LOG IN FORM

LOG IN FORM

LOG IN FORM

LOG IN FORM

LOG IN FORM

Forgot password?

FORGOT FORM

FORGOT FORM

FORGOT FORM

CSS:
#content{
  background-color: blue;
  width:100%;
  height:900px;
}
#box{
  width: 200px;
  position: relative;
  top: 20px;
  left: 14px;
  display: block;
  border:2px solid red;
  background-color: white;
  padding: 5px;
}
#forgot{
  cursor: pointer;
  color: blue;
}

This is what i got so far in jQuery:
$(document).ready(function () {
    $("#forgot_form").css({'display':'none'});
    $("#forgot").on("click", function () {
        $("#log_in").css({'display':'none'});
        $("#forgot_form").css({'display':'block'});
        $("#forgot_form").css({"left":"200px"}).animate({"left":"0px"}, "slow");
    });
});

JSFiddle example: https://jsfiddle.net/rLdfmf4n/4/
Answer: I think it would be easier to just use CSS animation to do what you're trying to do. Try adding this to your CSS file
#forgot_form {
position: absolute;
left: -200px;
width: 200px;
height: 200px;
-webkit-animation: slide 0.5s forwards;
-webkit-animation-delay: 2s;
animation: slide 0.5s forwards;
animation-delay: 2s;
}

@-webkit-keyframes slide {
100% { left: 0; }
}

@keyframes slide {
100% { left: 0; }
}

Now you would just have to write some JQuery to trigger the animation when clicked on the link. (Hint: use toggleClass())
Answer: You are not giving the margin-left and margin-right to auto in css...when you give margins it automatically sets the form in its position
Answer: Try this i hope this help you

$(document).ready(function () {
    $("#forgot").on("click", function () {
        $("#log_in").css({'display':'none'});
        $("#forgot_form").css({'display':'block'});
        $("#forgot_form").animate({"left":"0px"}, "slow");
    });
});
#content{
  background-color: blue;
  width:100%;
  height:900px;
}
#box{
    width: 200px;
  position: relative;
  top: 20px;
  left: 14px;
  display: block;
  border:2px solid red;
   background-color: white;
   padding: 5px;
}
#log_in{

}
#forgot{
  cursor: pointer;
  color: blue;
}
#forgot_form{

   position: relative;
    left: 220px;
    width: 200px;
    top: 0;
    display: none;
}

LOG IN FORM

LOG IN FORM

LOG IN FORM

LOG IN FORM

LOG IN FORM

Forgot password?

FORGOT FORM

FORGOT FORM

FORGOT FORM

hope this help you.


showing G is abelian

Question: If $G$ group of order $52$ includes a normal group of order $4$ then $G$ is abelian.
I did like this
$$
|G|=52=2^2\cdot 13
$$
let $H$ be normal group of order $4$.
$n_{13}=1$ thus $G$ has a $K$ normal group order $13$.
$|H|=4,|K|=13$,   $H∩K=\{e\}$, $|H \cap K|=1$ , $H$ and $K$ finite groups $52=|HK|=|H|||K|/|H∩K|$ thus $HK=G$
I dont know either what to do next or if it's correct with this way
Comment: observation: the order of $K$ is prime; hence $K$ is cyclic (in particular, abelian).
Answer: Since we have normal subgroups $H,K$ of $G$ with respective orders $4,13$, and since $H\cap K=\{e\}$ and $HK=G$, then $G\cong H\times K$. It suffices, then, to show that groups of order $4$ or $13$ must be abelian (the latter is very easy since a group of prime order is cyclic, and the former isn't too difficult), and that a product of abelian groups is abelian (again, not difficult).
Comment: I always like to say that small groups are abelian because formulating "is not abelian" requires a good handful of elements: If $ab\ne ba$, let $c=ab$, $d=ba$; then $1,a,b,c,d$ must be pairwise distinct (e.g. if $c=1$, then $b=a^{-1}$ and $ab=ba$).
Comment: Very nice; beauty in simplicity.

showing G is abelian


Why can't the piano play middle eastern music?

Question: I'm a beginner pianist, and I asked my teacher about the possibility of playing some Persian music on the piano. He told me it's typically not possible, but didn't really elaborate on why. So why is it that the piano shouldn't be able to play that music? Could I play it on the guitar, or violin, then?
Comment: Also, Kari Ikonen has invented a device called [maqiano](https://kariikonen.com/maqiano/) that allows you to temporarily retune a subset of the keys of a piano. Assuming you know how the tuning of the desired maqam differs from the default equal temperament tuning. I don't know if the device is commercially available yet. The last time I heard him give a demo, he told that the patent is still pending.
Comment: FWIW, our e-piano offers a specific tuning for Arabian music, which may or may not encompass Middle Eastern or Persian music.
Comment: See also @JyrkiLahtonen's [helpful post about maqiano](https://music.stackexchange.com/a/108021/70803).
Comment: Are you asking about authentic Middle Eastern music, or Middle Eastern-inspired music (the theme to "Aladdin" for example)
Comment: @dbmag9 I agree, but then the question doesn't ask for traditionality or authenticity. That seems to have been assumed by most of the answers here.
Comment: Maybe take a look at this? https://en.wikipedia.org/wiki/In_a_Persian_Market
Comment: @BradThomas Without judging the merits of *In a Persian Market*, I think it's safe to say that it is not an attempt to render tranditional Persian music or represent authentic Persian culture.
Answer: A modern piano is tuned to 12-TET, 12-tone equal temperament.
12-TET is what's called a tuning system, almost all current Western music uses it.
It basically means 12 notes per octave and the notes are spread equally, it's the same distance (measured in fractions of an octave) between all of them.
Persian music uses a different system. I'm no expert, but Essentials of Persian music says that there are three competing models to describe Persian music:

24-tone scale, like 12-TET but with an extra quartertone between each semitone.
22-tone scale, not tied to 12-TET
"Flexible intervals" with regional variations, not tied to any particular scale or tuning system. A researcher recorded many performers and measured the intervals used in practice, and found that the whole tone and semi-tone were fairly stable intervals, but several other intervals between a semi- and a whole tone were very flexible. (Perhaps analogous to blue notes used in blues, where there is no standard for how "blue" or flat the note should be, it's up to the performer.)

Whether there are 24, 22, or some other number of tones per octave, it's more than the 12 on a piano, and many of the them are tuned differently. Demo of differences between quarter tones in Persian/Arabic/Turkish music.
Piano can't play that. Instruments that can fall in two groups: Some have continously variable pitch (e.g. violin or trombone), while others have a standard 12-tone fingering but can pitch bend a semitone or more so it can cover all the intermediate pitches as well (e.g. saxophone, synthesizer, probably fretted guitar).
Comment: It should be added that it's definitely possible to play the piano in a way that resembles traditional Persian music *much more than* the usual Western way of playing it, just not perfectly. (After all, it's possible to play jazz music on the piano even though it doesn't have blue notes either.)
Comment: @KilianFoth what do you mean it doesn't have blue notes? My (limited) understanding is that in, for example, A minor pentatonic, the blue note is the Eb which the piano is perfectly capable of playing. Sure, you can't bend the piano's strings to get to notes that are not on the keyboard (or you can't do so easily, anyway) but many blue notes _are_ on the keyboard depending on the scale you're playing in. Is that wrong?
Comment: *Most* pianos can't - but [this one](https://www.thefluidpiano.com/) can...  Also many digital pianos have the capability to bend tones in this way, which is probably a far cheaper alternative.
Comment: @terdon Yes, that's exactly my point. You can get a pretty good rendition of  blue notes on the piano, but even so a jazz singer would feel *incredibly* hampered if they could only produce that one exact Eb frequency and not thousands around it.
Comment: @DarrelHoffman Thanks for the link, looks interesting. Yes, many digital keyboards can do it. Pure digital pianos very rarely have pitch bend, but things like arranger/workstation keyboards and stage pianos frequently do. Plus many/most digital keyboards and pianos have a set of alternative tunings, mine has about a dozen split between Indian, Middle-Eastern and alternative Western tunings like Pythagorean and meantone.
Comment: @terdon No, it's not wrong: A piano can play a blue note by going a semitone flat, like Eb instead of E. But it's missing the expressiveness from going flat some amount less than a semitone, which guitar/sax/voice can do just fine. How important that distinction is depends on the music and expectations, I suppose. Persian/Arabic music apparently has one scale (out of many) that is fairly close to the Western major scale, perhaps songs in that scale would be close enough on a piano, but I don't know enough abut Middle-Eastern music to comment on that. Still a bit restrictive.
Answer: The issues of tuning systems have been addressed, but there is an additional problem.
Pianos can be — and have been — retuned to accommodate, for example, quarter-tone music.
The truly "impossible" part of Arabic and Persian music — not to mention Indian, Chinese, Japanese, and many, many other cultures — is the ornamentation, which plays an essential, central role. The ornamentation requires the bending of pitches, which a fixed-pitch instrument like the piano simply cannot accommodate.
For a significant discussion of ornamentation in Arabian music, see Lois Ibsen al Faruqī, "Ornamentation in Arabian Improvisational Music: A Study of interrelatedness in the Arts", The World of Music 20/1 (1978): 17–32.
Answer: Possible but effort prohibitive
Persian music makes use of quartertones/microtones that fall in between the typical note progressions of western classical music (at least for the piano). Let's suppose we did have a kind of framework in mind (maqiano or otherwise) there is also the logistics of the process to consider. Tuning a piano even under normal circumstances is surprisingly complicated and potentially dangerous to you or the instrument if done improperly; many often turn to professionals for this. So we can only imagine how short the list would be for piano tuning services that understand oriental music. Absent professional help, we'd be attempting to tune a very sophisticated instrument by ourselves. At the very minimum we'd need beyond perfect pitch ears and an oriental tuner.
If we somehow got that far and tuned it full-Persian, then we may face other issues. The player interface of the piano is clearly designed for half-steps. Once you have quarter-tones in the mix, you'd lose the whole intuition of the white and black keys. This is especially problematic when the quartersteps don't line up with existing western scales and is further complicated if you did decide to play in a different Persian key -- probably feeling even weirder than normal and affecting muscle memory. So the process, would not be very scalable or intuitive, even if it is 'theoretically' possible.
Further issues arise once we view Persian music in the complete context: Dastgahs. These 12 scales/patterns form the framework for improvisation that provides the scaffolding of Persian music. In addition to your Persian piano, you'd need some really elaborate notation to handle not only the tones but irregular rhythms and other Oriental music quarks. I can recommend this book for more on Dastgahs:
Comment: You could use 2 pianos, one tuned a quarter-step off from the other. It would probably be easier to play and tune that way, althought requiring adjustment in the playing position.
Comment: This. I don't know enough to be sure, but I think that with maqiano you can only retune a piano to support a single maqam at a time. In a live music performance the artist won't necessarily have the time to adjust the maqiano between pieces (even if it only takes a few minutes). I cannot tell whether that is prohibitive or just a nuisance.
Comment: @simon I am little bit skeptical about that working. You see, [the maqam scales](https://en.wikipedia.org/wiki/Arabic_maqam) typically have many notes on the TET scale, but there are a few oddballs that are a quartertone off. You definitely want a single instrument to support the entire scale, I think. The catch is that on different maqams the quartertone "misses" are located at different parts of the scale.
Answer:
why is it that the piano shouldn't be able to play that music?

Without knowing much about Middle Eastern music, the obvious answer would seem to be "tuning". Within its range, which must be amongst the largest if not the largest of any instrument, it can only play the notes it is tuned to play. It cannot play the notes between them.

Could I play it on the guitar, or violin, then?

Not so easy on the guitar, because it is fretted and so suffers to a lesser degree to the same problem as the piano.
Should be easy on the violin, insofar as playing with correct intonation on the violin can be described as "easy".
Comment: Re the guitar, that's incorrect. Whilst it is fretted, string bending is considered a basic beginner technique which is key to playing the instrument at any level beyond simply strumming a chord. A little less so in classical, but certainly all other styles make widespread use of it. Quarter tones are often called "microbends", which comes directly from guitar string bending.
Comment: There are many pipe organs that have a range of pitch far greater than the piano.
Answer: Pianos are tuned basically to '12tet'. Which means they can play anything in any key, and it will sound at least o.k.
There are many other tuning systems, and I believe Middle Eastern tuning systems use other tuning systems which will not align exactly with 12tet. So, on a 'properly' tuned piano, the discrepancies in pitch between certain notes are not available, making any other music using any different tuning systems basically unavailable.
Trombones, violins, and other instruments will be able to find those elusive pitches, because they can play notes 'in the cracks' as we say.
Comment: It's not the discrepancies in tuning - those are fairly small and usually close enough. It's the quarter tones which simply aren't possible.
Answer: Piano = you would need to re-program the keyboard to use a microtone scale.  probably the easiest way to do this would be to use a midi keyboard and a program that allows microtone assignment.  do a search for the "apotome" project
Guitar = they make microtone guitars that have more frets than a standard guitar.  these are more difficult to play as the frets are much closer together
Violin = you should be able to do this on a standard violin, but your fingers and ears will need to be "re-programmed"
Comment: The importance of frets to tuning is frequently exaggerated.  Even on a fretted guitar it is possible to bend pitch.
Answer: Unless the piano is a player piano, a piano can't play any type of music ;-)
Also, and I mean this seriously, I'm not sure what you mean by 'middle eastern music'. The Middle East is a large region comprised of many countries spanning 3 continents. There are and have been many musicians there and they do practice and have practiced many different styles.
But I think the answer you are looking for is already given. Modern pianos are tuned using equal temperament and many musical traditions from the Middle East use other tuning methods that feature pitches not found on a modern piano. This is a big, big topic and touches not only on music theory and ethno-musicology but also physics, acoustics, and cognitive science.
However, I am not very enthusiastic about some of the previous answers, and believe that they provide some very misleading and problematic information.
The link provided by @j-g-faustus (https://theoryofmusic.wordpress.com/2008/06/09/essentials-of-persian-music-part-2/) describes the intervals used in Persian music in terms of 'cents' which means percentage of an equal tempered whole-tone. Since equal temperament is not the tuning system with which that musical tradition derived its modes, it is not in any way shape or form an appropriate way to describe it. To do so is a bit like analyzing ancient Japanese prints using a theory of art developed to describe Renaissance Italian painting.
Nor is the notion of "Flexible intervals" a good description of what is actually going on. Many scales are built on harmonic relationships built on whole number ratios (3:2, for example, is the frequency ratio of a perfect 5th---this interval by definition does not exist in 12tet). Using such ratios to construct a theory of melodic intervals results in pitches that cannot be found on a piano.
Statements like this: 'Equal temperament makes the complex harmonies of modern Western music possible, and this impressed musicians from the Middle East who came into contact with western art music. These musicians viewed the absence of harmony in their own music as a sign of inferiority to western music. The desired musical advancement was thought possible only through the adoption of western harmonic practice. That, in turn, required equidistant tones.' should be eschewed at all costs. Ali-Naqi Vaziri may have thought that, but it rather assumes quite a lot about many people's relationship to their own musical traditions.
I also find this statement from the link in @j-g-faustus very difficult to believe: '..no Middle Eastern musical instrument is capable of producing intervals of such precision [as found in the theories of the medieval theorists]; and vocal music is even more unreliable in producing accurate intervals.' Granted, I don't know and cannot know what medieval theorists the author refers to or what their theories entail, but I do know that musicians, particularly vocalists, are capable of being very accurate about pitch---particularly when placing the pitches of notes in a scale based on whole-number frequency ratios against a drone.
@Aaron's answer is also somewhat problematic. While it is true that most keyboard instruments cannot bend pitch (certainly not a modern piano), they can still approximate glissandi ornaments in their own way. I would point out that in Classical Indian Music, singers are often accompanied by a harmonium player who plays the raga in unison with the vocalist---ornaments included. By the same token it is technically impossible to perform a slur on a piano. That did not stop Beethoven from writing literally hours of piano music with slurs in it. Nor has it stopped literally millions of pianists from having performed those slurs.


prove that $Z_1 = i\cot \frac{\theta}{2}$ given that $Z = \cos \theta + i\sin \theta$

Question:
If $Z = \cos \theta+i\sin \theta$, $Z_1= \dfrac{z+1}{z-1}$, prove that $Z_1= -i\cot  \dfrac{θ}{2}\\$

This was a proof that I ran into in a quiz. I couldn't really solve it. I only got as far as $Z_1 = z+1$, $Z_1 = \cos \theta+\sin \theta$ $-1$.
It's bugging me since then. A friend told me we'd prove it using a double angle formula.
Comment: write $Z$ as $e^{i\theta}$ and factor by $e^{i\frac{\theta}{2}}$.
Answer: \begin{align*}
  \frac{z+1}{z-1} &=
  \frac{(\cos \theta+1)+i\sin \theta}{(\cos \theta-1)+i\sin \theta} \\
  &=
  \frac{2\cos^2 \frac{\theta}{2}+2i\sin \frac{\theta}{2} \cos \frac{\theta}{2}}
       {-2\sin^2 \frac{\theta}{2}+2i\sin \frac{\theta}{2} \cos \frac{\theta}{2}}
  \\ &=
  \cot \frac{\theta}{2}
  \left(
    \frac{\cos \frac{\theta}{2}+i\sin \frac{\theta}{2}}
         {-\sin \frac{\theta}{2}+i\cos \frac{\theta}{2}}
  \right) \\ &=
  \cot \frac{\theta}{2}
    \frac{\cos \frac{\theta}{2}+i\sin \frac{\theta}{2}}
         {i\left(\cos \frac{\theta}{2}+i\sin \frac{\theta}{2} \right)} \\
   &= -i\cot \frac{\theta}{2}
\end{align*}
Comment: I put a negative in front of the $i$ in the OP


How do I determine what type of exception occurred?

Question: some_function() raises an exception while executing, so the program jumps to the except:
try:
    some_function()
except:
    print("exception happened!")

How do I see what caused the exception to occur?
Comment: Never ever ever use bare `except:` (without a bare `raise`), except *maybe* once per program, and preferably not then.
Comment: Inside `except` block the exception is available through [`sys.exc_info()`](https://docs.python.org/2/library/sys.html#sys.exc_info) function – *This function returns a tuple of three values that give information about the exception that is currently being handled.*
Comment: If you care about the type of exception, it's because you've already considered what types of exception might logically occur.
Comment: If you use multiple `except` clauses you wont need to check the exception type, that is what is usually done to act accordingly to a specific exception type.
Comment: Related: [How to print an error in Python?](https://stackoverflow.com/q/1483429/3357935)
Comment: how do I fill in the blank here?  `except __ as e` . That is, how do I get the class/type in order to catch it? I'm using databricks btw so this is what I see when I try and print `type(e)`: .f_with_exception_handling..ExecutionError'>
Answer: The other answers all point out that you should not catch generic exceptions, but no one seems to want to tell you why, which is essential to understanding when you can break the "rule". Here is an explanation. Basically, it's so that you don't hide:

the fact that an error occurred
the specifics of the error that occurred (error hiding antipattern)

So as long as you take care to do none of those things, it's OK to catch the generic exception. For instance, you could provide information about the exception to the user another way, like:

Present exceptions as dialogs in a GUI
Transfer exceptions from a worker thread or process to the controlling thread or process in a multithreading or multiprocessing application

So how to catch the generic exception? There are several ways. If you just want the exception object, do it like this:
try:
    someFunction()
except Exception as ex:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(ex).__name__, ex.args)
    print message

Make sure message is brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there's one impression you should have come away with after reading the answers on this page, it's that this is not a good thing. Ending the except block with a raise statement will remedy the problem by transparently reraising the exception that was caught.
The difference between the above and using just except: without any argument is twofold:

A bare except: doesn't give you the exception object to inspect
The exceptions SystemExit, KeyboardInterrupt and GeneratorExit aren't caught by the above code, which is generally what you want. See the exception hierarchy.

If you also want the same stacktrace you get if you do not catch the exception, you can get that like this (still inside the except clause):
import traceback
print traceback.format_exc()

If you use the logging module, you can print the exception to the log (along with a message) like this:
import logging
log = logging.getLogger()
log.exception("Message for you, sir!")

If you want to dig deeper and examine the stack, look at variables etc., use the post_mortem function of the pdb module inside the except block:
import pdb
pdb.post_mortem()

I've found this last method to be invaluable when hunting down bugs.
Comment: @RikPoggi: Naive thinking. There are many reasonable circumstances when you need to catch exceptions from someone else's code and you don't know what exceptions will be raised.
Comment: @Rik I think you may very well need _all_ of this. For instance, if you have a program with a GUI and a backend, and you want to present all exceptions from the backend as GUI messages instead of having your program quit with a stack trace. In such a case, you should catch the _generic_ Exception, create a traceback text for the dialog, log the exception too, and if in debug mode, enter post-mortem.
Comment: traceback.print_exc() would do the same thing as your more complicated "".join-thing, I think.
Comment: @Gurgeh Yes, but I do not know if he wants to print it or save it to a file or log it or do something else with it.
Comment: This postmortem trick helped me narrow down an exception type of `objc.error` which is sort of a wonky one.
Comment: I didn't downvoted, but I'd say that's because you should have put a huge fat worning at the beginning saying **You shouldn't need any of this, but here's how it could be done**. And maybe because you suggest to catch the generic Exception.
Answer: Get the name of the class that exception object belongs:
e.__class__.__name__

and using print_exc() function will also print stack trace which is essential info for any error message.
Like this:
from traceback import print_exc

class CustomException(Exception): pass

try:
    raise CustomException("hi")
except Exception as e:
    print ('type is:', e.__class__.__name__)
    print_exc()
    # print("exception happened!")

You will get output like this:
type is: CustomException
Traceback (most recent call last):
  File "exc.py", line 7, in <module>
    raise CustomException("hi")
CustomException: hi

And after print and analysis, the code can decide not to handle exception and just execute raise:
from traceback import print_exc

class CustomException(Exception): pass

def calculate():
    raise CustomException("hi")

try:
    calculate()
except CustomException as e:
    # here do some extra steps in case of CustomException
    print('custom logic doing cleanup and more')
    # then re raise same exception
    raise

Output:
custom logic doing cleanup and more

And interpreter prints exception:
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    calculate()
  File "test.py", line 6, in calculate
    raise CustomException("hi")
__main__.CustomException: hi

After raise original exception continues to propagate further up the call stack. (Beware of possible pitfall) If you raise new exception it caries new (shorter) stack trace.
from traceback import print_exc

class CustomException(Exception):
    def __init__(self, ok):
        self.ok = ok

def calculate():
    raise CustomException(False)

try:
    calculate()
except CustomException as e:
    if not e.ok:
        # Always use `raise` to rethrow exception
        # following is usually mistake, but here we want to stress this point
        raise CustomException(e.ok)
    print("handling exception")

Output:
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    raise CustomException(e.message)
__main__.CustomException: hi

Notice how traceback does not include calculate() function from line 9 which is the origin of original exception e.
Comment: `e.__class__.__name__` is this the same as `type(e).__name__`, as suggested by the answer above?
Comment: @information_interchange yes. The question and accepted answer content changed completely over time. It is shame other participants are not notified by SO machinery :(
Comment: If you want to store the traceback as a string, you can use `traceback.format_exc()` as well
Comment: thanks, that error chaining was new to me! Very useful for injecting a new message to HTTP errors.
Comment: Please use `except CustomException` directly and don't check type afterwards.
Comment: @DSchmidt "Don't do it" is not great answer to any question, please see how question is formulated.
Comment: @Alex I'm not answering any questions. I'm just commenting on the current state of this answer. Which uses `if e.__class__ == CustomException` instead of the much cleaner `except CustomException`.
Comment: @DSchmidt the question is: "what *type* of exception occurred?" this is the crux of the answer. If you use `except CustomException` there is no question what *type* of exception is it, because its hardcoded. The `.__class__` is what one learns from this answer.
Comment: @Alex and your first example answers that question reasonably well. Your other examples showing the raise and logging differences should showcase the correct `except` IMHO. People copy this.
Comment: @DSchmidt you are on point
Answer: You usually should not catch all possible exceptions with try: ... except as this is overly broad. Just catch those that are expected to happen for whatever reason. If you really must, for example if you want to find out more about some problem while debugging, you should do
try:
    ...
except Exception as ex:
    print ex # do whatever you want for debugging.
    raise    # re-raise exception.

Comment: The use of the word "never" here has never been so wrong. I use `try: ... except Exception:` around lots of things, e.g. usage of network dependent libraries, or a data masseuse that may get weird stuff sent to her. Naturally I have proper logging too. This is crucial to allow the program to continue operating in the case of a single mistake in input data.
Comment: It is perfectly reasonable to catch all exceptions. If you are calling a third-party library, you may not know what exceptions will be raised in that library. In such a case, the only recourse is to catch all the exceptions, for example to log them in a file.
Comment: Ever tried to catch all the exceptions that could be raised when sending a email using `smtplib`?
Comment: There may be some special cases where catching all exceptions is necessary, but on a general level you should just catch what you expect so you don't accidentally hide errors that you did not anticipate. Good logging is a good idea, too, of course.
Comment: Ok ok you're right, I'll rephrase my answer to make clear that there are valid use cases for a catch all.
Comment: Why is the re-raising necessary? To crash the program deliberately?
Comment: Because re-raising it will not hide the exception, you just want to print it out for debugging purposes before you continue the program unchanged.
Answer: Most answers point to except (…) as (…): syntax (rightly so) but at the same time nobody wants to talk about an elephant in the room, where the elephant is sys.exc_info() function.
From the documentation of sys module (emphasis mine):

This function returns a tuple of three values that give information
  about the exception that is currently being handled.
  (…)
  If no exception is being handled anywhere on the stack, a tuple
  containing three None values is returned. Otherwise, the values
  returned are (type, value, traceback). Their meaning is: type gets the
  type of the exception being handled (a subclass of BaseException);
  value gets the exception instance (an instance of the exception type);
  traceback gets a traceback object (see the Reference Manual) which
  encapsulates the call stack at the point where the exception
  originally occurred.

I think the sys.exc_info() could be treated as the most direct answer to the original question of How do I know what type of exception occurred?
Comment: That's the correct answer to me as it does solve the problem of what exception is occurring so what should I put instead of bare `except`. Just for the sake of completeness, `exctype, value = sys.exc_info()[:2]` will tell you the exception type which can then be used on the `except`.
Answer: These answers are fine for debugging, but for programmatically testing the exception, isinstance(e, SomeException) can be handy, as it tests for subclasses of SomeException too, so you can create functionality that applies to hierarchies of exceptions.
Answer: Unless somefunction is a very bad coded legacy function, you shouldn't need what you're asking.
Use multiple except clause to handle in different ways different exceptions:
try:
    someFunction()
except ValueError:
    # do something
except ZeroDivision:
    # do something else

The main point is that you shouldn't catch generic exception, but only the ones that you need to. I'm sure that you don't want to shadow unexpected errors or bugs.
Comment: If you are using a third-party library, you may not know what exceptions will be raised inside of it. How can you possibly catch all of them individually?
Answer: In Python 2, the following are useful
except Exception, exc:

    # This is how you get the type
    excType = exc.__class__.__name__

    # Here we are printing out information about the Exception
    print 'exception type', excType
    print 'exception msg', str(exc)

    # It's easy to reraise an exception with more information added to it
    msg = 'there was a problem with someFunction'
    raise Exception(msg + 'because of %s: %s' % (excType, exc))

Comment: -1 as using `exc.__class__.__name__` had been already suggested in Alex's answer – https://stackoverflow.com/a/9824060/95735
Answer: Use type class and as statement
try:#code
except Exception as e:
     m=type(e)
     #m is the class of the exception
     strm=str(m)
     #strm is the string of m

Answer: Hope this will help a little more
import sys
varExcepHandling, varExcepHandlingZer = 2, 0
try:
  print(varExcepHandling/varExcepHandlingZer)
except Exception as ex:
  print(sys.exc_info())

'sys.exc_info()' will return a tuple, if you only want the exception class name use 'sys.exc_info()[0]'
Note:- if you want to see all the exception classes just write dir(__builtin__)
Comment: only response one that answers the actual question
Answer: Here's how I'm handling my exceptions.  The idea is to do try solving the issue if that's easy, and later add a more desirable solution if possible.  Don't solve the issue in the code that generates the exception, or that code loses track of the original algorithm, which should be written to-the-point.  However, pass what data is needed to solve the issue, and return a lambda just in case you can't solve the problem outside of the code that generates it.
path = 'app.p'

def load():
    if os.path.exists(path):
        try:
            with open(path, 'rb') as file:
                data = file.read()
                inst = pickle.load(data)
        except Exception as e:
            inst = solve(e, 'load app data', easy=lambda: App(), path=path)()
    else:
        inst = App()
    inst.loadWidgets()

# e.g. A solver could search for app data if desc='load app data'
def solve(e, during, easy, **kwargs):
    class_name = e.__class__.__name__
    print(class_name + ': ' + str(e))
    print('\t during: ' + during)
    return easy

For now, since I don't want to think tangentially to my app's purpose, I haven't added any complicated solutions.  But in the future, when I know more about possible solutions (since the app is designed more), I could add in a dictionary of solutions indexed by during.
In the example shown, one solution might be to look for app data stored somewhere else, say if the 'app.p' file got deleted by mistake.
For now, since writing the exception handler is not a smart idea (we don't know the best ways to solve it yet, because the app design will evolve), we simply return the easy fix which is to act like we're running the app for the first time (in this case).
Answer: To add to Lauritz's answer, I created a decorator/wrapper for exception handling and the wrapper logs which type of exception occurred.
class general_function_handler(object):
    def __init__(self, func):
        self.func = func
    def __get__(self, obj, type=None):
        return self.__class__(self.func.__get__(obj, type))
    def __call__(self, *args, **kwargs):
        try:
            retval = self.func(*args, **kwargs)
        except Exception, e :
            logging.warning('Exception in %s' % self.func)
            template = "An exception of type {0} occured. Arguments:\n{1!r}"
            message = template.format(type(e).__name__, e.args)
            logging.exception(message)
            sys.exit(1) # exit on all exceptions for now
        return retval

This can be called on a class method or a standalone function with the decorator:
@general_function_handler
See my blog about for the full example: http://ryaneirwin.wordpress.com/2014/05/31/python-decorators-and-exception-handling/
Answer: I found this solution, may be it will help you:
try:
  t
except Exception as e:
  print(type(e))

Output:
<class 'NameError'>

Answer: You can start as Lauritz recommended, with:
except Exception as ex:

and then just to print ex like so:
try:
    #your try code here
except Exception as ex:
    print ex

Comment: sure: you can print the caught exception like this:
try:
    #your try code here
except Exception as ex:
    print ex

now the error will be printed
Comment: Can you elaborate a bit so your answer stands alone?
Answer: Your question is: "How can I see exactly what happened in the someFunction() that caused the exception to happen?"
It seems to me that you are not asking about how to handle unforeseen exceptions in production code (as many answers assumed), but how to find out what is causing a particular exception during development.
The easiest way is to use a debugger that can stop where the uncaught exception occurs, preferably not exiting, so that you can inspect the variables. For example, PyDev in the Eclipse open source IDE can do that. To enable that in Eclipse, open the Debug perspective, select Manage Python Exception Breakpoints in the Run menu, and check Suspend on uncaught exceptions.
Answer: The actual exception can be captured in the following way:
try:
    i = 1/0
except Exception as e:
    print e

You can learn more about exceptions from The Python Tutorial.
Answer: Use the below for both Exception type and Exception text
import sys
print(str(sys.exc_info()[0]).split(' ')[1].strip('>').strip("'")+"-"+(str(sys.exc_info()[1])))

if you want only exception type: Use -->
import sys
print(str(sys.exc_info()[0]).split(' ')[1].strip('>').strip("'"))

 Thanks Rajeshwar
Answer: Just refrain from catching the exception and the traceback that Python prints will tell you what exception occurred.


Unwieldy CvMat* in ANN using OpenCV

Question: I'm trying to use OpenCV to train a neural network in C++.
I can't convert between cv::Mat* (or Mat*, if namespace cv is used) to CvMat*, and I would appreciate some help with this.

Let me elaborate:
I've got two data structures of cv::Mat* type. The first is the set of feature vectors and the second is the set of expected output.
<code>   cv::Mat *feat = new cv::Mat(3000, 100, CV_32F, featureData);
   cv::Mat *op = new cv::Mat(3000, 2, CV_32F, expectedOutput);
</code>
(These are 3000 data points of feature vector length = 100 and output state = 2)
These two matrices had been populated with data of correct dimensions and seem to be working fine when sample data were printed on the console.
The neural network has been initialized as:
<code>   int layers_array[] = {100,200,2};    //hidden layer nodes = 200

   CvMat* layer = cvCreateMatHeader(1, 3, CV_32SC1);
   cvInitMatHeader(layer, 1,3,CV_32SC1, layers_array);

   CvANN_MLP nnetwork;
   nnetwork.create(layer, CvANN_MLP::SIGMOID_SYM, SIGMOID_ALPHA, SIGMOID_BETA);
</code>
Now, the train method of ANN is of the following template:
<code>   virtual int train( const CvMat* inputs, const CvMat* outputs,
                       const CvMat* sampleWeights, const CvMat* sampleIdx=0,
                       CvANN_MLP_TrainParams params = CvANN_MLP_TrainParams(),
                       int flags=0 );
</code>
I tried to convert between cv::Mat * and CvMat * using the following code:
<code>   CvMat featMat,opMat;

   (&featMat)->cols = feat->cols;
   (&featMat)->rows = feat->rows;
   (&featMat)->type = CV_32F;
   (&featMat)->data.fl = (float *)feat->data;

   (&opMat)->cols = op->cols;
   (&opMat)->rows = op->rows;
   (&opMat)->type = CV_32F;
   (&opMat)->data.fl = (float *)op->data;

   //setting up the ANN training parameters

   int iterations = network.train(&featMat, &opMat, NULL, NULL, trainingParams);
</code>
When I run this code, I get the following error message in my console:
<code>**OpenCV Error: Bad argument (input training data should be a floating-point matrix withthe number of rows equal to the number of training samples and the number
of columns equal to the size of 0-th (input) layer) in CvANN_MLP::prepare_to_train, file ..\..\OpenCV-2.3.0-win-src\OpenCV-2.3.0\modules\ml\src\ann_mlp.cpp,
line 694**
</code>
I understand the error message. However, to the best of my knowledge, I believe I haven't made a mess of the number of nodes in the input/output layer.
Can you please help me understand what is going wrong?
Comment: Well, your conversion code is wrong because you are trying to initialise an object that you haven't created. The dupe I pointed to shows you other ways to do that conversion. If you try the simple assignment shown in the accepted answer, does it work?
Comment: I'm not too familiar with the old C `CvMat` usage, but try setting `type` to `CV_32FC1` instead, although I think it's handled the same.
Comment: @chappjc: tried. not working.
Comment: possible duplicate of [convert cv::Mat to const CvMat\* or CvMat\*](http://stackoverflow.com/questions/11027574/convert-cvmat-to-const-cvmat-or-cvmat)
Comment: @RogerRowland: Not exactly. This is in continuation of the answer provided in http://stackoverflow.com/questions/11027574/convert-cvmat-to-const-cvmat-or-cvmat. The solution provided in that question has been considered here. Still, it doesn't seem to work. Which forms the crux of my question. So... possibly not a duplicate.
Comment: Moreover, the error message I'm seeing maybe more due to an improper implementation of ANN and less due to the pointer dynamics of cv::Mat. Unless the root cause is determined, it can't be confirmed as a duplicate.
Comment: Assignment is what I tried initially. It doesn't work.
Answer: please try to avoid pointers to cv::Mat as well as CvMat* in general.
luckily, there's an overload to CvANN_MLP::train that takes cv::Mat as args, so use that instead:
<code>   cv::Mat feat = cv::Mat(3000, 100, CV_32F, featureData);
   cv::Mat op = cv::Mat(3000, 2, CV_32F, expectedOutput);

   int layers_array[] = {100,200,2};    //hidden layer nodes = 200
   cv::Mat layers = cv::Mat (3, 1, CV_32SC1, layers_array );

   CvANN_MLP nnetwork;
   nnetwork.create(layers, CvANN_MLP::SIGMOID_SYM, SIGMOID_ALPHA, SIGMOID_BETA);

   int iterations = nnetwork.train(feat, op, cv::Mat(), cv::Mat(), CvANN_MLP_TrainParams());
</code>
Comment: Works like a charm! I didn't notice the overloaded method. Thanks a lot. :)

Unwieldy CvMat* in ANN using OpenCV


where not working with whereBetween in Laravel

Question: I have this booking table

start_date | end_date     |  status

<code>2020-12-15   2020-12-18    Active
2020-12-19   2020-12-22    Inactive
</code>
In this table booking data is getting saved,but i want to add where also with whereBetween to return those rows where status is Active. I have used below query but it is returning Inactive rows also.
<code> $available_start = date('Y-m-d', strtotime($request->start_date));
         $available_end = date('Y-m-d', strtotime($request->end_date));
         $checkData =Booking::whereBetween('start_date', [
            $available_start, $available_end
        ])->orwhereBetween('end_date', [
            $available_start, $available_end
        ])->where('status','Active')->get();
</code>
Any help is highly appreciated.
Answer: you must merge the 'whereBetween' in one where to get the expected results:
<code> $available_start = date('Y-m-d', strtotime($request->start_date));
        $available_end = date('Y-m-d', strtotime($request->end_date));
        $checkData =Booking:: where(function ($query)use($available_start, $available_end){
            $query-> whereBetween('start_date', [
                $available_start, $available_end
            ])->orwhereBetween('end_date', [
                $available_start, $available_end]);
        })
        ->where('status','Active')->get();
</code>


mod_rewrite all but root

Question: I am trying to craft a mod_rewrite conditions and rules so that all requests to a domain other than "/" are re-mapped to a new domain as they are, while requests to "/" are mapped to a particular path on the new domain.
For instance;
siteone.domain.com/some/great/path goes to
sitetwo.domain.com/some/great/path
while;
siteone.domain.com/ goes to
sitetwo.domain.com/some/other/path
The first part is easy, and although I've read several howto's on excluding particular directories or files from a mod_rewrite rule, I cannot get the second to work. All my attempts have ended up with;
siteone.domain.com/ goes to
sitetwo.domain.com/
Following is where I am at now. I am attempting to deal with requests to root first, then everything else;
RewriteCond %{REQUEST_URI} ^/$
RewriteRule http://sitetwo.domain.com/some/other/path [R=301]

RewriteCond %{HTTP_HOST} ^siteone\.domain\.com$
RewriteRule (.*) http://sitetwo.domain.com/$1 [R=301,L]

I'm sure I'm missing something basic, but am going around in circles now.
The logs look as if both rules are being processed. I had assumed it would stop at the first match.
... (2) init rewrite engine with requested uri /
... (3) applying pattern 'http://sitetwo.domain.com/some/other/path' to uri '/'
... (3) applying pattern '(.*)' to uri '/'
... (2) rewrite '/' -> 'http://sitetwo.domain.com/'
... (2) explicitly forcing redirect with http://sitetwo.domain.com/
... (1) escaping http://sitetwo.domain.com/ for redirect
... (1) redirect to http://sitetwo.domain.com/ [REDIRECT/301]

I guess what I'm needing is some sort of if/else statement? If the first condition maths do that rewrite, else move to the second condition and rule. Is that what I'm missing?
Comment: From what I am seeing in the log, it looks like both rules are being processed. I had assumed that if the first condition and rule matched, it would perform that. The logs make it look like both patterns are being applied, which then negates the effect I am looking for...
Comment: I have tried with and without the L in the first rule.
Answer: I seem to have stumbled across the problem, and as suspected it was something silly I was missing. Adding (.*) to the first RewriteRule seems to have resolved the issue.
So, instead of
RewriteCond %{REQUEST_URI} ^/$
RewriteRule http://sitetwo.domain.com/some/other/path [R=301,L]

I needed
RewriteCond %{REQUEST_URI} ^/$
RewriteRule (.*) http://sitetwo.domain.com/some/other/path [R=301,L]

mod_rewrite all but root


How to enable "persistent mode" in Windows failover cluster manager 2012?

Question: In Windows Server 2008 R2 there was a checkbox named "Enable persistent mode" on a General tab in the Properties of a cluster resource.
In Windows Server 2012 that seems to have disappeared.
My cluster resource is a "generic script" resource (not that it makes any difference).
How do I enable "persistent mode" for a cluster resource in Windows Server 2012?
Answer: Here has some PowerShell commands to do this, have you seen/tried these at all?

http://blog.crayon.no/blogs/janegil/archive/2011/06/03/enable_2D00_persistent_2D00_mode_2D00_for_2D00_cluster_2D00_resource_2D00_groups_2D00_using_2D00_the_2D00_powershell_2D00_failover_2D00_clustering_2D00_module.aspx
Answer: After further investigation it seems to me that 2012 either defaults to or is hard-coded to "persistent mode" and they've disabled changing the value with the GUI.

How to enable “persistent mode” in Windows failover cluster manager 2012?


How to crop the test properly using ellipsis

Question: I have a html like follows:

${name}

How to show the text as dotted if the text is bigger in size than the show area. ?
Answer: You have to add overflow: hidden for text-overflow:ellipsis to work – otherwise the content will just flow out of the element and not be cut off.
Answer: For text-overflow:ellipsis; to work, you need to specify overflow: hidden; and white-space: nowrap; as well.
i.e.
... style="width:80px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;" ...

BTW, i suggest you move out that inline style (and other inline styles) into a CSS file.
Answer: it should be :-

${name}


How to pass arguments to thread functions in Python

Question: I have raspberry pi where I am using python to create a small buzzer script. In the script if a condition becomes True, I need to print some information and also make buzzer sound. Buzzer sounds are made in two different format i.e. High and Low. In High, I have to run below code:
GPIO.output(BUZZER, 1)
time.sleep(5)
GPIO.output(BUZZER, 0)
GPIO.cleanup()

so that buzzer make continuous sound for 5 sec. In Low, I have to run below code:
for i in range(5):
    print(i)
    state = GPIO.input(BUZZER)
    print("state is {}".format(state))
    GPIO.output(BUZZER, 1)
    time.sleep(0.3)

    state = GPIO.input(BUZZER)
    print("state is {}".format(state))
    GPIO.output(BUZZER, 0)
    time.sleep(0.3)

It will make 5 beep sounds.
Below is the python script:
def generate_sound(tempo):
    if tempo == "High":
        GPIO.output(BUZZER, 1)
        time.sleep(5)
        GPIO.output(BUZZER, 0)
        GPIO.cleanup()
    else:
        for i in range(5):
            state = GPIO.input(BUZZER)
            print("state is {}".format(state))
            GPIO.output(BUZZER, 1)
            time.sleep(0.3)

            state = GPIO.input(BUZZER)
            print("state is {}".format(state))
            GPIO.output(BUZZER, 0)
            time.sleep(0.3)

if some_condition is True:
    generate_sound("High")
    print("This condition is True")
    print("Here is the information you need")
    print("Some more information")

else:
    generate_sound("Low")
    print("This condition is False")
    print("Here is the information you need")
    print("Some more information")

The above code is working fine but the problem is that I have to display information and generate sound at the same time. But with current approach, the sound is generated and waits for 5sec and then information is printed.
To resolve this I though of putting the generating sound function in a thread so that it can run parallel with printing information, something like below:
sound = Thread(target=generate_sound)

But here I am not sure how do I pass the values High and Low to generate sound function. I am not very expert in threading. Can anyone please give me some ideas. Please help. Thanks
Comment: Did you check the documentation? What problem did you encounter when trying to pass parameters?
Comment: Does this answer your question? [How can I use threading in Python?](https://stackoverflow.com/questions/2846653/how-can-i-use-threading-in-python)
Answer: Pardon; reflexive habit there. The threading library in particular provides a direct solution for you, so the workaround below the line is not necessary.
See the Thread documentation:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, \*, daemon=None)
[ ... ]
args is the argument tuple for the target invocation. Defaults to ().

So we can just provide the args as appropriate:
# Note the comma in `('High',)`; we want a 1-element tuple.
sound = Thread(target=generate_sound, args=('High',))

But here I am not sure how do I pass the values High and Low to generate sound function.

This doesn't depend on understanding threading; it's a general technique for these kinds of "callback" functions (any time that you pass a function as a parameter to something else, basically). For example, frequently you need this technique for buttons when making a GUI with tkinter (or other toolkits).
Bind the parameter to the call, for example using functools.partial from the standard library:
from functools import partial
sound = Thread(target=partial(generate_sound, 'High'))

Comment: Sorry, never mind that. Specifically for threading, there *is* a specific thing you're meant to do rather than this general-purpose hammer. Please see the update. Some other libraries do analogous things too. The first step should always be to read the documentation; even the best of us can forget things :)
Comment: What is the use of partial in here.?
Comment: It... does the thing that I said needs to be done. I have added a link to the relevant documentation.
Comment: Can the same code be used to get the return value from the thread function


Daemon continue working after SIGSEGV

Question: I have a daemon which works under Linux.
 Program received SIGSEGV signal but it did not stopped immediately, according to log time when it received SIGSEGV is - 01:11:45.085 and
time when it stopped to work is -  01:11:48.219
 It is multithreaded and on time SIGSEGV was generated it had like 25threads in it.
So, question is how the program managed to work additional 3 second, even though no mo actions were done from the thread which generated SIGSEGV  ?
Thanks.
Comment: Maybe `SIGSEGV` is caught or "ignored" and other threads where able to run a few more seconds... Anyway `SIGSEGV` is sent to the offending *thread* (but by default kill the entire process).
Answer: SIGSEGV will by default kill the process, but you can handle the signal, signal.h is the header in C, if you need to clean up files or communications before exiting for example. I made a short code example that does cause a SIGSEGV and handles it and does something afterwards, just an example, probably not a very good one.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

void sighandler( int signal);
int main(){
    signal(SIGSEGV,sighandler);
    int* a = NULL;
    a[0] = 5;
    return 0;
}

void cleanup(){
    // do neccesary cleanup
    sleep(3);
    exit(0);
}

void sighandler( int signal){
    if ( signal == SIGSEGV){
        printf("oups, sigsegv\n");
    } else {
        printf("some sig\n");
    }
    cleanup();
}

Comment: Warning: Signal handlers can call -directly or indirectly- a very  restricted set of functions. Read carefully [signal(7)](http://man7.org/linux/man-pages/man7/signal.7.html)
Comment: Indeed, you can't do arbitrary "cleanup" work from a signal handler. Instead, tell a thread about the signal (e.g. by setting a `sig_atomic_t` variable or writing to a pipe) and let the thread shut the program down cleanly.
Comment: Thanks for the list! I don't use signals often, mostly for my own amusement, but I never looked into what I am allowed to do.

Daemon continue working after SIGSEGV


clBuildProgram yields access violation (using Cloo)

Question: OpenCL 1.1, using Cloo 0.9.1.0.
For a certain CL module I get a crash at the following line:
program.Build(null, null, null, IntPtr.Zero);

Visual Studio 2010 tells me this:

An unhandled exception of type 'System.AccessViolationException'
  occurred in Cloo.dll
Additional information: Attempted to read or write protected memory.
  This is often an indication that other memory is corrupt.

I have trace the error to a certain line of code.
int offset = 1000000 * (input == 0); // This is the culprit!
const sampler_t smp = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;
int4 pixel = read_imagei(image, smp, (int2)(offset + x, y));

I'm using the trick above to avoid branching. It works perfectly in all but one situation where the above yields an access violation at compile-time. If I remove the conditional multiplication it works. E.g.
int offset = 1000000;
// -or-
int offset = (input != 0 ? 0 : 1000000);

Am I facing a compiler bug here? How do I work around this error?
Some details about my Graphics card/driver:

Driver Packaging Version: 18.104.22.168-110901a1-125827C-Fujitsu Technology
Solutions Provider: ATI Technologies Inc. 2D Driver Version: 8.01.01.1152
Comment: I think you won't avoid branching with that code, the branching will still be there after it's compiled.
Comment: Well, empirical testing shows that it is indeed a lot faster to use the trick above. Anyway, the problem is not the code itself. The problem is that the compiler bails out...
Comment: Have you tried running a kernel with only (int offset = 1000000 * (input == 0);)? If it runs fine, maybe your bug is in a different place..
Comment: Even if it runs fine it's no guarantee that the bug is somewhere else. Altering the code yields a new code tree to be optimized by the compiler, which could mean that the potential bug is avoided.
Answer: It's a compiler bug. Hopefully it will get fixed some day. For now, I will just avoid that specific optimization trick.


2 problems with group actions on a finite set.

Question: I've got two problems, which I can't solve on my own so I ask you to help me a little, with some tips :)

Prove, that every action of group ( order 9 ) on a set of 8 elements has a fixed point.
Show the action of $S_3$ group on set of 5  elements without fixed points.

How should I start?
I know, that :

$G$ - group of order = 9, $X$ - set of 8 elements

$x$ is fixed point, if $G(x) = \{x\}$, so $g(x) = x$ for every single $g \in G$
Answer: For 1, show that the size of each orbit is either 1 or 3. An orbit of size 1 is what you want to show exists. For 2, split the set of 5 elements into a set with 2 elements and a set with 3 elements.
Answer: By the orbit-stablizer theorem, the orbit size divides the order of the group, i.e. $|O(x)|=(G:G_x)$ for $x\in X$. Hence the size of the orbits $O(x)$ can be $1,3,9$. Now $X$ has $8$ elements, so we obtain $k\cdot 1+\ell \cdot 3=8$, which implies $k\ge 1$. Hence we have an orbit of size $1$.
More generally we have:
Theorem: Let $G$ be a finite $p$-group acting on a finite set $X$. Let $X^G$ denote the subset of $X$ consisting of those elements fixed by $G$. Then $|X^G| \equiv |X| \bmod p$; in particular, if $p \nmid |X|$,  then $G$ has a fixed point.


How to forward a specific log file in a syslog config?

Question: I just want to ask how can I log for example /var/log/test/test.log to a remote syslog-ng?
Im using syslog not rsyslog. I can do it in rsyslog but not in syslog.
Answer: Check the manual for your syslog version. Almost always you can forward the messages your systems generates via the syslog facility (which are normally written by syslog to local logfiles) to a remote syslog server, but not existing log files nor the files directly maintained by other services, that don't use a syslog facility.
In the syslog configuration file simply find the line that matches you existing log file e.g.:
<code> test.*               /var/log/test/test.log
</code>
and replace that by the ip-address of your remote server.
<code> test.*                @192.168.0.1
</code>
Many applications that by default maintain their own log files can be configured to use a syslog facility instead.
Comment: Hi HB, thanks for your quick response. I actually did that trick but still no luck. My syslogd version is 1.4.1 under old debian 5.


nginx try files subdirectory dont work

Question: I have configuration file where i am using root dir beyond public_html because i want to separate static files and php.
      root /home/user/domain;

       location / {
       try_files  /static/$uri /static/$uri/ /php/index.php?$args;
       }

       location ~ \.php$ {
       fastcgi_pass hiphop;
       include /etc/nginx/fastcgi.conf;
       try_files  /static/$uri /static/$uri/ /php/index.php?$args;
      }

where i am mistaking?
Comment: Are you seeing that `/static/$uri` is loading when you request a location where you want something else to load?
Answer: Your approach is flawed. For example, the /static/$uri/ causes an external redirect, which means that /static/ URIs will be presented to your server, that your config will attempt to resolve as /static/static/. The try_files in the PHP location is attempting to execute /static/ files as PHP scripts.
Have you considered using two root directives? Maybe:
root /home/user/domain/static;

location / {
    try_files $uri $uri/ /index.php?$args;
}

location ~ \.php$ {
    root /home/user/domain/php;
    try_files $uri /index.php?$args;
    fastcgi_pass hiphop;
    include /etc/nginx/fastcgi.conf;
}

nginx try files subdirectory dont work


C++ function converted to C# function

Question: I have this C++ function that I want to convert into C#.
// replace all occurences of a string with another string
void replace_all(string& s, const string& from, const string& to) {
    if(!from.empty()) {
        for(size_t pos = 0; (pos = s.find(from, pos) + 1); pos += to.size()) {
            s.replace(--pos, from.size(), to);
        }
    }
}

As specified in the comment, it replaces all occurences of a string with another string, in a given string.
As I have used some C++ functions to replace and find the string, I'm in need of help to convert that function into something that does the same thing in C#.
I am aware of the Regex and I have read a few topics, but could not make much sense of it.
Comment: how about `String.Replace`? This method can be used to replace string occurrence in the given string.
Comment: Does this help you along: https://stackoverflow.com/questions/7265315/replace-multiple-characters-in-a-c-sharp-string
Answer: If this is a function working on a small string, you could do something like this:
    const string s = "Write code in .Net.";
    Console.WriteLine(s);

    // We must assign the result to a variable.
    // ... Every instance is replaced.
    string v = s.Replace("Net", "Basket");
    Console.WriteLine(v);

If you want to work on the same string like in C++, use StringBuilder:
    const string s = "This is an example.";

    // Create new StringBuilder from string.
    StringBuilder b = new StringBuilder(s);
    Console.WriteLine(b);

    // Replace the first word.
    // ... The result doesn't need assignment.
    b.Replace("This", "Here");
    Console.WriteLine(b);

C++ function converted to C# function


Cast string to number, format; unless cannot be cast, then string=string

Question: The variable benefit.amount comes in as a String.
var amount = String()
if let tempAmount = benefit.amount as? NSDecimalNumber {
    amount = Formatter.currencyFormat(tempAmount)
} else {
    amount = tempAmount
}

All I am trying to do is if the benefit.amount is something like 1000, that I can use the currency formatter on it.  Sometimes though that variable may look something like Included in Policy Year Maximum Benefit, which clearly cannot be made into a number.
Please advise.
Answer: Just try to convert the value to Int. The initializer returns nil on failure.
let amount : String
if let tempAmount = Int(benefit.amount) {
    amount = Formatter.currencyFormat(tempAmount)
} else {
    amount = benefit.amount
}

Comment: If you try to convert an amount like "1.23" then the `Int` init method will fail. Using a `Float` is problematic because decimal numbers aren't stored well in the internal binary format and you often won't get the same value as what you started with. `NSDecimalNumber` is intended to store base-10 numbers accurately.
Answer: You have to use the init(string:) method and compare the result against NSDecimalNumber.notANumber():
let decimal = NSDecimalNumber(string: benefitAmount)
if decimal == NSDecimalNumber.notANumber() {
  // handle not a number
}
else {
  // handle the number
}


LINQ query .ToDictionary with Tuple int key

Question: I'm wondering if is it possible to do a linq query like this:
Dictionary<(int,int), object)> entity = _context.Table.ToDictionary((i => i.IDOrigin, i.IDDestiny), o => o);

I know that it's possible with an unique key .ToDictionay(i => i.Key, o => o.Value); but in this case this table has a double PK and I need both as keys.
Thank you.
Comment: Did you try it? What happened? Did you get an error?
Answer: You just need to tweak your call a bit:
_context.Table.ToDictionary(i => (i.IDOrigin, i.IDDestiny), o => o)

All I've moved is the brackets: you still want i as a regular lambda expression parameter, but you want the result of the lambda to be a tuple literal, which is the (i.IDOrigin, i.IDDestiny) part.
Note that the o => o part is unnecessary - if you don't specify a lambda expression for projecting from a source element to a value, ToDictionary uses the source element as the value. So you can use:
_context.Table.ToDictionary(i => (i.IDOrigin, i.IDDestiny))

Comment: Well, that's seems pretty logical now , I feel a bit silly now hahaha Thank you so much! Works perfectly


Trying to get COUNT(*) from custom content type with EntityFieldQuery

Question: How can I retrieve the 'count(*)' from a query in drupal 7?  The query needs to include a custom content type and a custom field.
Notes

Custom Content Type: employees
Custom Field Name: field_employees_email
As a note, I'm looking to add
WHERE field_employees_email = 'firstname.lastname@example.com'

to the query...
So far, I have something like:
$query = new EntityFieldQuery;

$result = $query
     ->entityCondition('entity_type', 'node')
     ->propertyCondition('status', 1) // Getting published nodes only.
     ->propertyCondition('type', 'employees') //Getting 'employees' type only.
     // How do I include custom field as part of query?
     ->execute();

Also, is there an easier way than
$total = count($result);

to return the COUNT(*) from the query?
Answer: You can use EntityFieldQuery::count(), as reported in the documentation for EntityFieldQuery::execute().

[The result is] Either a number if count() was called or an array of associative arrays of stub entities.

The code you should use is similar to the following one:
$query = new EntityFieldQuery;

$count = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'employees')
  ->propertyCondition('status', 1) // Getting published nodes only.
  ->count()
  ->execute();

To filter the result by the content type, you need to use EntityFieldQuery::entityCondition('bundle', $content_type).
For conditions on fields, you should use EntityFieldQuery::fieldCondition().
Comment: Thank you @kiamlaluno  fieldCondition is what I was looking for.  This post was pretty helpful for anyone else searching as well: http://commerceguys.com/blog/checking-out-entityfieldquery


How to learn steep functions using neural network?

Question: I am trying to use a neural network to learn the below function.  In total, I have 25 features and 19 outputs. The above image shows the distribution of two features with respect to one of the outputs. There are close to 200k examples, and the neural network contains 7 layers with 256 neurons having leaky relu as activation. The last layer is a linear layer.
The problem is that the output is too steep and the neural network has a large error on peaks. How can I modify the target variables or neural networks such that it makes a small mean absolute error on the peaks (basically flatten the below error plot)? Below is the error plot
Things which I have tried but have not worked-

Used log to transform target variables.
Increasing the size of the neural network with the hope that a large enough neural network will fit anything but the training loss is still large on peaks
Used mean absolute, mean squared and percentage loss
Comment: How do you know the correct (pink) function? // This would be more likely to get attention if you enlarged the pictures.
Answer: Some years ago, I spent a lot of time solving a similar problem.
Let me say that accurate function approximation with neural nets can be really hard.
First of all, in my experience, standard optimization methods used in deep learning (e.g., for image recognition and language modelling) are not very well-suited to this kind of problem, especially if the capacity of the network (number of neurons and layers) is not very large.
I would start by trying to reproduce the identity mapping with the algorithm you are currently using: take your 25 input features and use them as both input and output and see what happens. You might easily find that your training algorithm is not even able to accurately reproduce the identity mapping.
Another problem might be caused by multicollinearity in the outputs, which can seriously impair the convergence properties of the training algorithm (basically, you have ill-conditioned matrices somewhere in the net). Try to train a separate network for each of the 19 outputs and see what happens.
Try custom parameter updating rules. The one that worked best for me was parameter update = -sign(gradient) * indicator(gradient and momentum have the same sign). I found this in a paper that tried thousands of rules. This rule was the best one. Updating only one layer per iteration may also help.
Increase the batch size as the loss decreases. With your problem, I would say, start from 50 and increase to something around 10000 in the end.
Decrease the learning rate as the loss decreases.


Blazor rendering content twice

Question: I've tried different ways to prevent this from happening.
After changing to render-mode="Server" I was able to prevent rendering twice on the first load.
But now when I refresh the page it still doubles the amount of elements.
Here is what I've got

    @if (Items != null)
    {
        @foreach (var item in Items )
        {
            <ItemComponent Item="@item" />
        }
    }

@code {

    [Inject]
    private IItemService ItemService { get; set; }
    List<ItemViewModel> Items { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Items = await ItemService.GetItemsAsync();
        base.OnInitialized();
    }
}

I've read over the Stateful reconnection after prerendering section and it doesn't seem to work for me.
Comment: "when I refresh the page it still doubles the amount of elements"?? Are you saying that `Items` contains everything twice and thus `foreach` doubles up on `ItemComponent`?  Is so check 'GetItemsAsync. ' Also note that when the Blazor Server SPA first loads it calls the page twice - the first time to statically render the page on the server, then a second time when the client side Blazor code calls back to the Blazor Hub to get a fully wired up page.
Answer: For me it was that this script was duplicated on _Hosts.cshtml

After deleting one of them problem was solved.
Answer: In case of Blazor Server, modifying _Host.cshtml solved this for me:
before
<component type="typeof(App)" render-mode="ServerPrerendered" />

after
<component type="typeof(App)" render-mode="Server" />

Comment: in this mode, you lost the content for SEO.
Answer: For anyone else who is hitting this "loading twice" with .Net 8 and "AutoRender" mode.  I found this post to be valuable:
https://jonhilton.net/persist-state-between-renders-net8/#:~:text=Chances%20are%20it's%20down%20to,show%20something%20nice%20and%20quickly.

By default in .NET 8 your interactive components are rendered twice:
Once on the server (prerendering), where HTML is returned so the
browser can show something nice and quickly.
Then your component will be rendered again using your preferred
interactive render mode (server or WASM).
The problem is, if you're fetching data in your component, it's going
to be fetched for both renders.
You can often see this in the UI, with a visible flash as the
prerendered content is replaced with the "new data" when your
component is rendered for a second time.
So what to do about it? Turns out there are two main options at your
disposal:
Disable prerendering Persist state between the first and second
renders
Answer: Turns out in a further down stream service where I've added to the list, I wasn't creating an empty list to begin with.
Thanks for assisting.
Comment: NP. `OnInitializedAsync` is the correct place for your code. Could you please tick off the question as answered?
Answer: Don't override OnInitialized
Use OnAfterRender or OnAfterRenderAsync

protected override async Task OnAfterRenderAsync(bool firstRender)

With firstRender you get the info.
You can also use our own mecanism to avoid loading your context more than one time.
If needed call StateHasChanged to update the DOM.
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-5.0
EDIT
The easiest way to solve this problem is to use browser localstorage. You can save user id and then get it back in case of a refresh.
If a user press F5 to refresh the page, blazor will create a new circuit and there is no easy solution on the server side.
Comment: That still doesn't work, perhaps you can write the code from what I've shown you and I will test it.
Comment: Look at localstorage and see my answer edit.

Blazor rendering content twice


Finding the range of $|\sin (x)|+|\cos (x)|$ by considering each quadrant as a separate case

Question: I was given  homework on trigonometric range and here is the question that I was stuck in.

Find the range of the function
$$|\sin (x)|+|\cos (x)|$$

In my attempt I knew that it can be solved by taking $4$ cases of $4$ quadrants. But my answer doesn't match. My teacher tell me the solution by squaring.
I need a solution that involve taking cases. I am a beginner in trigonometry so please help.
Comment: You say you got an answer but it "didn't match". Step by step, show us how you got your answer. Someone then could confirm you are correct or show you where you went wrong. Also, what was the other answer that disagreed with yours?
Comment: Show, don't tell. You showed your four cases, but you only told about the rest of the steps. Also, your work should be **in the question**, not in a comment below the question.
Comment: Here's how you can write math formulas so they display well on this site: http://math.stackexchange.com/help/notation
Comment: I just make 4 cases, case 1 x ∈ [0 , π/2] case 2 x ∈ [π/2 , π] case 3 x ∈ [π , 3π/2] and case 4 x ∈ [3π/2 , 2π] in all 4 case cos(x) and sin(x) have different signs by applying astc rule I found different intervals and then take intersection of them. Is my way correct??
Answer: There is a geometric way to handle the four cases. It involves equations like Equation $(1)$ below:
$$ \lvert x \rvert + \lvert y \rvert = r. $$
If you set $r$ to some constant value and plot the solutions of Equation $(1)$ you get a figure like the one below, a square whose sides make $45$-degree angles with the axes:

This particular square is the graph of $\lvert x \rvert + \lvert y \rvert = r$ where
$r = 4.$
The nice thing about this square is it represents four cases all at once.
The side in the first quadrant shows what the solutions of
$\lvert x \rvert + \lvert y \rvert = r$ are for $x > 0$ and $y > 0,$
the side in the second quadrant shows what the solutions are for $x < 0$ and $y > 0,$
and so forth for the third and fourth quadrants.
Now let's consider what happens if we plot the following parametric equations,
using the parameter $\theta$:
\begin{align}
x &= \cos(\theta), \\
y &= \sin(\theta).
\end{align}
We get a circle of radius $1$ with center at $(0,0),$ of course.
Now let's see what happens if we inscribe a square within the circle and circumscribe another square around the circle as shown in the figure below:

The squares are graphs of $\lvert x \rvert + \lvert y \rvert = r$
for two different constant values of $r.$
Note that the circle cannot touch the plot of
$\lvert x \rvert + \lvert y \rvert = r$ for any $r$ smaller than the
$r$ value used for the small square.
That is, you cannot have any smaller sum of
$\lvert x \rvert + \lvert y \rvert
 = \lvert\cos(\theta)\rvert + \lvert\sin(\theta)\rvert.$
The circle also cannot touch the plot of
$\lvert x \rvert + \lvert y \rvert = r$ for any $r$ larger than the
$r$ value used for the large square.
That is, you cannot have any larger sum of
$\lvert\cos(\theta)\rvert + \lvert\sin(\theta)\rvert.$
But the sum $\lvert\cos(\theta)\rvert + \lvert\sin(\theta)\rvert$ can be equal to the $r$ value of either square because the circle touches both squares.
So if you can just figure out what $r$ is for each of these squares, you have the smallest and largest possible values of
$\lvert\cos(\theta)\rvert + \lvert\sin(\theta)\rvert.$
These are also the smallest and largest values of
$\lvert\cos(x)\rvert + \lvert\sin(x)\rvert.$
Answer: Let $f(x)=|\sin x|+|\cos x|$ then the first thing we can say is that $f(x)>0$ and the second thing is that $f(x)<2$ since $|\sin|$ and $|\cos|$ are both between 0 and 1 and are never both equal to 0 or both equal to 1.
In the first quadrant, $0\leq x \leq \pi/2$, $|\sin x|=\sin x$ and $|\cos x|=\cos x$ so $f(x)=\sin x+\cos x$. You say your teacher got the answer by squaring, so let's do that.
$$
\begin{align}
f(x)^2&=\sin^2x+2\sin x\cos x+\cos^2 x\\
&=1+2\sin x \cos x
\end{align}
$$
using $\sin^2 x+\cos^2 x=1$. Now use $\sin 2x=2\sin x\cos x$ to get
$$
f(x)^2=1+\sin 2 x
$$
So the maximum value this may attain is 2, when $2x=\pi/2$, and so $f(x)^2=2$ and $f(x)=\sqrt 2$, and the minimum is $f(x)^2=1$ when $x=0$ and so $\sin (2x)=0$, so $f(x)=\sqrt1=1$. So the minimum and maximum on the first quadrant are 1 and $\sqrt2$ respectively.
Hopefully you can fill this argument in with the values from the other quadrants.


Tensorflow fit, can you set weights/bias on specific elements in train data?

Question: Let's assume I feed my TF model a 3D array
e.x. with the input_shape = (3,3)
X_data =      [ [[3,4,-1] , [2,2,-8] , [4,7,0]] ,
                [[...] , [...] , [5,10,-15]] ,
                 ... ]

tf.fit() function has an argument class_weight, but from examples I have seen, that it only separates the weights between output labels ( in my case 0 or 1 ) in Y_data = [ 0, 1, 1 ...], thus to make more notice to one, or the other output.
But what I need is for training func. to make more notice to some data in the input.
e.x. in the X_data, I want training function to consider and be more biased about the last array in 2D array in the train data => [4,7,0], [5,10,-15] and so on.
Or, e.x. To consider and be more biased about the first element in each of the arrays => 3, 2 and 4 and so on.
Is that possible?
Answer: You should use a custom loss function to do that:
loss = 0.6 * loss(a[0]) + 0.2 * loss(a[1]) + 0.2 * loss(a[2])

Try something like this formula.


Utilizando multi linguagem em Wordpress

Question: Estou desenvolvendo um site em Wordpress, e preciso que alguns conteúdos no site (menus, fotos e etc) estejam em 3 línguas diferentes.
Como é possível fazer isso sem precisar criar um novo Wordpress para cada língua?
Comment: Você está procurando por internacionalização. Dei uma resposta detalhada sobre isso [aqui](http://pt.stackoverflow.com/a/95562/23051)
Comment: @CaioFelipePereira Não quero só traduzir, para isso eu editaria o .po do template. Quero ter páginas diferentes para línguas diferentes.
Answer: Desconheço qualquer função nativa do wordpress que trabalhe com multi-linguagem, e quando preciso utilizo duas maneiras, dependendo do que o trabalho pede.
Recomendo que utilize o plugin ACF para conteúdos gerenciáveis ele ira facilitar tua vida, alem de ser bem documentado a abrangência dele também é boa mesmo em versão gratuita. Para o método I utilizarei ele como referência, porém caso não queria utilizar você pode usar as funções nativa do wordpress, para criação de campos chegando ao mesmo resultado.

Para capturar a língua atual, selecionada pelo usuário utilizo o seguinte código em ambos os métodos:

    <?php
        $lang = $_COOKIE['lang'];
        if ($lang == 'en'):
            $flag_1 = 'es';
            $flag_2 = 'pt-br';
        elseif ($lang == 'es'):
            $flag_1 = 'pt-br';
            $flag_2 = 'en';
        else:
            $flag_1 = 'en';
            $flag_2 = 'es';
        endif;
    ?>

        <form method="post" action="">
            <input name="lang" type="hidden" value="<?php echo $flag_1; ?>" aria-hidden="true">
            <input name="redirect" type="hidden" value="<?php echo $_SERVER['REQUEST_URI']; ?>" aria-hidden="true">
            <input type="submit" role="button" value="<?php echo $flag_1; ?>">
        </form>

        <form method="post" action="">
            <input name="lang" type="hidden" value="<?php echo $flag_2; ?>" aria-hidden="true">
            <input name="redirect" type="hidden" value="<?php echo $_SERVER['REQUEST_URI']; ?>" aria-hidden="true">
            <input type="submit" role="button" value="<?php echo $flag_2; ?>">
        </form>

Sim, utilizo dois <form>! Nesse exemplo, há 3 línguas: Português, Inglês e Espanhol, onde apos capturar a língua selecionada cada um dos <form> recebe uma das línguas não selecionada, podendo ser trocada futuramente.
Dentro do functions.php insiro o seguinte código:
if (!isset($_COOKIE['lang'])) {
    setcookie('lang', 'pt-br', (time() + (3 * 24 * 3600)), '/');
    wp_redirect(site_url());
    die;
}
if (isset($_POST['lang'])) {
    setcookie('lang', $_POST['lang'], (time() + (3 * 24 * 3600)), '/');
    /*Rede
    wp_redirect(site_url($_POST['redirect']));*/
    //local
    wp_redirect(site_url());
    die;

}
Nada demais, apenas atribuo o valor vindo do post para um Cookie.

Método I:
Nessa forma duplica-se os campos de conteúdos dentro de uma mesma pagina utilizando sempre a mesma URL.
Por exemplo, utilizando o ACF crio dentro da pagina "exemplo" três campos, "conteudo_br", "conteudo_es" e "conteudo_en", os quais se referem ao mesmo campo, porém cada um é responsável pelo conteúdo em cada linguagem.
No código faço a seguinte verificação:
<?php
    if ( $_COOKIE['lang'] == "en"):
        $conteudo = get_field('conteudo_en');
    elseif ($_COOKIE['lang'] == "es"):
        $conteudo = get_field('conteudo_es');
    else:
        $conteudo = get_field('conteudo_br');
    endif;
?>

Título do conteúdo

    <?php echo $conteudo; ?>

Através do if atribuo a variável $conteúdo o campo da língua atual, verificando o Cookie.
Vantagem desse método:
Crio apenas um menu, pois a pagina lincada sera sempre a mesma.
Desvantagem:
Para SEO, a página sempre terá o mesmo nome, por exemplo a página de contato, será sempre "www.meudominio.com/contato" e não terá um "/contact" por exemplo para a língua inglesa.
Método II:
Você pode duplicar as paginas, onde  você não precisaria criar "conteudo_br", "conteudo_es" e "conteudo_en", basta apenas criar um campo, por exemplo "conteudo" e atribuir o mesmo as três paginas (inglês, espanhol e português), onde cada uma fica com o respectivo conteúdo da linguagem.
No código você apenas teria que verificar a linguagem atual do cookie e trocar o link dos menus ao invés do conteúdo em si como o método I sugere.
Exemplo:
<?php
    if ($_COOKIE['lang'] == 'en'):
        $item_1 = 'contact';
    elseif ($_COOKIE['lang'] == 'es'):
        $item_1 = 'contacto';
    else:
        $item_1 = 'contato';
    endif;
?>
<a href="<?php bloginfo('url'); echo '/'.$item_1; ?>"><?php echo $item_1; ?>

Acima o código seleciona o href atribuindo ao $item_1 dependendo do Cookie.
Vantagem desse método:
O conteúdo fica mais fácil de ser gerenciável pois a quantidade de campos por paginas é menor.
Em relação ao SEO, cada pagina terá sua devida URL em cada linguagem.
Desvantagem:
Em sites que possuem muitas paginas, esse modelo pode gerar um acumulo excessivo de páginas, pois para cada página serão criadas 3, uma para cada língua.

Enfim, analise o que seu trabalho necessita e utilize a forma que melhor te se adeque.
Também se preferir você pode utilizar algum plugin que faça todo esse trabalho por você, podendo conferir alguns na página de plugins do wordpress.
Se mesmo apos o passo a passo você estiver com dificuldades, sugiro que você replique o conteúdo para três subdomínios como es.site.com, en.site.com e site.com ... Por mais que eu não recomende esse método, devido a duplicidade de conteúdo, ele também é valido.
Comment: Entendi, mas como eu faria para que um menu exista somente em uma linguagem e nas outras ele não exista? Seria um `display: none` ou alguma coisa do tipo? O primeiro código eu não entendi muito bem, onde você colocaria ele? No index?
Comment: Você citou que existe plugin's que fazem esse processo, mas saberia dizer se há algum que segue essa sua mesma logica?
Comment: @GiovanniBernini, em relação a linguagem você pode simplesmente inserir o código HTML entre os "if" do php, e então ele sera mostrando apenas naquela determinada lingua, pois com display none seria um tanto gambiarra. Em relação ao primeiro código vai do bom senso, eu geralmente coloco dentro da header ou do nav como é algo que o usuário pode mudar a qualquer momento.
Comment: Plugins são um tanto limitados, por isso escrevi esse texto gigante para que você possa fazer no "braço" já que é algo bem especifico e não conheço nenhum plugin que faça isso de maneira satisfatória.
Comment: Entendi, mas vou ter que bater um pouco a cabeça para fazer, pois eu uso WP faz pouco tempo, resolvi migrar do Joomla! no projeto errado, rsrsrs. Fico com duvida nessa parte de chamar as páginas. A página `conteudo`, que carregará o código para chamar as páginas com a linguagem correta? Mas o que seria um "campo" é uma outra página? Eu criaria uma página "contatoconteudo" e mais 3 páginas por língua, e na página "contatoconteudo" estará o código do seu ultimo exemplo? Essa página "contatoconteudo" seria uma redirecionadora?
Comment: Fazer 3 Wordpress diferentes em subdominios, não seria uma solução boa né? (site.com, es.site.com, br.site.com). Queria ter essa diferença entre as línguas, na url. Mas acredito que um "site.com/pt-br/" seria mais fácil.
Comment: Um campo seria um campo, por exemplo o editor de texto é um campo, o titulo é um campo os quais você consegue acessar via the_algumacoisa(), com o ACF você consegue criar campos personalizados mais facilmente que a forma nativa de wordpress, de uma lida minima sobre e você era entender é bem facil!
Comment: Talvez seja @giovanniBernini, se você estiver com dificuldade para entender o passo a passo a melhor maneira seria mesmo fazer um subdominio para cada linguagem, porem eu já tive problemas de redirecionamento por causa de subdominios, mas você pode tentar, também é uma alternativa valida!
Comment: Acho que eu acabei me entendendo aqui, esse trecho de código que você deu como exemplo no método 2, ele teria de existir nas 3 páginas? Onde eu estou me complicando é nisso, onde que esse ultimo código ficaria? Eu atualmente já tenho as páginas para cada língua montada, então acredito que esse método 2 séria melhor e mais fácil. Não sei se consegui explicar a minha duvida dessa vez mais claramente, mas agradeço pela ajuda!!
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/31374/discussion-between-rafael-kendrik-and-giovanni-bernini).
Answer: Tenta esse plugin, ele tem vários idiomas
https://wordpress.org/plugins/google-language-translator/
Comment: Mas será que com esse eu consigo editar algumas coisas como os exemplos que eu citei? Ou será só para traduzir os posts.

Utilizando multi linguagem em Wordpress


Induction: Bounds on sum of inverses of first $n$ square roots

Question: I am trying to show by induction that $2(\sqrt{n}-1)<1+\dfrac{1}{\sqrt{2}}+\cdots+\dfrac{1}{\sqrt{n}}<2\sqrt{n}$.
For the upper bound, I have that if $1+\dfrac{1}{\sqrt{2}}+\cdots+\dfrac{1}{\sqrt{n}}<2\sqrt{n}$, then $1+\dfrac{1}{\sqrt{2}}+\cdots+\dfrac{1}{\sqrt{n}}+\dfrac{1}{\sqrt{n+1}}<2\sqrt{n}+\dfrac{1}{\sqrt{n+1}}=$
$2\sqrt{n}+\dfrac{2}{2\sqrt{n+1}}<2\sqrt{n}+\dfrac{2}{\sqrt{n}+\sqrt{n+1}}=2\sqrt{n}+2(\sqrt{n+1}-\sqrt{n})=2\sqrt{n+1}$.
However, despite hours of trying, I cannot figure out how to show that $2(\sqrt{n+1}-1)<1+\dfrac{1}{\sqrt{2}}+\cdots+\dfrac{1}{\sqrt{n}}+\dfrac{1}{\sqrt{n+1}}$.
Answer: Observe that: $\dfrac{1}{2\sqrt{k}}> \dfrac{1}{\sqrt{k+1}+\sqrt{k}}= \sqrt{k+1}-\sqrt{k}$. Taking summation for $k$ from $1$ to $n$ and get:
$\dfrac{S_n}{2} > \displaystyle \sum_{k=1}^n\left(\sqrt{k+1} - \sqrt{k}\right)= \sqrt{n+1}-1\implies S_n > 2\left(\sqrt{n+1}-1\right)> 2\left(\sqrt{n}-1\right)$ as claimed.
Answer: $$\begin{array}{cl}
& 1+\dfrac{1}{\sqrt{2}}+\cdots+\dfrac{1}{\sqrt{n}} \\
>& \dfrac2{1+\sqrt2}+\dfrac{2}{\sqrt{2}+\sqrt3}+\cdots+\dfrac{2}{\sqrt{n}+\sqrt{n+1}} \\
=& \dfrac{2(\sqrt2-1)}{(\sqrt2+1)(\sqrt2-1)}+\dfrac{2(\sqrt3-\sqrt2)}{(\sqrt{3}+\sqrt2)(\sqrt3-\sqrt2)}+\cdots+\dfrac{2(\sqrt{n+1}-\sqrt n)}{(\sqrt{n+1}+\sqrt{n})(\sqrt{n+1}-\sqrt n)}  \\
=& 2(\sqrt2-1)+2(\sqrt3-\sqrt2)+\cdots+2(\sqrt{n+1}-\sqrt n) \\
=& 2\sqrt{n+1}-2 \\
\end{array}$$
Answer: Try to use the induction method for $2(\sqrt{n}-1+\frac{1}{\sqrt{n}}) < \frac{1}{\sqrt{1}} +  \frac{1}{\sqrt{2}} + \cdots + \frac{1}{\sqrt{n}}$
Check it for base cases like $n=1,2,3,4,5,6,7,8,9,10$ and it will fail for all $n=1,2,3,4,5,6,7$ and will hold for $n=8,9,10$.
Induction step : assume that $2(\sqrt{n}-1+\frac{1}{\sqrt{n}}) < \frac{1}{\sqrt{1}} +  \frac{1}{\sqrt{2}} + \cdots + \frac{1}{\sqrt{n}}$ is true for the number $n$.
Proving step : we need to prove that $2(\sqrt{n+1}-1+\frac{1}{\sqrt{n+1}}) < \frac{1}{\sqrt{1}} +  \frac{1}{\sqrt{2}} + \cdots + \frac{1}{\sqrt{n}}+\frac{1}{\sqrt{n+1}}$
From the induction step we know that $2(\sqrt{n}-1+\frac{1}{\sqrt{n}}) < \frac{1}{\sqrt{1}} +  \frac{1}{\sqrt{2}} + \cdots + \frac{1}{\sqrt{n}}$ thus replacing $ \frac{1}{\sqrt{1}} +  \frac{1}{\sqrt{2}} + \cdots + \frac{1}{\sqrt{n}}$ with $2(\sqrt{n}-1+\frac{1}{\sqrt{n}})$ will strengthen the inequality.
We arrive at $2(\sqrt{n+1}-1+\frac{1}{\sqrt{n+1}}) < 2(\sqrt{n}-1+\frac{1}{\sqrt{n}})+\frac{1}{\sqrt{n+1}}$, (i will leave this for you to prove).
Now since its obvious that $2(\sqrt{n}-1+\frac{1}{\sqrt{n}}) > 2(\sqrt{n}-1)$ then the inequality $2(\sqrt{n}-1) < \frac{1}{\sqrt{1}} +  \frac{1}{\sqrt{2}} + \cdots + \frac{1}{\sqrt{n}}$ will be a corollary to this induction proof.
you just have to check basic cases for $2(\sqrt{n}-1) < \frac{1}{\sqrt{1}} +  \frac{1}{\sqrt{2}} + \cdots + \frac{1}{\sqrt{n}}$ which are $n=1,2,3,4,5,6,7$ and thus completing the proof.
Answer: Note: I can see that there are already fine answers using induction!
An ad in favor of graph paper. The outcome of the standard sum/integral comparison is
$$  2 \sqrt {n+1} - 2 \;  < \; 1  + \frac{1}{\sqrt 2 }  + \frac{1}{\sqrt 3 } + \cdots + \frac{1}{\sqrt n } \; < \; 2 \sqrt n - 1 $$


Find probability in card question

Question: Suppose that a test for extrasensory perception consists
of naming (in any order) $3$ cards randomly drawn from
a deck of $13$ cards. Find the probability that by chance
alone, the person will correctly name (a) no cards, (b) $1$
card.
this is what I got
a) $f(0)= \left( \begin{array}{ccc}
3  \\
0  \\
 \end{array} \right)   (10/13)^3= 45.5$%
b)$f(1)= \left( \begin{array}{ccc}
3  \\
1  \\
 \end{array} \right) (3/13)  (10/13)^2=40.96$%
but the book says a) $42$% and b $47.2$%. I really need to understand this. So would anyone please show me where I am wrong.
Comment: 1) are they drawn w/replacement? 2) are all cards unique?
Comment: The three picks are not identical trials so the binomial formula doesn't apply (it would apply if you picked with replacement).
Comment: The person knows which cards are 13 cards in the deck? Or is randomly selected package of 32 cards a person does not know is?
Answer: A) Assuming that each card is unique:

The number of different ways to pick $3$ cards out of all $13$ cards is $\binom{13}{3}=286$
The number of different ways to pick $3$ cards out of the $10$ cards not drawn is $\binom{10}{3}=120$
So the probability that a person will name $0$ cards correctly is $\displaystyle\frac{120}{286}=41.9\%$

B) Assuming that each card is unique:

The number of different ways to pick $3$ cards out of all $13$ cards is $\binom{13}{3}=286$
The number of different ways to pick $2$ cards out of the $10$ cards not drawn is $\binom{10}{2}=45$
The number of different ways to pick $1$ card out of the $3$ cards drawn is $\binom{3}{1}=3$
So the probability that a person will name $1$ card correctly is $\displaystyle\frac{45\cdot3}{286}=47.2\%$
Answer: Assuming the cards are drawn without replacement and are each uniques, Barak's answer is correct for part (a). Diane's answers are right if the cards are drawn with replacement.
The book obviously meant the cards are drawn without replacement.
For part (b) the answer is
$$
\binom{3}{1} \frac{3}{13} \frac{10}{12} \frac{9}{11} = \frac{135}{286}
$$
which is 47.2%.
(Barak's method is superior but I gave a more step-by-step way to reach the same number because Barak already showed the couning-cases way.)

Find probability in card question