Have I found a counterexample that invalidates a proof on the convergence of a sequence?

Question: I am not sure of the validity of a proof I read about the convergence of sequences in certain space. Let $X$ be the set of all bounded or unbounded sequences of complex numbers with distance
$$d(x,y) = \sum_{j=1}^{\infty}\frac{1}{2^j}\frac{|\zeta_j - \eta_j|}{1+|\zeta_j - \eta_j|}.$$
Claim: We have that the sequence $(\zeta^{(n)}_j) = x_n \to x = (\zeta_j)$ iff $\zeta^{(n)}_j \to \zeta_j$ for all $j = 1, 2, \dots$.
To prove it, first suppose that $x_n \to x$ and fix $j$. We have $$\frac{|\zeta^{(n)}_j - \zeta_j|}{1+|\zeta^{(n)}_j - \zeta_j|} \le 2^j \cdot d(x_n,x) \to 0,$$
as $n \to \infty$. Therefore, for $\epsilon > 0$ sufficiently small it holds that for $n$ large enough that
$$|\zeta^{(n)}_j - \zeta_j| < (1+|\zeta^{(n)}_j - \zeta_j|)\epsilon,$$
which implies that
$$|\zeta^{(n)}_j - \zeta_j| < \frac{\epsilon}{1-\epsilon} < 2\epsilon,$$
and hence $\zeta^{(n)}_j \to \zeta_j$ for all $j$.
But for convergence of a sequence, we require that for all $\epsilon > 0$, there exists $N \in \mathbb{N}$ such that $|\zeta^{(n)}_j - \zeta_j| < \epsilon$ when $n \ge N$, not just when "$\epsilon > 0$ is sufficiently small".
For example, if I take $\epsilon$ slightly smaller than $1$ then $$|\zeta^{(n)}_j - \zeta_j| < \frac{\epsilon}{1-\epsilon} < 2\epsilon,$$
certainly doesn't hold.
So how can this proof be valid when the expression doesn't hold for all $\epsilon >0$?
This proof is from page $2$, problem 3 of these notes.
Comment: Given $\varepsilon > 0$, pick an $N(\varepsilon)$ such that $\lvert \zeta_j^{(n)} - \zeta_j\rvert < \min \bigl\{\frac{1}{3}, \varepsilon\bigr\}$ for $n \geqslant N(\varepsilon)$.
Comment: A general principle is that in the definition of limit, one can restrict $\epsilon$ to any interval $(0,\epsilon_0)$ without changing the definition. That is, the conditions $$\forall\epsilon>0\quad\exists N\quad \forall n\geqslant N\quad d(x_n,x)\leqslant\epsilon$$ and $$\forall\epsilon\in(0,\epsilon_0)\quad\exists N\quad \forall n\geqslant N\quad d(x_n,x)\leqslant\epsilon$$ are **strictly equivalent**.
Comment: Sure, the implication from $\forall\epsilon$ to $\forall\epsilon<\epsilon_0$ is trivial. For the other implication, assume the second property holds and note $N_0$ some $N$ given by the second property for $\epsilon=\frac12\epsilon_0$, then use $N_0$ to show that the first property holds for every $\epsilon\geqslant\epsilon_0$ as well.
Comment: @DanielFischer Where are you getting $\text{min}\{\frac{1}{3},\epsilon\}$ from? How does this help with my counterexample which shows the proof doesn't hold if $\epsilon$ is slightly smaller than 1?
Comment: @Did That's a very nice property. Is there a simple way to show that this holds?
Comment: @Did Ok so if we assume the second property holds and there exists $N_0$ such that $d(x_n,x) < \epsilon \in (0, \epsilon_0)$ for all $n \ge N_0$ then for any $\gamma > \epsilon_0$ we have $d(x_n,x) < \epsilon < \gamma$ for $n \ge N_0$. Why did you use $\epsilon = \frac{1}{2} \epsilon_0$?
Comment: To guarantee to have some $\epsilon<\epsilon_0$.
Answer: Note that $N$ that "works" for $\epsilon$ also works for $\epsilon'$ if $\epsilon'>\epsilon$. Therefore, it indeed suffices to consider only "sufficiently small" $\epsilon$.


samba+openldap vs ad for medium size network

Question: We are going to have an organized network with an NT user authentication and proxy server. In choosing between Active Directory and Samba Server, I wanted to choose Samba server (I do love Open Source ). Our plan has a Forest (root : [domainname]) and trees for sub-domains (like: eng.[domainname], maybe with some children) and maybe for internet site (Sites where users just use Internet) we may have a new forest (we should have trust between these domains). In every site we should have DC and Squid Proxy server (for control and traffic shaping the internet in the with high performance) .
All of our clients are using Win XP or Seven.
And we are also going to use MOSS 2007.
The problem are:
- Can we completely handle our plan with Samba server? ,with replication and trusts? ,what should we do? Should we use OpenLDAP for our plan? What do you suggest for ? Which distribution of Linux do you recommend for our plan? Won't we have problem using these with MOSS?
Answer: While I believe in OpenSource. What I believe in even more is using the right tool for the job. From what you have provided trying to use openLDAP + SAMBA will be like trying to shove a round peg into a sqaure hole. Especially at the size your deployment sounds like. If your clients are all running Windows, then Use active directory.
Group Policy alone is enough in my opinion to make this a no brainer.
Now with that said, that doesn't mean you have to run Windows on all of your servers. Once again using the right tool for the job comes into play. Run your SQUID proxy servers on Linux and authenticate them against active directory.
You should probably use CentOS (or redhat if your university wants a support contract) Debian, or Ubuntu LTS.
To directly answer a few of your questions that I havn't answered above:
Can you do everthing with samba? Probably but honestly I think it would be more trouble than it's worth, and you won't get the full benefits of AD
You need Windows (and i think in the new version AD) to use sharepoint
You might be able to get away with using mono the run .net applications - but once again it would probably be more trouble than it is worth.
Comment: tnx , can you answer this question too ?
http://serverfault.com/questions/97347/active-directory-squid-planning-for-a-large-network-with-over-than-7000-users
Answer: The short answer is Samba's AD support is coming in Samba 4, which is not ready to be deployed by regular users yet.
Ubuntu LTS is my personal suggestion.
Comment: tnx , can you answer this question too ?
http://serverfault.com/questions/97347/active-directory-squid-planning-for-a-large-network-with-over-than-7000-users


Win32 asynchronous sockets basic question

Question: I've done a client-server voice chat (like ventrilo) in C# and am now doing it in unmanaged win32 c++. I've got a question about how asynchronous reads/writes are handled in c++. In C#, you had a function that got called (EndSend/EndRecieve) once BeginSend/BeginRecieve were done. How is this done in c++? I've looked at msdn and googled and couldn't find an answear.
Here's the code for example that runs when a button is pressed, triggering a WM_WRITE message that called this function:
<code>[...]
case ID_BUTTON_SEND:
    SendMessage(hWnd,SOCKET_TCP,0,FD_WRITE);
    break;

[....]
case FD_WRITE:
      onTextSend()
      break;
[....]

void onSendText(HWND hWnd) {
// get window handle to send edit control
HWND hWndSend = GetDlgItem(hWnd,ID_EDIT_SEND);

// get textlength of send edit control
int textlen = GetWindowTextLength(hWndSend);

// allocate memory for a buffer that will contains the text to be sent and get the text
char* textbuff = (char*)malloc(textlen+1);
SendMessage(hWndSend,WM_GETTEXT,textlen+1,(LPARAM)textbuff);

// send content
send(tcp_sock,textbuff,textlen+1,0);

// cleanup allocated tempbuffer
  free(textbuff);
}
</code>
Of course I don't want to initiate an asynchronous send and then proceed to deallocate the buffer used in the send directly, I want to deallocate it once send is complete (like EndSend). I havn't found the c++ way to do it, any suggestions?
EDIT: ALSO! for some reason, when the server accepts the client, the client is not getting a FM_CONNECT message, shouldn't it get it as soon as the client is connected? I can send() and recv() so the connection is definately up.
Answer: have a look at Boost Asio library. even if you don't need cross-platform solution, Asio is great C++
library that provides asynchronous sockets. an example of asynchronous read/write
Answer: and if you don't want to deal with Asio, here's good tutorial about asynchronous sockets: http://www.gamedev.net/reference/programming/features/asyncsock/
Comment: I prefer using winsock and this tutorial did clear some things up, but not how to deal with send. Basically right now I am just sending text. The tutorial mentions WM_WRITE is not very good for that purpose, so how do I deal with deallocating that buffer? Also updated main question!


Relation between the roots of a polynomial and its derivative

Question: Ok so I was going through a limit question, and I am only interested in one aspect of the question it is mention that
Let f(x) be a polynomial which is satisfying
${f(a)}^{2} + {f'(a)}^{2} = 0$, then that means $f(a) = 0 = f'(a)$. This means that x = a is a root of $f'(x)$, now this is the part i don't understand whatsoever, because in my book its written that $(x-a)^2$ is a factor of f(x). My question is why is it required to take a square of the root $(x-a)$? I'd like to see an example to help me understand this please
Answer: Since $a$ is a root of $f(x)$, you can write $f(x)$ as $(x-a)p(x)$ for some polynomial $p(x)$. Suppose that $a$ is not a root of $p(x)$. Then $f'(x)=p(x)+(x-a)p'(x)$ and therefore $f'(a)=p(a)\ne0$. But we are assuming that $f'(a)=0$. So, $a$ has to be a root of $p(x)$. So, $x-a\mid p(x)$, and therefore $(x-a)^2\mid f(x)$.


How to tell which Web Node is serving Content?

Question: I have a loadbalancer that distributes traffic to 1 of 5 Web Nodes.  Is there an easy way to tell what Web Node I am talking to when it serves me content.  For example whould I implement a Header in Apache? Add a hidden HTML element on each page?
Bonus points: What do people do to force themselves to one specific web node?
Answer: There are various way to solve this issue. My favourite, mainly because it is easy, is to set an HTTP header specific to each server in the apache configuration that just contains the hostname. You can use an arbitrary string if you do not want to reveal the underlying hostnames.
<code># On host1
Header set ServerID host1
# On host2
Header set ServerID host2
# etc.
</code>
You can then see the relevant HTTP header in the request response.
With regards to forcing yourself to a particular node, that depends on the details of how you are load balancing the servers.
If you are running a stateless application and the load-balancer is just sending the requests in a round-robin, or some random manner, then there is little you can do to force yourself to a specific underlying node (other than maybe switching off all the other nodes).
However if your load-balancers are doing some form of cookie insertion (or similar) in order to provide sticky sessions, then you can normally tailor a request that will allow you to force yourself to a particular underlying node, but a lot depends on the method used.
Comment: I was thinking the HTTP Header was the way to go. We do have a form of sticky sessions but I THINK its based on IP not a COOKIE.
Comment: If session stickyness is done purely on the load balancer then you probably wont be able to affect it directly, but talk to whoever maintains your load balancer.


Sheafification of representable presheaves

Question: Recall that if $\mathscr{C}$ is a site (which, for me, means a category equipped with a Grothendieck pretopology—not sieves) that it's not in general true that the representable presheaf $h_X$ associated to an object $X$ of $\mathscr{C}$ is a sheaf.
In particular, one can consider the composition of functors
$$\mathscr{C}\to \mathsf{PSh}(\mathscr{C})\xrightarrow{(-)^\#}\mathsf{Sh}(\mathscr{C})$$
(where $(-)^\#$ denotes sheafification) and think of the full image—the full subcategory of $\mathsf{Sh}(\mathscr{C})$ whose objects are sheaves isomorphic to $h_X^\#$ for an object $X$ of $\mathscr{C}$. Let me denote this category with the (probably poorly chosen) notation $\mathscr{C}^\#$.
My question is then the following

Question: What is an explicit description of $\mathscr{C}^\sharp$?

To give an idea of what type of description I'm looking for, I think that one can write that there is a bijection
$$\mathrm{Hom}(h_X^\#,h_Y^\#)=\varinjlim_{\substack{\{U_i\to X\}\\ \mathscr{C}\text{-coverings}}}\check{H}^0_\mathrm{loc}(\{U_i\to X\}, h_Y)$$
where
$$\check{H}^0_\mathrm{loc}(\{U_i\to X\}, h_Y):=\left\{(f_i)\in\prod_i \mathrm{Hom}_{\mathscr{C}}(U_i,Y): f_i\text{ and }f_j\text{ agree locally on overlaps for all }i,j\right\}$$
where $f_i$ and $f_j$ agreeing locally on overlaps means that there exists a cover $\{V_k\to U_i\times_X U_j\}$ such that $(f_i)\mid_{V_k}=(f_j)\mid_{V_k}$.
This is literally, I believe, just because one has natural bijections
$$\mathrm{Hom}(h_X^\#,h_Y^\#)=\mathrm{Hom}(h_X,h_Y^\sharp)=h_Y^\#(X)$$
the first from the definition of sheafification, and the second from Yoneda's lemma. The claimed equality then follows from the explicit description of sheafification.

Refined question: With the above description of $\mathrm{Hom}(h_X^\#,h_Y^\#)$ (or a slightly modified, but still
explicit version)

What is the actual map $h_X^\sharp(Z)\to h_Y^\#(Z)$ for $Z$ an object of $\mathscr{C}$?
What is the composition  $$\mathrm{Hom}(h_X^\#,h_Y^\#)\times \mathrm{Hom}(h_Y^\#,h_Z^\#)\to \mathrm{Hom}(h_X^\#,h_Z^\#)$$ look
like?

NB: I'm mostly looking for a reference. Obviously you can answer this question by tracing through all the definitions, but I'd like to save myself the time/writing and just cite something. I'd be a little surprised if a reference didn't exist.
Thanks!
Answer: I don't have the reference you want, but here's the concrete description of composition you ask for.
An element of $h_Y^\sharp(X)$ is witnessed by some cover $\{U_i\to X\}$ and maps $U_i\to Y$ agreeing on overlaps. An element of $h_Z^\sharp(Y)$ is witnessed by a cover $\{V_j\to Y\}$ and maps $V_j\to Z$ agreeing on overlaps. The composition in $h_Z^\sharp(X)$ is then witnessed by the cover $\{U_i\times_Y V_j \to U_i \to X\}$ and the maps $U_i\times_Y V_j \to V_j \to Z$.
Comment: A bit busy now, but I promise to return and accept this later if I don't have any other questions. Thanks!


Correlation of randomly oriented unit vectors

Question: Let $R(\alpha):u\rightarrow v$ be a random transformation from Euclician 3D unit vector $u$ to same such unit vector $v$ so that $\measuredangle (u,v) \le \alpha$. The probability density is constant within $\alpha$. My question is, how to estimate such $n$ so that $R^n(u)$ is reasonably uncorrelated with $u$? Rough lower estimate would be $n \approx \pi/\ \alpha $ but I'd love to have more solid ground for such estimate.
Comment: You are perfectly right. Dayne made a good answer for a single rotation in range ($-\alpha, \alpha$) which was not what I meant. I could have been more clear in my question. What I had in mind is essentially random walker on a sphere where each random step taken is within some given alpha. As for correlation, it was my assumption that if I take randomly two unit vectors, it is expected them to be mutually orthogonal. In any case, would you recommend me to try fix the question or try asking whole new question?
Comment: Could you clarify what you mean by "uncorrelated"?  My concern is that every rotation has an axis and that no matter how many times you apply the rotation, unit vectors near that axis will barely change, so there won't be any eventual reduction to zero correlation.
Comment: I am no mathematician, but I mean uncorrelated - as in, if I provide you with R^n(u), you would not be able to determine vector u with better accuracy than guessing. The function R is applied successive, iterative way and no unit vector of the sphere is invariant to it.
Comment: My meaning is the same: if you provide me with $R^n(u)$ and this is close to the axis of $R,$ then $R^n(u)$ will be close to $u:$ that's "correlation" in the sense you describe.  I wonder whether by "$R^n(u)$" you might mean choosing $n$ independent random rotations and applying them in succession?  That is *very* different than what $R^n$ means, which is to obtain a *single* random rotation $R$ and apply it $n$ times.
Comment: Thank you for your thoughtful comments.  Because you already have an upvoted answer to an interpretation of your question, it's probably better to start a new thread with a clarification of your intended question.  I suggest also clarifying what you mean by the "probability density is constant within $\alpha,$" because that has several natural interpretations in this context. For instance, it could mean the amount of rotation has a uniform distribution but the rotation axis is random; or it could mean you want to select uniformly from all rotations of less than $\alpha;$ or something else?
Answer: If I understand correctly, $R(\alpha):u \to v$ is a rotation by amount $\theta$ such that
\begin{align}
\theta \sim U[-\alpha,\alpha] \\
\lambda \equiv \frac{\theta+\alpha}{2\alpha} \sim U[0,1]
\end{align}
(I am taking distribution from $-\alpha$ because otherwise the rotation is happening only in one direction and the correlation will become cyclical).
Let $\theta_i$, $i=1,2,\dots,n$ be $n$ rotations, and $\theta_{(n)} \equiv \sum_1^n \theta_i$ be the final angle between $u,v$ after $n$ rotations.
Define
$$\lambda_n = \frac{\theta_{(n)} + n\alpha}{2\alpha} = \sum\limits_1^n \frac{\theta+\alpha}{2\alpha}$$
So, $\lambda_n$ follows the Irwin-Hall distribution, with parameter $n$.
Now we also need to define what is a reasonable range of correlation to claim that $u,v$ are uncorrelated. For reasonably high number of dimensions, this can come from theory (from distribution of the correlation coefficient). However, here since it's just a three-dimensional space, we should define it.
Say, we consider $(-0.2,0.2)$ as this range. Also note that (pearson) correlation is just $\cos \theta_{(n)}$.
Therefore,
\begin{align}
-0.2 &\leq\cos\theta_{(n)} \leq 0.2 \\
\cos^{-1}(0.2) &\leq \theta_{(n)} \leq \cos^{-1} (-0.2) \\
1.37 &\leq \theta_{(n)} \leq 1.77
\end{align}
For this range of $\theta_{(n)}$, we can get a range of $\lambda_n$:
$$\Lambda:=\bigg( \frac{1.37+n\alpha}{2\alpha},\frac{1.77+n\alpha}{2\alpha}\bigg)$$
From the distribution, we can get:$\mathbb P(\lambda_n \in\Lambda)$ as a function of $n$. Finally, MLE can be used to estimate $n$ to maximize this probability.
Comment: @Dayne thank you for your effort to answer my question. As far as I can see it, you made a good answer but not to the question I had in mind - that was my fault, I could and should have been more clear. I am not a mathematician and didn't know that I need a matrix to characterize relation of two random vectors. Intuitively, I figured if I pick randomly two vectors from unit sphere, they would be orthogonal and didn't google it beyond that. I'll try reformulating question.
Comment: How do you obtain $\cos(\theta_{(n)})$ as the correlation?  Indeed, what exactly do you mean by using a single value to characterize the correlation between unit *vectors*?  Doesn't that need a correlation matrix?
Comment: @whuber: I understand that taking unit vectors of just 3 dimension as samples of a single random variable (as opposed to considering them as random vectors) doesn't make much sense but I thought that was OP's requirement.
Comment: StipeGalić: No issues. I just read the comments by @whuber on the question and I realized that I wrongly assumed that the rotation is happening in the same plane (i.e., there is no change in axis of rotation). This is clearly very restrictive. Please ignore my answer. I should perhaps consider deleting it.


Confused about the key of "Watermelon Man"

Question: It is said that the original 1962 recording of "Watermelon Man" by Herbie Hancock is in the key of F. It makes a lot of sense given it's a bluesy piece, so we have a typical I-IV-V based chord progression.
However, here is where it gets confusing to me: the first chord is F7, but there is no minor seventh in the F major scale. Why is it then that people still say it's in F? Wouldn't it make more sense to call it F mixolydian? Or is it implied?
Comment: You can't mix keys and modes. It's in F and, as you say, it's bluesy. There are F7s in the accompaniment and there are Abs in the tune. That's what happens in jazz and blues. There's too much daft analysis in here!
Comment: @secondcitysaint You're not alone in this, it's a very common idea to equate scale and key, because we say things like, "this is in D major" or "this is in A minor", and there's this thing called "key signature", which implies a scale. But all of these notations and idioms are really approximations, compromises or historical accidents, just like everything about our communication. No expression "cuts it" from all possible angles, there's always a chance of misunderstanding, and you'll learn to make better guesses only by taking part in the culture, by making music with others. :)
Comment: So, what do people mean when they say that a song is "in" a key, and why do songs supposedly in some key use notes outside the most obvious scale that comes to mind?    There are several questions about that https://music.stackexchange.com/questions/38939/difference-between-keys-and-scales  https://music.stackexchange.com/questions/42650/what-does-the-key-of-a-song-mean https://music.stackexchange.com/questions/80604/why-dont-key-signatures-indicate-the-tonic  I particularly like the idea in the last question that it's all just a big historical accident. It wasn't designed.
Comment: @piiperiReinstateMonica - seems like more of a question than a comment!! However, there's usually a sort of 'home key' which gives most of what's needed, and it strays from there. Scale and key aren't synonymous anyway - particularly in minors! Trouble is, as said previously, humans love to try to pigeon-hole things, but music just cocks a snook at that.
Comment: @Tim I meant to imply that the question is probably just about terminology and that there are several answered questions about the same thing already.
Comment: @piiperiReinstateMonica Thanks for the links! The "key != scale" is a good point. I'm coming from a technical background so I guess I'm a bit guilty at trying to figure out and follow the rules way too strictly (especially while learning).
Answer: There isn't a 'rule' about what notes fit into what key - not really even an unwritten one!
Especially when considering jazz and blues.
Yes, I suppose 'F Mixolydian' might be a more accurate way to describe the key here, but all the transcriptions I've played from use the key sig. of 1♭, (Fmajor) rather than 2♭s (B♭/F Mix.).
It's what blues and jazz do: use a basic key, and use flat 3s, flat 5s and flat 7s. It's become the norm over many decades, and doesn't present a problem to us - not even pedants such as myself!
Comment: Thanks, it makes sense! I'm probably trying to be overly pedantic while learning to make sure I'm not missing anything. The good old "learn the rules before breaking them" kind of thing :)
Answer: Listen to the recording (on the Herbie Hancock album "Takin' Off") with the sheet music and try to see if it makes aural sense to you. If you haven't listened to much blues-oriented music it might not make any sense at all! But listening to "Watermelon Man" is a good start. Then, try to understand why it sounds good! Remember that music theory is only observations and explanations about what our ears think sounds good.
Answer: Blues is a style that's non-diatonic (it does not conform to diatonicity rules whereby you stick to 7 notes in a scale). There a few guidelines that apply to blues (except when they don't)
In major blues, all chords are dominant (ie: major chords with a minor 7th).
Note that further on in the progression you find a C7, which has an E, which conforms to Fmajor (vs the Eb that F7 would have).
Major blues compositions are both minor and major at the same time (ie: you can play both the minor 7th and the major 7th).
The blues scale uses the flatted 5th.
It's these chromatisms that give a tune the 'bluesy' sound.


Nested or not nested if-blocks?

Question: I was wondering if there is a performance difference when using ifs in C#, and they are nested or not. Here's an example:
if(hello == true) {
    if(index == 34) {
        DoSomething();
    }
}

Is this faster or slower than this:
if(hello == true && index == 34) {
    DoSomething();
}

Any ideas?
Comment: You don't have to compare booleans with true. if (hello)... or if (hello && index == 34)... is much better.
Comment: I know, I just wanted to make it obvious.
Answer: Probably the compiler is smart enough to generate the same, or very similar code, for both versions. Unless performance is really a critical factor for your application, I would automatically choose the second version, for the sake of code readability.
Comment: Totally agree, I'm quite sure what ever is the way is written on the low level it will transform into two JE or JNE instructions one after another. http://www.csee.umbc.edu/courses/undergraduate/CMSC313/fall04/burt_katz/lectures/Lect05/decisionMaking.html
Answer: Even better would be
if(SomethingShouldBeDone()) {
    DoSomething();
}

...meanwhile in another part of the city...
private bool SomethingShouldBeDone()
{
    return this.hello == true && this.index == 34;
}

In 99% of real-life situations this will have little or no performance impact, and provided you name things meaningfully it will be much easier to read, understand and (therefore) maintain.
Comment: It may be a personal preference, but I disagree with this being more readable because it's not possible to see what this method does unless you go to that method to check it out. In any case, I'd make this a property with a getter, not a method because it describes a *property* of a class, rather than actively doing something like a method (like getting something from a database).
Comment: Usually we would be talking about local variables here. You're strangely assuming `hello` and `index` are fields.
Comment: I'd only use this if I was performing the same evaluation in multiple places, or the original IF statement was rather long. It's just adding unnecessary complexity.
Comment: @ JR&CbM: I used to think that way too until I started working with a huge legacy codebase. The problem with things like this is that you completely lose the intent of the conditional check. At the time of writing it (might) have made complete sense, but after several years of various people fiddling the meaning it often isn't - even for very simple checks. Better to make it clean to start off with and continue that way. I was moving this way anyway, but after reading Clean Code (and some headaches reading some particulary poor code) I feel more confident that the extra verbosity is worth it.
Comment: @Joren: oops, yes - still the same principle applies though.
Answer: Use whichever is  most readable and still correct (sometimes juggling around boolean expressions will get you different behavior - especially if short-circuiting is involved).  The execution time will be the same (or too close to matter).
Just for the record, sometimes I find nesting to be more readable (if the expression turns out to be too long or to have too many components) and sometimes I find it to be less readable (as in your short example).
Answer: Any modern compiler, and by that I mean anything built in the past 20 years, will compile these to the same code.
As to which you should use then it depends whichever is more readable and logical in the context of the project).  Generally I would go for the second myself, but that would vary.
A strong point worth consideration though arises from maintenance.  One of the more common bugs I have hunted down is a dangling if/else in the middle of a block of nested ifs.  This arises if you have a complex series of if else conditions which has been amended by different programmers over a period - often several years.  For example using pseudo-code for a simple case:
IF condition_a
  IF condition_b
    Do something
  ELSE
    Do something
  END IF
ELSE
  IF condition_b
    Do something
  END IF
END IF

you'll notice for the combination !condition_a && !condition_b the code will fall through the conditions doing nothing.  This is quite easy to spot for just the pair of conditions, but can get very easy to miss very quickly once you have 3, 4 or more if/else conditions to check.  What commonly happens is the nested structure is correct when first coded, but becomes incorrect (in terms of the business outputs) at some later point because the maintenance programmers will not understand or allow for the full range of options.
It's therefore generally more robust, over time, to code using combined conditions in the if structure adopting the flatest feasible structure and keep nesting to a minimum, hence with your example as there's no logical reason not to combine the two conditions into a single statement then you should do so
Answer: I can't see that there will be any great performance difference with either, but I do think that option two is MUCH more readable.
Answer: I don't believe there is any performance difference you might be experiencing between the two implementation..
Anyway, I go for for the latter implementation because it is more readable.
Answer: Depends on the compiler. The difference will be more apparent when you have code after the close of the nested if, but before the close of the outer.
Answer: I've wondered about this often myself. However, it seems there really is no difference (or not much to speak of) between the options. Readability-wise, the second option is more readable and so I usually choose that one unless I anticipate having to code specifically for each condition for some reason.

Nested or not nested if-blocks?


PyQT on click open new window

Question: I'm new to PyQT and I'm looking for a code that demonstrates a simple push button, which when clicked will open a new small window with QTextEdit in it
Comment: http://stackoverflow.com/a/4839224/1110381 ...
Comment: well,  I tried w1 = QTextEdit() w1.show() but nothing happens
Comment: You need to construct a QApplication before this, and if you're not running interactively call _exec on the QApp to make sure the program doesn't just exit immediately. But the reason I linked this specific answer was the comment about modal dialogs: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qinputdialog.html#details
Answer: Here is something to start with:
<code>#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtCore, QtGui

class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)

        self.buttonBox = QtGui.QDialogButtonBox(self)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)

        self.textBrowser = QtGui.QTextBrowser(self)
        self.textBrowser.append("This is a QTextBrowser!")

        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.addWidget(self.textBrowser)
        self.verticalLayout.addWidget(self.buttonBox)

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pushButtonWindow = QtGui.QPushButton(self)
        self.pushButtonWindow.setText("Click Me!")
        self.pushButtonWindow.clicked.connect(self.on_pushButton_clicked)

        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.pushButtonWindow)

        self.dialogTextBrowser = MyDialog(self)

    @QtCore.pyqtSlot()
    def on_pushButton_clicked(self):
        self.dialogTextBrowser.exec_()

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())
</code>

PyQT on click open new window


ajax para notificação

Question: Para alterar o html sempre que for alterado uma informação no banco sem refresh(estilo as notificações do facebook) é feito como?
atualmente estou utilizando um timer, queria saber se há um jeito melhor que faça a requisição apenas quando necessário
[estou fazendo desta forma: setInterval("ajax()", 60000);]
Comment: setInterval é uma maneira, outra é por exemplo websockets: https://pt.stackoverflow.com/questions/19345/como-trabalhar-com-websockets?s=6|0.0000
Answer: Existem diversas técnicas para manter informações atualizadas com o servidor. Essa que você tá fazendo, é uma delas, e é perfeitamente aceitável.
Existem outras formas mais atualizadas, porém que possuem certas limitações quanto à navegadores. Uma delas é os WebSockets.
Dá maneira como você está fazendo, você fica pedindo informações ao servidor em um intervalo regular de tempo. Isso dá a impressão de a aplicação ser real-time. Porém, suas requisições são feitas a cada 60 segundos. E se uma informação for alterada no banco logo após a última requisição? Ela só vai ser atualizada depois de vários segundos. WebSockets mantém uma conexão aberta entre o servidor e o cliente, de modo que o servidor pode checar por si mesmo novas informações, e enviar ao cliente quando precisar. O cliente estará de prontidão para receber essas informações, e atualiza-las na DOM, ou aonde for.
Comment: muito obrigado, vou ler sobre o WebSockets, me ajudou basntante.

ajax para notificação


How do I access child xml elements?

Question: I have an xml string saved in a legacy database that I'm attempting to parse.  I can get the string but having 2 issues getting the values that I need.  First, some sample xml.
<?xml version="1.0" encoding="utf-16"?>
<email>
    <meta>
        <smartForm>
            <unit name="ForgotUsername" label="Forgot Username Email">
                <textBox name="FromEmail" label="From Email" type="Email" />
                <textBox name="FromName" label="From Name" type="100" />
                <textBox name="BccEmail" label="BCC" type="EmailList" />
                <textBox name="Subject" label="Subject" type="300" />
                <textBox2 name="TextBody" label="Body" type="Memo" />
            </unit>
            <unit name="ForgotPassword" label="Forgot Password Email">
                <textBox name="FromEmail" label="From Email" type="Email" />
                <textBox name="FromName" label="From Name" type="100" />
                <textBox name="BccEmail" label="BCC" type="EmailList" />
                <textBox name="Subject" label="Subject" type="300" />
                <textBox2 name="TextBody" label="Body" type="Memo" />
            </unit>
        </smartForm>
    </meta>
    <value><?xml version="1.0" encoding="utf-16"?><root><ForgotPassword BccEmail="firstname.lastname@example.com" FromEmail="email@example.com" FromName="password test" Subject="password test" TextBody="info" /><ForgotUsername BccEmail="email@example.com" FromEmail="email@example.com" FromName="test" Subject="test" TextBody="test" /></root></value>
</email>

Issue #1 - I attempted to parse the xml using XElement.Parse("string") however, I cannot get the <value> node unless I remove the xml declaration (i.e. first 39 characters).  I'm hoping to not HAVE to do this since it's a brittle solution.
Issue #2 - Once I have the <value> element's contents and parsed into an XElement, I want the query to either the <ForgotUsername> or <ForgotPassword> child node of the <root> document element. When I got .Elements(), I'm told the collection is null.
What am I doing wrong?
The Value's XML after entities are replaced:

<root>
    <ForgotPassword BccEmail="email@example.com" FromEmail="firstname.lastname@example.com" FromName="password test" Subject="password test" TextBody="info" />
    <ForgotUsername BccEmail="email@example.com" FromEmail="firstname.lastname@example.com" FromName="test" Subject="test" TextBody="test" />
</root>

UPDATES:
After trying abatishchev's initial suggestion - I changed the code for issue #1 to the following:
var xdoc = XDocument.Parse(contentXml);
return (from element in xdoc.Elements("value")
        select element.Value).FirstOrDefault();

Based on the information provided, it should return the string in the value node; however, it's returning null.  The xdoc.Elements() (or as shown in the above snippet) return null.
Comment: Have you tried `XDocument.Parse()` instead of `XElement.Parse()`?
Comment: Tried both and same results with both.
Answer:
Use XDocument.Parse() to create a document supporting XML declaration
To get units, use
XDocument.Parse("...").Root // or Element("email")
    .Elements("meta")
        .Elements("smartForm")
            .Elements("unit");

or use XPath: email/meta/smartForm/unit
also you can use query-style:
var doc = XDocument.Parse("...");
var q = from meta in doc.Root.Elements("meta")
        from smartForm in meta.Elements("smartForm")
        from unit in smartForm.Elements("unit")
        select unit;

Comment: After switching it to XDocument.Parse() and then calling xdoc.Elements("meta"), it says Elements() returns null.
Comment: Added snippet to main question.
Comment: @James: In brief, prepend with `XDocument.Root`
Comment: That was it.  Forgot Root.  I knew it was something simple.  Thanks!
Answer: The following works for me:
var xd = XDocument.Load("Test.xml");
var xv = XDocument.Parse((string)xd.Root.Element("value"));
Console.WriteLine(xv.Root.Elements().Count());

Output is 2, for ForgotPassword and ForgotUsername.
Answer: For #1:
XElement doc = XElement.Load(file);
XElement valueElement = doc.Element("value");
string value = (string)valueElement;

How do I access child xml elements?


Using fabric to manipulate database connection

Question: I just started using Fabric to better control the specific settings for test and deployment environments, and I'm trying to get an idea of the best approach to swapping configurations.
Let's say I have a module in my application that defines a simple database connection and some constants for authentication by default:
host = 'db.host.com'
user = 'someuser'
passw = 'somepass'
db = 'somedb'

class DB():
  def __init__(self,host=host,user=user,passw=passw,db=db,cursor='DictCursor'):
    #make a database connection here and all that jazz

Before I found fabric, I would use the getfqdn() function from the socket library to check the domain name of the host the system was being pushed to and then conditionalize the authentication credentials.
if getfqdn() == 'test.somedomain.com':
  host = 'db.host.com'
  user = 'someuser'
  passw = 'somepass'
  db = 'somedb'
elif getfqdn() == 'test.someotherdomain.com':
  host = 'db.other.com'
  user = 'otherguy'
  passw = 'otherpass'
  db = 'somedb'

This, for obvious reasons, is really not that great.  What I would like to know is what's the smartest way of adapting something like this in Fabric, so that when the project gets pushed to a certain test/deployment server, these values are changed at post-push.
I can think of a few approaches just from looking through the docs.  Should I have a file that just defines the constants that Fabric could output to using the shell commands based off what the deployment was, and then the file defining the database handler could import them?  Does it makes sense to run open and write from within the fabfile like this?  I assumed I'd also have to .gitignore these kinds of files so they don't get committed into the repo and just rely on Fabric to deploy them.
I plan on adapting whatever approach is the best suggested to all the configuration settings that I currently either swap using getfqdn or adjust manually.  Thanks!
Answer: You can do all of that off of the env.host and then use something like the contrib template function to render the conf file and push it up. But templates are best in these instances (see: puppet and other config managers as well)
Comment: Thanks - using this I decided to have Fabric output some json as the config and refactor my code to expect this.


How to display references two deep in phoenix elixir

Question: I am wanting to display a reference two tables deep in Pheonix Elixirr, and seem one step away from actually getting it.
There are three interrelated tables:
The main table is Clients. Clients have Requests. Requests have Requesttypes, which are a lookup table.
In the Clients Template would like to show a listing of the requests a client has made. In the Show Template, there is a loop as follows:

     <%= for request <- @client.requests do %>

       <%= request.request_date %> -
       <line in question> -
       <%= request.notes %>

       <%= link "Show", to: Routes.client_request_path(@conn, :show, @client, request) %>
       <%= link "Edit", to: Routes.client_request_path(@conn, :edit, @client, request) %>
     <% end %>

The above is working fine without the line in question. I would like to add the request type, which is selected from a dropdown, so a reference from the Request table.
If I try to add:
<%= request.requesttype.requestname =>
It doesn't work.
In the Request Show page
<%= @requesttype.requestname =>
does work
And in the line in question
<%= request.requesttype_id %>
Does show the correct id.
The error is key :requesttype not found in: #Ecto.Association.NotLoaded<association :requesttypes is not loaded>.
The get_client function is as follows:
def get_client!(id, tenant) do
Client
|> Repo.get!(id, prefix: Triplex.to_prefix(tenant))
|> Repo.preload([:genders, :requests])
end

How would I add association from the requests table?
Any help would be greatly appreciated.
Comment: I added these into the main body of the post.
Comment: Couple of questions :) What error did you get exactly? How did you query (did you use some [`preload`](https://hexdocs.pm/ecto/Ecto.Query.html#preload/3))? Can you try to replace the following: `<%= for request <- @client.requests |> IO.inspect(label: "requests") do %>` and see what is being logged?
Comment: The error is ```key :requesttype not found in: #Ecto.Association.NotLoaded```. Seems that the associations from the Requests table are not being loaded. How do I preload those? Here is the get_client function:
```  def get_client!(id, tenant) do
    Client
    |> Repo.get!(id, prefix: Triplex.to_prefix(tenant))
    |> Repo.preload([:genders, :requests])
  end
```
Answer: As hinted by the error message, the nested requesttypes are not loaded because you are only preloading client.requests, but not the associated requesttypes. You need to be explicit about what you are preloading, which is actually a good thing because you are controlling what you are querying.
Using Repo.preload([genders: [], requests: :requesttypes]) should fix your issue, it is using a keyword list to preload nested associations as in one of these doc examples.
Please note that this will fire 4 separate queries (which might be fine or not depending on your use case), if you want to use joins to avoid this you should probably write a query (see this great explanation).
I encourage you to fiddle with your queries in the REPL (iex -S mix), it is very transparent and you'll see:

the data being returned (what is loaded or not)
the underlying queries from the debug log

There is a great section about this in Elixir school that could be interesting as well.
Comment: thank you very much. The preload with the nested associationns were just the thing. Thanks for the links to creating joins and the associated data.
Comment: Nice, I'm glad it worked! If your question has been answered, please make sure to accept the answer for further references ;)
Comment: @ArniMikelsons please mark the answer as correct with the green checkmark in the top-left corner. It's mandatory according to SO rules. Thanks.


Code=3072 "The operation was cancelled" when setting alternate app icon

Question: I am trying to set an alternate app icon named MyIcon in my iOS app. I have a MyIcon.png image in my project bundle (not in my Assets folder) and it is declared in my Info.plist like so:
<key>CFBundleIcons</key>
<dict>
    <key>CFBundleAlternateIcons</key>
    <dict>
        <key>MyIcon</key>
        <dict>
            <key>CFBundleIconFiles</key>
            <array>
                <string>MyIcon</string>
            </array>
            <key>UIPrerenderedIcon</key>
            <false/>
        </dict>
    </dict>
</dict>

In my code, I try to change the app icon:
UIApplication.shared.setAlternateIconName("MyIcon")

However, the icon doesn't change and I am instead given this error in the console:
Error Domain=NSCocoaErrorDomain Code=3072 "The operation was cancelled."

How can I fix this issue?
Answer: I was getting this error because of two reasons,

First(and highly not because of), I didn't do "Add Files to 'ProjectNameFoo'" by adding png file to project. Otherwise it didn't work. After that it started to see icon.
Secondly(and highly possible reason), I was getting this error because I was trying to change the icon in viewDidLoad. When I try with a delay like the code below it was working whatever second I gave.

override func viewDidLoad() {
    super.viewDidLoad()

    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
        UIApplication.shared.setAlternateIconName("MyIcon")
    }
}

Comment: For anyone who still couldn't fix it... I had to take a delay of 3.0 seconds in order to have it working.
Comment: @flyingBear did you find a reason for this issue ? I mean why does it not work without the delay ?
Comment: That was a free time project for me to present something. So. unfortunately, I didn't go on it on more after that. But if you find, please let me know too.
Answer: I was stuck with this error for quite a while and tried all sorts of things but couldn't work out what I was doing wrong. I was changing the icon from AppDelegate.application(didFinishLaunchingWithOptions:). Delaying the call with a timer as suggested above did solve it.
It is worth noting that this problem is due to UIKit trying to show a UIAlertController with the message

You have changed the icon for $(PRODUCT_NAME)

and that didn't seem to work at that point. You need to wait until a root view controller is loaded.
This is because this API is not meant to for the developer to update the icon arbitrarily, but for the user to deliberately choose one.
Comment: This should be the right answer. The delay solution is just wrong.


Django email verification URL with token parameter

Question: I'm trying to create an email verification auth, but I'm unable to access this URL
127.0.0.1:8000/activate/d34324/KYJsqYMoV5DJ0vewSBdC9KZlZtnOAU7KE

How can I create proper routes for this code?
urls.py
url(r'^logout/$', OwnerRegister.logout_view),
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',OwnerRegister.activate,name='activate'),

views.py
class OwnerRegister(TemplateView):
    template_name = "owner_register.html"

    def get_context_data(self, * args, ** kwargs):
        context = super(OwnerRegister, self).get_context_data()
        return context

    def logout_view(request):
        logout(request)
        return HttpResponseRedirect("/")

    def activate(request, uidb64, token):
        try:
            print('\n\n request',request)

            user_id = request.GET.get('uid')
            token = request.GET.get('token')
            user = User.objects.get(username=user_id)
            profile = OwnerInfo.objects.get(user=user)
            print(user.date_joined)

            if profile.confirmation_code == token and user.date_joined > (datetime.datetime.now()-datetime.timedelta(days=1)):
                print("test")
                user.is_active = True
                user.save()

                user.backend='django.contrib.auth.backends.ModelBackend'
                auth_login(request,user)
                return HttpResponseRedirect('You have activated this account')
        except:
            return HttpResponseRedirect('')

def send_registration_confirmation(self,user,request):
    p = OwnerInfo.objects.get(user=user)
    current_site = get_current_site(request)
    content = current_site.domain+"/activate" +  user.username + "/" + str(p.confirmation_code)
    send_mail("Email Verify", content, 'firstname.lastname@example.com', [user.email], fail_silently=False)

Answer: Notwithstanding any other problems you may have in your code, there appears to be a problem with your URL pattern declaration. Specifically, the URL pattern specifies the following regex for the token named parameter and the trailing slash:
(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/

The string passed in as token in the URL does not match this regex as it is missing a hyphen after its thirteenth character.
Your URL also does not have a trailing slash. This is fine provided Django's APPEND_SLASH option is enabled (the default behaviour), which will cause Django to automatically issue a redirect to add a trailing slash when no URL pattern is found without one.
You should either change the mechanism used to generate the token in the URL to ensure it matches the regex (adding a hyphen indeed does so), or vice-versa.
Comment: i tyred this http://127.0.0.1:8000/activate/KYJsqYMoV5DJ0vewSBdC9KZlZtnOAU7KE

    url(r'^activate/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',OwnerRegister.activate,name='activate')

but still returning 404
Comment: You still have a hyphen (`-`) in the regex between the `{1,13}` and the second character class, but no hyphen in the token in the URL.


Special Counters

Question: I`m trying to create a special counter in C# ... I mean the counter will be consisting of characters not numbers.
I have a char[] of size 3:
char[] str = new char[strSize];
int i = 0;
int tmpSize = strSize - 1;
int curr;
while(!isEqual(str,finalStr,strSize))
{
    str[strSize] = element[i % element.Length];
    i++;
    if (str[strSize] == element[element.Length - 1])
    {
        int j = strSize - 1;
        if (j > 0)
        {
            j--;
            int tmpCntr = j+1;
            curr = getCurrentID(str[tmpCntr]);
            str[tmpCntr] = element[(curr + 1) % element.Length];
            while (str[tmpCntr] == element[0] && (i % element.Length > 0) && tmpCntr < 0)
            {
                tmpCntr--;
                curr = getCurrentID(str[tmpCntr]);
                str[tmpCntr] = element[(curr + 1) % element.Length];
            }
        }
    }
}

if the strSize < 3 the application works fine and gives accurate output. If the strSize >= 3, the application goes in infinite loop!
Need help.
if this is hard this way, I would need a way to create a numerical counter and I`ll work on it to suite my application.
Comment: Why not use a numerical counter, then convert it to text when you need to display it? What's in `element`?
Comment: @Tim Robinson: `element` contains the characters that will be used as a counter.
Comment: @Saeed: `getCurrentID()` retrieves the location of the element in `str[*]` in respect to `element[]`
Comment: @Tim Robinson: it will be the same when I use the numerical counter, each location in the array will contain an integer, and the integer can be greater than 9!
Answer: You haven't shown what half of your methods or parameters are.
Personally I would take a different approach. I would use an iterator block to make it easy to return an IEnumerable<string>, and internally just keep an integer counter. Then you just need to write a method to convert a counter value and "alphabet of digits" into a string. Something like this:
public static IEnumerable<string> Counter(string digits, int digitCount)
{
    long max = (long) Math.Pow(digits.Length, digitCount);
    for (long i = 0; i < max; i++)
    {
        yield return ConvertToString(i, digits, digitCount);
    }
}

Another alternative is to do the same thing with LINQ, if a range of int is enough:
public static IEnumerable<string> Counter(string digits, int digitCount)
{
    int max = (int) Math.Pow(digits.Length, digitCount);
    return Enumerable.Range(0, max)
                     .Select(i => ConvertToString(i, digits, digitCount));
}

In either case, you just iterate over the returned sequence to get appropriate counter values.
With those in place, you just need to implement ConvertToString - which would probably be something like this:
public static string ConvertToString(long value, string digits, int digitCount)
{
    char[] chars = new char[digitCount];
    for (int i = digitCount - 1 ; i >= 0; i--)
    {
        chars[i] = digits[(int)(value % digits.Length)];
        value = value / digits.Length;
    }
    return new string(chars);
}

Here's a test program showing it all working:
using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
    static void Main()
    {
        // Show the first 10 values
        foreach (string value in Counter("ABCD", 3).Take(10))
        {
            Console.WriteLine(value);
        }
    }

    public static IEnumerable<string> Counter(string digits, int digitCount)
    {
        long max = (long) Math.Pow(digits.Length, digitCount);
        for (long i = 0; i < max; i++)
        {
            yield return ConvertToString(i, digits, digitCount);
        }
    }

    public static string ConvertToString(long value,
                                         string digits,
                                         int digitCount)
    {
        char[] chars = new char[digitCount];
        for (int i = digitCount - 1 ; i >= 0; i--)
        {
            chars[i] = digits[(int)(value % digits.Length)];
            value = value / digits.Length;
        }
        return new string(chars);
    }
}

Output:
AAA
AAB
AAC
AAD
ABA
ABB
ABC
ABD
ACA
ACB

Comment: @sikas: It returns a sequence which only yields the first 10 values from the input sequence. If you haven't looked at LINQ yet, I strongly suggest you do so :)
Comment: @Jon Skeet: what does `.Take(10)` do?
Comment: OK, I have removed it to display all possibilities and updated some of your code to work with `char[]` instead of `string` and for now it is working
Comment: @sikas: Is there any reason why you need it to use `char[]` instead of `string`? The latter is likely to be easier to cope with in most situations.
Comment: @Jon: I`m using the `char[]` because I have a `char[]` of elements that should be used in the counter. The elements vary from user to user.
Comment: @sikas: Is there any reason why *that* should be a `char[]` rather than a string? Strings are easier to cope with, being immutable etc.
Comment: @Jon: is there any way to convert the `char[]` to string? I don`t mind using `string`
Comment: @sikas: Yes, my original answer used a `char[]` internally and converted it to a string - just call the `string(char[])` constructor.

Special Counters


ask user enter a file to run the program with python

Question: I have a program that concatenates French words separated by an asterisk in a text. As I want this program to be used by different users, I want to insert a line in the program asking the user to enter the path of the text file or simply enter the name of the text…How to do that? Just using function "input"? I have no idea…Is there an elegant way to ask that to the user to run the program? The program is below:
import nltk
from nltk.tokenize import word_tokenize
import re

with open ('text-test.txt') as tx:
   words = word_tokenize(tx.read().lower())

with open ('Fr-dictionary.txt') as fr:
    dic = word_tokenize(fr.read().lower())

l=[ ]
errors=[ ]
out_file=open("newtext.txt","w")

for n,word in enumerate (words):
    l.append(word)
    if word == "*":
        exp = words[n-1] + words[n+1]
        print("\nconcatenation error:", exp)

        if exp in dic:

            l.append(exp)
            l.append("$")

            errors.append(words[n-1])

            errors.append(words[n+1])
        else:
           continue

for i, w in enumerate(l):
    if w == "*":
        l.remove(l[i-1])
    else:
        continue

for i, w in enumerate(l):
    if w == "$":
        l.remove(l[i+1])
    else:
        continue

text=' '.join(l)
print('\n\n',text)
e=len(errors)

print('\n',e/2,'WORDS CONCATENATED IN TEXT',errors)

user=input('\nREMOVE * AND $ FROM TEXT? Type "Y" for yes or "N" for
no:')

for x in l:
    if user=='Y' and x=='*':
        l.remove(x)
    elif user=='Y' and x=='$':
        l.remove(x)
    else:
        continue

final_text=' '.join(l)

print('\n\n', final_text)

user2=input('\nWrite text to a file? Type "Y" for yes or "N" for no:')

if user2 =='Y':
    out_file.write(final_text)
    out_file.close()
    print('\nText named "newtext.txt" written to a file')

Comment: Possible duplicate of [User input and command line arguments](https://stackoverflow.com/questions/70797/user-input-and-command-line-arguments)
Answer: You can do it any way you like, but having your users write out a full path to a file is tedious and error prone. What you could do is have a "watch folder". It's a folder that your script already knows about, maybe even in the same folder as your script.
A small example:
import os
import sys

# This prints the folder where the script is run.
script_directory = os.path.dirname(sys.argv[0])
print(script_directory)

# This is the folder we want to keep track off
our_watched_folder = f'{script_directory}/watch_folder'
print(our_watched_folder)

# Let's see if a user dropped a new file in our folder
print("Files in watch folder")
for file in os.listdir(our_watched_folder):
    print(file)

Output:
C:/your_script_folder/
C:/your_script_folder/watch_folder
Files in watch folder
a_new_text_file.txt
some_old_textfile1.txt
some_old_textfile2.txt

Answer: from pathlib import Path
data_folder = Path(str(input("type the path you would like to use")))
file_to_open = data_folder / str(input("insert the file you would like to use with its extension"))
f = open(file_to_open)

If you don't want to use the full path and just use a local file located in the script's location, you just need to ask the user for its name and open it with f = open(filename) directly.
Note:
If you are wondering why there's a / in file_to_open instead of a string concatenation + this explains why.


Using xpath or ->nextSibling to read html file using curl

Question: Help please on how to extract data like 15,Teaching Periods 1 and 2.,Max 150. e.t.c from the sample html code below using DOMDocument function? I have tried to work around it but having mutiple tags before the text I like to extract makes it harder for me to extract all the content once as I have to save all the extracted data into mysql database.

CS1050 Fundamentals of Internet Computing

Credit Weighting: 15

Teaching Period(s): Teaching Periods 1 and 2.

No. of Students: Max 150.

Pre-requisite(s): None

Co-requisite(s): None

Teaching Methods: 72 x 1hr(s) Lectures; 18 x 2hr(s) Practicals.

Module Co-ordinator: Professor Gregory Provan, Department of Computer Science.

Lecturer(s):  Mr Gavin Russell, Department of Computer Science.

Module Objective: To introduce students to Internet computer systems, web design, and
client-side programming.

Module Content: This module provides an introduction to the key concepts of Internet computing. Starting with the fundamentals of computer systems and the Internet, students progress to learn how to design web sites and how to utilize simple client-side programming. Issues related to user interface design and human-computer interfacing (HCI) are covered. Broader issues related to the use of the Internet for Blogging and Social Networks are discussed. The practical element of the module allows students to develop skills necessary for web site design using simple client side programming.

Learning Outcomes: On successful completion of this module, students should be able to:
· Understand the fundamental principles of computer systems and the Internet;
· Design web sites;
· Use simple client-side programming;
· Understand the principles of user interface design and human-computer interfaces.

Assessment: Total Marks 300: End of Year Written Examination 240 marks; Continuous Assessment 60 marks (Departmental Tests; Assignments).

Compulsory Elements: End of Year Written Examination; Continuous Assessment.<BR

Penalties (for late submission of Course/Project Work etc.): Work which is submitted late shall be assigned a mark of zero (or a Fail Judgement in the case of Pass/Fail modules).

Pass Standard and any Special Requirements for Passing Module: 40%.

End of Year Written Examination Profile: 1 x 3 hr(s) paper(s).

Requirements for Supplemental Examination: 1 x 3 hr(s) paper(s) to be taken in Autumn. The mark for Continuous Assessment is carried forward.

                   MY SAMPLE CURL CODE

$content3= $dom->getElementsByTagname('p');
$content4 = $dom->getElementsByTagname('b');

        //===========================================
        //=====  EXTRACT P STUFF ====================
        //===========================================

        foreach ($content3 as $value) {
            $contentnew[]= $value;
        print_r($value);

        echo "Attribute Value = ";
        echo $value->getAttribute('value');
        echo "
";

        // let's get hold of the text value from the node
        $mytempvariable=$value->nodeValue;
        print "CONTENT OF P NODE: \n\n$mytempvariable

\n\n\n";
        }
        echo "

";

        //===========================================
        //===== EXTRACT B STUFF =====================
        //===========================================
        foreach ($content4 as $value) {
            $contentnew[]= $value;

        echo "Attribute Value = ";
        echo $value->getAttribute('value');
        echo "
";

        print_r($value);
        // let's get hold of the text value from the node
        $mytempvariable=$value->nodeValue;
        print "CONTENT OF B NODE: \n\n$mytempvariable

\n\n\n";
        }
        echo "

";

I heard I could use ->nextSibling or xpath to extract all the data after all the b nodes but I cant seems to get around using xpath to extract all the relevant data I need.I could I do this please ??
Answer: You were very close:
$result = array();
foreach($dom->getElementsByTagName('b') as $node){
    $result[preg_replace('/:\s+$/','',$node->textContent)] = trim($node->nextSibling->textContent);
}
var_dump($result);

Comment: Thanks you so much for that.It works great.Can you please explain how it work so I could understand this for some other time. Specially the regular expression please?
Comment: Well, `->nextSibling` is just the next sibling node in the tree (i.e: in the case the text directly after ``), the regex is just to trim of the `: ` part in for instance `Credit Weighting: ` because I didn't like them in my case.... `textContent` is as stated a text-representation of the content of a node, without any tags.


How to enable Ckeditor for email templates?

Question: I have installed HTML Mail module, to send HTML emails and it is working fine and sending email in HTML format. Now i wanted to load CKeditor for email templates textarea, as html email will be handled now.
I have googled it, but didn't find any solution yet. Is there any way I can enable the ckeditor for system email templates and webform email templates.
-- Thanks for your time.
Answer: I recently had the same issue and was able to accomplish this through a hook_form_FORM_ID_form_alter(); in a custom module.
<?php

function MYMODULE_form_webform_email_edit_form_alter(&$form, &$form_state) {
  // This check will determine whether the form already has a ckeditor textarea on it, if not it will initialize ckeditor requirements.
  if (!function_exists('ckeditor_load_by_field')) {
    module_load_include('inc', 'ckeditor', 'includes/ckeditor.lib');
    $input_formats = ckeditor_profiles_compile();
    drupal_add_js(array('ckeditor' => array('input_formats' => $input_formats, 'plugins' => array())), 'setting');
  }

  // Set some vars.  Modify these as needed.
  $format_key = 'full_html';
  $element = $form['template']['template'];
  $element_id = 'edit-template--2';

  // The format array here is used within the ckeditor_load_by_field() function, without it things won't work.
  $format = array(
    '#options' => array(
      $format_key => $format_key,
    ),
    '#value' => $format_key,
  );

  // Both of the following keys are required for the textarea to become ckeditor-ified
  $element['#wysiwyg'] = TRUE;
  $element['#id'] = $element_id;

  // Run the ckeditor_load_by_field function which does all the magic.  Modify to match the $element var set above.
  $form['template']['template'] = ckeditor_load_by_field($element, $format);
}

Comment: Jason Gray's answer only works for certain forms.  It will not work on this particular textarea since we are using form_alter and such.
Answer: Or you could just use '#type' => 'text_format' and set the '#format' => 'full_html' for the textarea.
Just keep in mind that the data stored in the field will be stored as an array with 'value' and 'format'. So when setting up your form you'll want to use something like this:
$prev_input = variable_get('my_ckeditor_field',array('value'=>'booyah!
Works as designed.', 'format' => 'full_html'));
$form['my_ckeditor_field'] = array(
  '#type' => 'text_format',
  '#title' => 'CKEditor Field',
  '#format' => $prev_input['format'],
  '#default_value' => $prev_input['value'],
);

Hope this helps anyone else looking to quickly and easily enable the wysiwyg of their choice on their FAPI textareas.
If you are attempting to change a plain text textarea generated by a module that is not your own, such as the Webform or HTML Mail modules, then use nicholas' method since it's your only option.


How to delete thread object from device after finishing the task?

Question: How can I delete thread object after finishing the job?
Here's the code for creating the threads, also see that number of threads created reach 100 thread look at the image, how to delete them?
if __name__ == "__main__":
    segmentationProcess = SegmentationProcess()
    data = segmentationProcess.readDoc("./IT resumes as text/ktalzoubi.txt")
    data = segmentationProcess.preProcess(data)
    lock = multiprocessing.Lock()
    thread1 = ThreadWithLogAndControls(target=segmentationProcess.searchWorkExperience, args=(data, "W", lock))
    thread2 = ThreadWithLogAndControls(target=segmentationProcess.searchEducation, args=(data, "E", lock))
    thread3 = ThreadWithLogAndControls(target=segmentationProcess.serchSkills, args=(data, "S", lock))
    thread4 = ThreadWithLogAndControls(target=segmentationProcess.searchOthers, args=(data, "O", lock))
    wr1 = weakref.ref(thread1)
    wr2 = weakref.ref(thread2)
    wr3 = weakref.ref(thread3)
    wr4 = weakref.ref(thread4)
    thread1.start()
    thread2.start()
    thread3.start()
    thread4.start()
    print(wr1())
    thread1.join()
    thread2.join()
    thread3.join()
    thread4.join()
    del thread1, thread2, thread3, thread4
    print(wr1())

Comment: This is hardly a [mre] - it isn't clear what threading library you are using so it's likely impossible to give you specific help. One option would be to look at using a "pool" to assign tasks to threads. I wonder if you're just misunderstanding the printout though, and you're not actually creating hundreds of threads
Comment: Am using nbmultitask library:
https://github.com/micahscopes/nbmultitask
Comment: Maybe `segmentationProcess` creates hundreds of threads while loading the data? Also remember that `del` doesn't destroy an object - it only removes a reference to it. Since references could be stored elsewhere you can never really control when an object is destroyed.
Comment: Ok, then how can I permanently delete it?
Answer: You're worrying about a non-issue. The text "thread-103" does not mean that there are currently 103 threads. Instead it suggests that >=103 threads have been created. It comes from the Python threading module: if a name isn't supplied for the new thread then it defaults to one like Thread-<number>. <number> only ever goes up, and never goes down even when threads are destroyed (it also doesn't go up if a thread is created with a name, hence the number displayed is only a lower bound). This is only intended to give each thread a recognisable name, and not for anything else.
These threads are probably created in the lines:
data = segmentationProcess.readDoc("./IT resumes as text/ktalzoubi.txt")
data = segmentationProcess.preProcess(data)

We obviously don't know what's in these functions. The threads are probably being cleaned up correctly, but since you don't provide a mininal reproducible example it's impossible to provide any further detail.

There's a secondary point: the point at which Python objects are destroyed are called is pretty unreliable. del does not do so - it only breaks an individual reference to an object. It's likely that there are some circular references to the object stored in thread1 and so it still exists even after the thread1 variable is deled. These circular references are not a problem since they will be caught when the Python garbage collector is run (but exactly when that happens is a arbitrary).
Therefore, resources (other than memory) should not rely on object destruction to free them. The standard Python idiom is to use a with block, or try: ...; finally:. However, in the case of multithreading the resources you should be caring about are released when the thread finishes, so (again) a non-issue. (Or at least an issue out of your control).

Finally you look to be mixing multiprocessing.Lock with threading. These are two different methods of parallelising Python code and I would not assume that it's valid to mix them (it might be, it might not be, but it gives the impression that you haven't really understood what you're doing).
Comment: Thenk you so much for your highly benefits answer, I understood what you mean. But the idea of lock is that each thread perform specific task, and after each one finish it will go to another thread to update a list, all of them will access that thread, so when a single thread access it, a a lock will aquire, then the another etc... Kindly my bro, am facing another problem https://stackoverflow.com/questions/58941098/why-threads-stopped-in-heroku
Comment: About the lock: I was suggesting you use the lock in `threading` instead of the one in `multiprocessing`. The problem is (possibly) with mixing the modules, not having a lock.


How to make queries atomic in PostgreSQL stored procedures?

Question: I think the balance will be updated incorrectly if one process select the balance from a unique userid and attempts to do the insert, but another process reads the balance before that happens. How do I fix this?
CREATE OR REPLACE FUNCTION incBalance(INTEGER, BIGINT) RETURNS void AS $$
DECLARE
    balanceRecord record;
    newBalance bigint;
BEGIN
    FOR balanceRecord IN
        SELECT balance FROM users WHERE userid = $1
    LOOP
        newBalance := balanceRecord.balance + $2;
        UPDATE users SET balance = newBalance WHERE userid = $1;

    END LOOP;
    RETURN;
END;
$$ LANGUAGE plpgsql;

Answer: For this particular query, you could rewrite it as a single SQL statement:
UPDATE users SET balance = balance + $2 WHERE userid = $1;

More generally, you want to let the transaction system handle atomicity and data consistency.  In Postgres, stored procedures are always executed inside a transaction context - if you aren't calling it from an explicit transaction block, it will create one for you.
http://www.postgresql.org/docs/14/static/sql-set-transaction.html discusses how to set the isolation level if the default isn't stringent enough.
You will want to read http://www.postgresql.org/docs/14/static/mvcc.html to help decide which level is appropriate for a particular stored procedure.  Note sections 13.2.2 and 13.2.3 which warn that higher isolation levels are subject to serialization exceptions that should be caught and the transaction retried as a mechanism for ensuring consistency.
If I have such a procedure, I add a statement at the beginning of the procedure's first BEGIN block to ensure the transaction is running at a sufficient isolation level.  If no work has been done in the transaction yet, it will raise it if necessary.  If the calling context was a transaction that has done work, it will cause an error if the enclosing transaction block had not already raised the isolation level sufficiently.  It will not lower the isolation level if it was already higher than what you specify here.
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;

Comment: What happens if we, say, execute simultaneously thousands of queries, each of which makes `balance = balance + $2` for that specific user? Wouldn't it be that at some point `balance` would be taken from older time, increased/decreased by $2, loosing some intermediate additions/decreases? And why?
Comment: @PF4Public The whole point of using an [ACID](http://stackoverflow.com/questions/3740280/acid-and-database-transactions) compliant database is so you can avoid such problems.  ISOLATION LEVEL READ COMMITTED is sufficient for the single UPDATE statement shown.  More complex transactions may warrant a higher level as is discussed in the documentation links provided.
Comment: Thanks for your answer and clarifications


Creating versioning and oauth2 based authentication with my existing project on cakephp 2.0 to laravel 5

Question: I am upgrading from Cakephp 2.0 to Laravel 5.1. I need to do versioning if some one can suggest whether it should be in URI or headers?
How to maintain previous login databases of users info with Cakephp hashes to new Laravel oauth2.
Please help me find good reference for this and best practices to write code using repos, services and libraries.
I found this package Laravel oauth2 server
But could not find anything for better versioning where I do not need to repeat whole code.
Thanks in advance.
A article on REST API Best way to write rest api
Answer: I finally did it.For password i used
Using passwords hashed in CakePHP in Laravel environment
For Oauth i used the same package mentioned above using password auth and for API versioning i followed laracasts series.


Python- Removing brackets from a list of results

Question: i am retrieving some results from a mysql database and they come in a form separated by brackets. I want to remove the brackets, i have used the strip function but that will only work for when i have one result to display.
The code below will only remove brackets for search results that only have one element.
@QtCore.pyqtSignature("on_pushButton_clicked()")
def searchDBnumber(self):
    searchName = self.searchInput.toPlainText()

    if len(searchName) != 0:
        searchForName = ("""SELECT number FROM test_table WHERE name =""" + "'"+ searchName +"'")

        cursor.execute(searchForName)

        result = cursor.fetchall()

        result = str(result).strip('[](),')
        self.number.setPlainText(result)

Comment: Try: `', '.join(map(repr, result))`. Can include the output of `print(result)` in your question?
Comment: Don't ever do this: `name =""" + "'"+ searchName +"'"` when forming SQL queries. Here lies the path to [lil Bobby Tables](https://xkcd.com/327/). Use placeholders and pass your arguments to `cursor.execute`.
Comment: About "the form", `fetchall` returns a list of tuples (usually). You should format that using [`str.join`](https://docs.python.org/3/library/stdtypes.html#str.join) and [`str.format`](https://docs.python.org/3/library/stdtypes.html#str.format) (for example) to suit your needs, as pointed out by @MYGz.
Answer: I think the simple way is using extend
result = []
for i in c.fetchall()
    result.extend(i)

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: After some playing around I found that the results you get back from a mysql query aren't string but tuples so simply trying to remove the brackets doesn't work.
Here's is my example of how I dealt with it, starting with the query:
mycursor.execute("SELECT name1, name2 FROM testdatabase where (name1 REGEXP '^test.*') ")

I can then loop through the results and print each one like this:
for result in query_results:
    print(result)

Which gives some results like this:
('test0', 'something0')
('test1', 'something1')
('testing0', 'somethingelse1')

But I wanted to separate each of those results into both fields so you can do something like this:
for result in query_results:
    part1, part2 = result
    print('{} - {}'.format(part1, part2))

which will give you output like this:
test0 - something0
test1 - something1
testing0 - somethingelse1

Rather than just printing these out the plan for my code is to create a json type dictionary that I can easily search.
Answer: If you want to simply remove all brackets from a result, you can use replace() method. The syntax is string.replace(string_to_replace, string_to_replace_with).
eg:
result = str(result).replace("()", "")

This will need to be done for each bracket type, I believe. So another round for "[]".
Note that after you remove all brackets, splitting a result set to individual rows might be hard if the brackets are the delimiters.


jquery ui sortable, div block in first item not visible

Question: I want to make the div - "small_box" in the first item of sortable list to be always not visible. I tried with jquery first() but that works only once and only for one and same element whenever it's dragged. How can i simple make it back to be visible when I dragg it into other than first place and then make invisible "small_box" for the item which jumps in the first place?
I put the live example here: http://jsfiddle.net/kriskasper/3knnn/

small box

big box

small box

big box

small box

big box

small box

big box

And here is jquery ui function:
    $(function() {
    $( "#sortable" ).sortable({
        connectWith: ".connectedSortable",
        placeholder: "ui-state-highlight",
        forcePlaceholderSize: true,
        opacity: 0.6,
        revert: 70

    });
});

Please help.
Answer: You should play with the sortable plugin events. The sortreceive event is fired when the connected element receives an item. My guess would be something like ...
$("#sortable").bind("sortreceive", function(event, ui) {
    $(".connectedSortable .small_box").show();
    $("#sortable .small_box").first().hide();
});

Comment: I used this:

`$(function() {
 $( "#sortable" ).sortable({
        connectWith: ".connectedSortable",
        placeholder: "ui-state-highlight",
        forcePlaceholderSize: true,
        opacity: 0.6,
        revert: 70

});

$("#sortable").bind("sortreceive", function(event, ui) {
$(".connectedSortable .small_box").show();
$("#sortable .small_box").first().hide();
});

});`

But it's not working, I don't know what I'm doing wrong. [ttp://jsfiddle.net/3knnn/4/](http://jsfiddle.net/3knnn/4/)
Comment: You got me all confused with the connectedSortable, which you're not using, since you only have one list. You can solve this with a simple css `ul li:first-child .small_box { display: none; }`
Comment: Check out these two fiddles. one with css, the other with js. http://jsfiddle.net/3knnn/11/ and http://jsfiddle.net/3knnn/14/
Comment: Hey Mark, thanks for help very much! Sorry, I should have clear it from connectedSortable class, it left from the example i'm working on which has two lists.


Como realizar operação matemática dentro da view em MVC?

Question: Estou criando uma aplicação web MVC 5 para estudos e tenho uma dúvida: é possível realizar uma operação matemática na view?
Queria realizar a multiplicação da linha 16. Qual seria a solução?
@foreach (var item in Model) {

        @Html.DisplayFor(modelItem => item.users.first_name_user) @Html.DisplayFor(modelItem => item.users.last_name_user)

        @Html.DisplayFor(modelItem => item.product.name_product)

        @Html.DisplayFor(modelItem => item.quantity)

        R$ @Html.DisplayFor(modelItem => item.product.price)

        @Html.DisplayFor(modelItem => item.quantity) * @Html.DisplayFor(modelItem => item.product.price) ******Preciso Realizar essa multiplicação****

        @Html.ActionLink("Editar", "Edit", new { id = item.id_order }) |
        @Html.ActionLink("Detalhes", "Details", new { id = item.id_order }) |
        @Html.ActionLink("Excluir", "Delete", new { id = item.id_order })

}

Tentei usar o código dessa forma:
R$ @Html.DisplayFor(modelItem => item.quantity * item.product.price)

Apresentou esse erro:
Comment: Por que não monta o *model* já com esse campo calculado. È até o mais certo a fazer.
Comment: Hum, não tinha pensado no model. Ele veio montado automaticamente de um banco sql server. Eu alterando o model, causa algum impacto no meu banco?
Comment: Não, é o correto.
Comment: Você está usando ORM ???
Comment: Pra falar a verdade, tem uma semana que comecei a mexer em asp. Então desconheço ORM, mas vou pesquisar sobre.
Answer: O ideal não é fazer processamento na view, então a solução correta é criar o modelo que já inclua o valor total calculado como um campo do model (pode ser uma viewmodel se não quiser fazer no modelo normal), e aí pode usar facilmente.
Se quiser a forma incorreta, mas funciona, pode fazer a conta antes e depois usar o resultado, algo assim:
@{
foreach (var item in Model) {
    var total = item.quantity * item.product.price;
    ...
    @Html.DisplayFor(modelItem => total)
}

Coloquei no GitHub para referência futura.
Comment: Adicionei na model o cálculo que resolveu o problema

public decimal total { get { return quantity * product.price; } }

e na view  chamei o total


Como deixar minha GridView no meio da tela?

Question: Como deixar minha GridView c# no meio da tela ?
ja tentei coloca-la em uma div e atribur aling = center
mas não deu certo.
Alguem tem uma sugestão ?
<asp:GridView ID="GridView1" runat="server" CellPadding="4"
        ForeColor="#333333" GridLines="None" HorizontalAlign = "Center">
    <AlternatingRowStyle BackColor="White" />
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    <SortedAscendingCellStyle BackColor="#FDF5AC" />
    <SortedAscendingHeaderStyle BackColor="#4D0000" />
    <SortedDescendingCellStyle BackColor="#FCF6C0" />
    <SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>

Comment: Dê uma medida a GridView e  tipo style="width:500px;margin:0 auto 0 auto;" talvez ajude
Comment: Poste seu código, por favor
Answer: tudo bem?
Quando você está criando um GridView em uma página ASP.Net, uma das coisas que você pode tentar é colocar uma

 em torno dele, a fim de centralizar o GridView na página, através da atribuição de text-align: center para o seu div , mas isso não vai funcionar. Pois os mais recentes CSS não funcionam desta forma =(.
A fim de fazer isso, supondo que você tenha uma classe CSS que você está usando com o GridView, basta adicionar o seguinte CSS para sua classe:
margin-left: auto;
margin-right: auto;

Espero ter ajudado.
Comment: O `margin: 0 auto;` simplifica isso @Danilo. Porém é a mesma coisa. :)


Proper way to share variables in classes Python

Question: I am trying to develop an AI for a game using Python. Therefore, I have a class "Game" and a class "AI".
I would like to use a variable of Game (e.g. the board of Game) inside AI, but I am not sure what is the best way to do it. Right now the only way I found to pass information from game to AI is to put it as an argument every time. I feel like there is a way better way to share variable with AI without needing to put in argument every time.
I would do something a little similar to that (I know this code can't work, but still) :
class Game():
    def __init__(self):
        self.board = 1 #It will be an array
        self.ai = AI(self.board)

    def functionThatUpdateTheBoard(self):
        self.board = 2

    def useTheAI(self):
        print(self.board)
        self.ai.getAction()

class AI():
    def __init__(self,board):
        self.board = board
        print(self.board)
    def getAction(self):
        print(self.board)

game = Game()
game.functionThatUpdateTheBoard()
game.useTheAI()

and getting :
1
2
2

thanks for the help :)
Comment: It depends. If `board` is an immutable object like an int then this wont work. If you use an array and modify it, it will work (though mutable stuff tend to introduce bugs since you have to be very careful). Alternatively change `AI(self.board)` to `AI(self)` and use `self.game.board` inside `AI`
Comment: That does indeed work!
You said it may introduce bugs, what do you think the best way to tackle this then ? Call the variable board to every functions ?
Comment: Read about [scopes-and-namespaces - global](https://docs.python.org/3/tutorial/classes.html#scopes-and-namespaces-example) and [class-variables](https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables)
Answer: See if you can make use of Observer Pattern.
Something like, Create subscriber and call when "board" changes value in Game class.
If a class needs the updated value of "board" they can subscribe, which gets triggered on value of "board" changes.
In this way, you can be very sure of the value being changed irrespective of immutability of data type used.
class Game(object):
 def __init__(self):
    self.board = 1
    self.observers = []

 def functionThatUpdateTheBoard(self, new_value):
    # you can change this to setter ,
    # refer https://www.tutorialspoint.com/What-are-Getters-Setters-methods-for-Python-Class
    self.board = new_value
    for fn in self.observers:
        fn(self.board) # send your board value here.

 def subscribe(self, callback):
    self.observers.append(callback)

class AI(object):
  def game_board_value_changed(self, value):
      print("Printing value in AI class")
      print("Value of 'board' changed in Game class to {}".format(value))

game = Game()
ai = AI()
game.subscribe(ai.game_board_value_changed)
print("*"*50)
modified_value = 10
print("Board value changed in Main to {}".format(modified_value))
game.functionThatUpdateTheBoard(modified_value)
print("*"*50)
modified_value = 100
print("Board value changed in Main to {}".format(modified_value))
game.functionThatUpdateTheBoard(modified_value)
print("*"*50)

**************************************************
Board value changed in Main to 10
Printing value in AI class
Value of 'board' changed in Game class to 10
**************************************************
Board value changed in Main to 100
Printing value in AI class
Value of 'board' changed in Game class to 100
**************************************************

Comment: I am currently reading about Observer pattern, but I'm not sure how to implement what you said. I would like to know if you would could show me a very simple implementation for this example
Thanks !


What could be causing slow DNS lookups for domains that I host the DNS for?

Question: I currently host a TinyDNS server that serves DNS requests for all domains with nameservers that point to the server. The data configuration file is:
.
+*:184.108.40.206

with 188.8.131.52 being the IP of the server. It's intended to be a wildcard DNS server (any nameserver that points to this server will return A records that point to itself).
However, DNS lookups have been really slow for these domains when attempting to access the website on the domain and I have been experiencing this on different devices and networks (sometimes up to 10 seconds). Are the DNS records that are propagating from my DNS server somehow malformed? Here is an example domain: http://trp.do/s/
EDIT:
I know it's a DNS issue and not a website issue by inserting various headers with timestamps at different points within the request and response stack. They are within ms whereas the actual request from start to finish is around 5-10 seconds. When using Google Chrome, it appears to be stuck on "Resolving Host" on the bottom left as well. I've dug deeper and used Rack-Mini-Profiler @ https://github.com/MiniProfiler/rack-mini-profiler to profile the requests and listed Domain Lookup in the range of 5-10 seconds as well. So that's why I'm fairly confident it's a DNS issue and not a website performance issue.
Addressing the concerns of the single point of failure, I'm aware of it but don't think it should be affecting performance on a consistent level.
My burning question is... can a malformed DNS record even cause a situation like this?
Comment: 1) Please define "really slow". Are you properly differentiating between DNS slowness and website slowness? What research have you done to demonstrate this? Show, don't tell. 2) Both nameservers are pointing at the same IP address. This is a brittle configuration that is both a single point of failure, and unforgiving of network problems between client and server -- which may or may not be related to your described issue. Please take a step back from  hosting your own DNS and read a book on the basic subject matter.
Comment: Also see: [Should we host our own nameservers?](http://serverfault.com/questions/23744/should-we-host-our-own-nameservers)
Comment: Do you have a new example, it appears that the `trp.do` domain has been delegated elsewhere now (`ns{1,2,3,4}.linode.com`)? What I wonder is if tinydns deals properly with EDNS0 queries. From what I know tinydns is pretty outdated (last release in 2001, but with some third party patches available) so I don't really know what the expectations should be? If it fails to understand the initial queries, maybe that could lead to some strange issues?
Comment: @Håkan The trp.do link used to contain the name of one of his domains but the link has "self-destructed" already.
Comment: @HåkanLindqvist Sorry about that, can you try this, thanks in advance! http://trp.do/s/fe6eKQ9mFkKahAxHv
Comment: @Axsuul The one thing that stands out to me is that your nameserver is denying the existance of `NS` records for that domain name. From the response it looks like you actually have a root zone (`.`) set up rather than a zone by the name you mentioned. (That empty response includes `.   2560 IN SOA ns. hostmaster. 1411742341 16384 2048 1048576 2560`)
Comment: @HåkanLindqvist Ah ok interesting, what sort of effect will that have?
Comment: @Axsuul The effect of that may not necessarily match the problem described in the question but if someone looks up `example.com NS` they will from then on know for a fact that there are no `NS` records, which seems like a potentially very bad thing for subsequent queries.
Answer: A malformed response from an individual authoritative server is unlikely to cause this problem. Whether the first server is taking too long to reply and times out, or the reply is malformed (truncated, mangled, etc.), the recursive DNS server can retry with the next authoritative nameserver. If all servers return bogus data, there is a major problem somewhere.
This assumes that you are following best practices and operating multiple nameservers that are georedundant. Your configuration fails this standard on both counts. It may seem like I'm beating a dead horse here, but it's truly the basics of DNS: this configuration places your company assets in jeopardy and you are basically at the mercy of whatever network events happen between everyone on the internet and your single geoisolated server.
Start by fixing this problem. Until you have addressed it, everything else is kind of moot. The 5-10 second delay may very well be due to the resolver library attempting to append your search suffixes to the original (failed) query, but the current config is fundamentally broken and kinda pointless to troubleshoot further at the moment.


MIN/MAX of a right circular cylinder

Question: An oil can is to be made in the form of a right circular cylinder to hold ONE QUART of oil. What dimensions of the can will require the LEAST amount of material?
The quart of oil is to be in terms of 'a', not an actual calculation of how many cubic cm a quart is
Formula: $V = (\pi)r^2h = a^3$
Comment: So, what do you think the next step is?
Answer: HINT
How much material used is determined the by the area of the container.
Area of the bottom + area of the side
$$=\pi r^2 + 2\pi rh = \pi r^2 + \frac{2a^3}{r}$$

MIN/MAX of a right circular cylinder


Print statement only once in a while loop (Python, Selenium)

Question: driver.get("Link of product site.")
while "Not available right now." in driver.page_source:
print("Not available right now, reloading site until it is available..")
driver.refresh()
sleep(45)

else:
print("It is available! Gonna order it now..")

The problem here is that it gives me lots of print statements every 45 seconds. How is it possible that it gives the statement "Not available right now, reloading site until it is available.." only once until the else statement is true?
(Written in Python, Selenium)
Thanks for any help!
Comment: Code won't work; it's missing some pieces; there is no context. Please [read how to ask a question](https://stackoverflow.com/help/how-to-ask)
Comment: Alright, changed it. Hope it's clear now.
Answer: You just need to change the order of your code, and you don't need an if..else statement.  Let it default to "Checking availability...", and then start your loop which will refresh the page every 45 seconds until that text you specified is gone from driver.page_source
driver.get("Link of product site.")
print("Checking availability...")
while "Not available right now." in driver.page_source:
    sleep(45)
    driver.refresh()

print("It is available! Gonna order it now..")

If it is available immediately it will just print these both out right after each other..
Checking availability...
It is available! Gonna order it now..

Otherwise there will be a time delay between them.
If you want to add a timestamp so you know how long it took to become available use this:
import datetime

current_time = datetime.datetime.now()

driver.get("Link of product site.")
print("Checking availability...")
print(current_time)
while "Not available right now." in driver.page_source:
    sleep(45)
    driver.refresh()

print("It is available! Gonna order it now..")
print(current_time)

Comment: It's nicer to have sleep before the refresh, otherwise the page will be visually updated but the console output will be delayed.
Comment: Thanks a lot for your help!
Comment: @Niloct.  Good point.  Updated code to reflect


Limit of integration - double integral

Question: $$\iint_D f $$
where $D$ is region given by $D = \{(x,y) | 0 < ax + by < \pi,\  0< cx + dy < \pi\}$
My question is how can i find the limit of integration, is it by change of variables? Please only give me hints about limits of integration and please also do not evaluate the question
Thank you very much
Answer: Make a change of variables $$ u = ax + by, \ v = cx + dy $$
Then
$$ du dv = \left|\begin{matrix} \dfrac{\partial u}{\partial x} & \dfrac{\partial u}{\partial y} \\ \dfrac{\partial v}{\partial x} & \dfrac{\partial v}{\partial y} \end{matrix}\right| dxdy = (ad - bc)\ dxdy $$
Thus
$$ \iint_{D(x,y)} \sin(ax+by)\sin(cx+dy)\ dxdy = \frac{1}{ad-bc}\iint_{D(u,v)} \sin(u)\sin(v)\ dudv $$
The limits of integration should be obvious now.
Answer: More generally: when the domain of the double integral
$$\iint_D f$$
is limited by level curves of nice functions:
$$D = \{(x,y)\,|\, g_1\le g(x,y)\le g_2, h_1\le h(x,y)\le h_2\}$$
and the transformation
$$(u,v) = (g(x,y),h(x,y))$$
is injective, we have usually a good change of variables.
Ditto for triple integrals with domains limited by level surfaces.
Comment: Thank you very much :) Helpful for me :)

Limit of integration - double integral


How can I skip the validation checks(not even entering the validation checks) in ActiveRecord?

Question: I have a model where geocodes are calculated before the model is saved using geokit-rails plugin. I have to run a Rake task where the state field is replaced by its abbreviation in the database. I was planning to use a hash with the states and its mapped abbreviations for this task. While doing this, I dont want to calculate the geocodes again, as this will take time for each record. Here is my code:
Site.all.each do |site|
  site.state = Site.convert_to_abbr(site.state)
  site.save(false)
end

Site model
US_STATES = {
  "Alabama" => "AL",
  "Alaska" => "AK",
  ..
  ..
}

before_save :generate_lat_lon

def generate_lat_lon
  puts "Entered validation"
  @address = "#{address1}, #{city}, #{state}"
  @location = Geokit::Geocoders::MultiGeocoder.geocode(@address)

  if @location.success
    self.lat = @location.lat
    self.lon = @location.lng
  else
    self.lat = nil
    self.lon = nil
  end
end

def self.convert_to_abbr(state_string)
  US_STATES[state_string.to_s.strip.titlecase] ? US_STATES[state_string.to_s.strip.titlecase] : state_string
end

But the problem with the above code is that, with save(false), the validations are skipped, but the validation checkings are not skipped. So, the geocodes are calculated before saving a record and this is very time consuming. Is there a method to skip validation checking also in Rails?
Answer: You could add an attr_accessor :calculate_lat_long, and set that to true before anything that calls save.
Your model would then have:
before_save :generate_lat_lon, :if => :calculate_lat_lon

Comment: thanks..good solution..for making the default value `true`, should I use `def initialize; super; @calculate_lat_lon = true; end` and set `calculate_lat_long` to `false`, before this specific action, so that I will not have to change code in other parts.
Comment: or maybe perhaps, use `attr_accessor :dont_calculate_lat_lon` and use it like this `before_save :generate_lat_lon, :unless => :dont_calculate_lat_lon` and set it to `true` before my specific method.
Comment: I would probably use the :dont_recalculate/unless variant if recalculation was the more common case. :)
Comment: And you probably don't want to override initialize. Just drop an after_initialize method or callback in there.
More: http://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html
Comment: I went by the `:dont_calculate` method..aand yes, recalculation is the more common case and I agree it is a bad idea to override `initialize`..`after_initialize` seems a better option..many thanks for your help..
Answer: You could use
site.send(:update_without_callbacks)

http://ackbar.rubyforge.org/classes/ActiveRecord/Base.html#M000082