Alinhamento de div dentro de html

Question: Tenho duas divs, quando oculto a primeira preciso que a segunda suba para o lugar dela, porém ela não se mexe, como posso fazer para ela fica no lugar da primeira div, ou seja subir?

Segue o código:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Módulos</title>

    <form class="form" id="wizard_with_validation" method="POST">

                                    <input id="id_id" name="id_id" type="hidden" class="form-control input-style" autofocus required>
                                    Descrição*
                                    <input id="id_nome" name="id_nome" type="text" class="form-control input-style input-casesensitive" autofocus required>

    </form>

Comment: cara, copiei seu html/css e tem algo muito sinistro ai, melhor vc rever o css, porque é alguma coisa que vc inseriu, vou postar um html com bootstrap básico mostrando um exemplo sem sobrescrever nada do bootstrap.
Comment: Existe uma diferença entre utilizar `visibility:hidden` e `display:none`. Veja qual é a diferença [nesta pergunta](https://pt.stackoverflow.com/q/44678/5878).
Answer: Existe uma diferença entre utilizar visibility: hidden e display: none em um elemento. A diferença já foi discutida anteriormente aqui:
Qual a diferença entre display:none e visibility:hidden?
Resumindo, utilizando o visibility: hidden, o espaço do elemento continua sendo ocupado, não afetando o layout da página. Se você deseja que o layout responda à omissão do elemento, use display: none.
Exemplo utilizando visibility: hidden

.red {
  background: red;
  height: 100px;
}

.green {
  background: green;
  height: 100px;
  visibility: hidden;
}

.blue {
  background: blue;
  height: 100px;
}

Este elemento será ocultado

Exemplo utilizando display: none

.red {
  background: red;
  height: 100px;
}

.green {
  background: green;
  height: 100px;
  display: none;
}

.blue {
  background: blue;
  height: 100px;
}

Este elemento será ocultado

Cuidado: Ao definir a propriedade display: none utilizando estilo inline você não será capaz de exibir o elemento através do CSS ou do JavaScript, pois estilos inline possuem prioridade maior que estes, não sendo capaz de sobrescrevê-lo.

#teste {
  display: block;
}

Stack Overflow em Português

Leia sobre em Qual seletor css tem prioridade.
Comment: era isso mesmo. Obg
Answer: Cara, o que pode fazer é criar uma função no javascript, por exemplo, acionada ao clicar num link, botão, etc, que oculta a primeira DIV e altera uma classe CSS da segunda DIV, mudando a posição dela na tela. De modo que ela ocupe a posição anteriormente ocupada pela outra. Isso se as duas estão visíveis ao carregar a página. Uma embaixo da outra. Mas, se uma será mostrada só quando a outra for fechada, ai a resposta já foi dada.
Comment: Pode utilizar `display: none` mesmo se os dois elementos estiverem visíveis. O layout será ajustado sozinho. Utilizar JS para isso seria gambiarra.

Alinhamento de div dentro de html


Incompatible Declaration in Implementation file in C++

Question: I have a couple incompatible declarations in my implementation file for my lab that I cant figure out why. I'm still learning C++ but I cant see what this problem is. Basically all the program is supposed to do is when its run is to spit out a message at the end stating the Welcome to the grade book to and state the class for the grade book along with the Teacher. However my set and get statements in my Implementation file wont allow me to compile because of a incompatibility. I could use a few tips Thank you.
Here is my code for all three files:
Header -
#include <string>

class GradeBook
{
public:
    explicit GradeBook(std::string);
    void setCourseName(std::string);
    std::string getCourseName() const;
    void displayMessage()const;
    void setInstructorName(std::string);
    std::string getInstructorName() const;
private:
    std::string courseName;
    std::string instructorName;
};

Implementation file -
#include <iostream>
#include "GradeBook.h"
using namespace std;

GradeBook::GradeBook(string name): courseName(name)

{

}

void GradeBook::setCourseName() const
{
    courseName = name;
}

string GradeBook::getCourseName() const
{
    return courseName;
}

void GradeBook::setInstructorName() const
{
    instructorName = name;
}

string GradeBook::getInstructorName() const
{
    return instructorName;
}
void GradeBook::displayMessage() const
{
    cout << "Welcome to the grade book for\n" << getCourseName() << "with"     << getInstructorName << "!" << endl;
}

Main file-
#include <iostream>
#include "GradeBook.h"
using namespace std;

int main()
{
    GradeBook courseName("COP2224: Intro To C++ Programming");
    GradeBook instructorName("Heidi Gentry Kolen");
}

Comment: Where are the error messages
Comment: If you had taken the time to reduce the code to a minimal example, you would have found the error yourself.
Comment: @AverageJoe: no, it's not minimal ... here's the minimal version you should be able to arrive at before posting a new question to SO: `class GradeBook { public: void setCourseName(std::string name) const { courseName = name; } private: std::string courseName; }` all in the header file. In fact, this small program might have shown you what you needed just by itself.
Comment: The funny thing is this is minimal, from a starting point in learning this. Yes it can be simplified but i need to learn more.
Comment: [**Minimal, Complete, Verifiable Example**](https://stackoverflow.com/help/mcve).
Comment: I say all that not to be mean, but to tell you one of the most important things I know about programming: **the compiler is your best teacher**. Write small programs, and make sure they _build_ and _run_, then make them bigger. I've been a professional programmer for over twenty years, and I still do this everyday ... if you were to add the word _test_ to the _build_ and _run_ advice, this would be one of my number one things that I tell beginning programmers.
Answer: void setCourseName(std::string);         // declaration in .h
void GradeBook::setCourseName() const    // implementation in .cpp

void setInstructorName(std::string);      // declaration in .h
void GradeBook::setInstructorName() const // implementation in .cpp

See the difference?  Your implementations are missing the name parameter and have trailing const modifiers.  You need to correct those mistakes:
void GradeBook::setCourseName(std::string name)
{
    courseName = name;
}

void GradeBook::setInstructorName(std::string name)
{
    instructorName = name;
}

The signature of an implementation must match the signature of its declaration.
Comment: Hmm i totally didnt catch that. I appreciate it.  Like i said i am still learning but Thank you.
Answer: void GradeBook::setCourseName() const
{
    courseName = name;
}

That's wrong.
Not only you missed to give it the same signature as from the declaration
void setCourseName(std::string);

It would never work as const member function, unless courseName is declared as mutable. Also name isn't declared in this context.
I'd guess that's all simply a typo.
Answer: declaration is:
void setCourseName(std::string);

while in definition
void GradeBook::setCourseName() const

which is incorrect
correct definition should be
void GradeBook::setCourseName(std::string name)

Comment: Was about to comment, but you got it: now that you've removed `const`, as in other answers, I'm upvoting.
Comment: And if you downvoted QuestionAndAnswer for it, maybe you could remove it.
Comment: @JohnCastleman: I have not downvoted QuestionAndAnswer for it.
Comment: ok good ... his answer wasn't right, but wasn't so wrong it needed a downvote, IMHO.
Answer: You don't need an explicit keyword before GradeBook's constructor.
Delete const modifier after setInstructorName and SetCourseName in implementation file.
Comment: how to removal of const will help to solve the problem
Comment: Removing `const` *is* definitely part of the solution (*I'm* not one of the downvoters), but `explicit` keyword is definitely in there for a reason (which I think is actually why you're getting downvotes)
Comment: @Sumeet, Set methods designed to change class's field value. Const keyword restricts any changing in class. If Set methods in this example mean something else, then, yes, my answer is useless.
Comment: @JohnCastleman, Yes, explicit keyword is not the main reason. It was just by the way.
Comment: @Summet, Oh... I see now. I don't noticed args list. My fault.
Comment: @QuestionAndAnswer: Agree set method used to change the value but that changed value should be provided in function arguments without which it will not work.


Question on regex not performing as expected

Question: I am trying to change the suffixes of companies such that they are all in a common pattern such as Limited, Limiteed all to LTD.
Here is my code:
re.sub(r"\s+?(CORPORATION|CORPORATE|CORPORATIO|CORPORATTION|CORPORATIF|CORPORATI|CORPORA|CORPORATN)", r" CORP", 'ABC CORPORATN')

I'm trying 'ABC CORPORATN' and it's not converting it to CORP. I can't see what the issue is. Any help would be great.
Edit: I have tried the other endings that I included in the regex and they all work except for corporatin (that I mentioned above)
Comment: You could add a word boundary at the end `|CORPORATN)\b` https://regex101.com/r/NeAsZY/1 and perhaps shorten it to `\bCORPORA(?:T?TION|TE|TIO?|TION|TIF|TN)?\b` See https://regex101.com/r/eW7js8/1
Answer: I see that all te patterns begins with "CORPARA", so we can just go:
import re
print(re.sub("CORPORA\w+", "CORP", 'ABC CORPORATN'))

Output:
ABC CORP

Same for the possible patterns of limited; if they all begin with "Limit", you can
import re
print(re.sub("Limit\w+", "LTD", 'Shoe Shop Limited.'))

Output:
Shoe Shop LTD.

Comment: Thank you so much. This simplifies everything and more readable too! Appreciate the help! :)


Select columns that don't contain any NA value in R

Question: How to select columns that don't contain any NA values in R? As long as a column contains at least one NA, I want to exclude it. What's the best way to do it? I am trying to use sum(is.na(x)) to achieve this, but haven't been successful.
Also, another R question. Is it possible to use commands to exclude columns that contain all same values? For example,
  column1  column2
row1   a        b
row2   a        c
row3   a        c

My purpose is to exclude column1 from my matrix so the final result is:
   column2
row1   b
row2   c
row3   c

Comment: See http://stackoverflow.com/questions/2643939/remove-columns-from-dataframe-where-all-values-are-na/12614723#12614723 and modify appropriately.
Answer: Remove columns from dataframe where ALL values are NA deals with the case where ALL values are NA
For a matrix, you can use colSums(is.na(x) to find out which columns contain NA values
given a matrix x
x[, !colSums(is.na(x)), drop = FALSE]

will subset appropriately.
For a data.frame, it will be more efficient to use lapply or sapply and the function anyNA
xdf[, sapply(xdf, Negate(anyNA)), drop = FALSE]

Answer: Also, could do
new.df <- df[, colSums(is.na(df)) == 0 ]

this way lets you subset based on the number of NA values in the columns.
Comment: Could you please [edit] in an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/q/148272/274165), because they don't teach the solution. (This post was flagged by at least one user, presumably because they thought an answer without explanation should be deleted.)
Answer: Also if 'mat1' is the matrix:
indx <- unique(which(is.na(mat1), arr.ind=TRUE)[,2])
subset(mat1, select=-indx)


EJB authentication

Question: Here is what I'm trying to do: I have an authentication EJB that can grant user a "ticket" (pair of key and token) by validating username and password. Clients should pass the ticket every call to remote EJB and such ticket should be able to be fetched by EJB (method, or interceptor) and EJB/ or interceptor should validate the ticket and determine whether the call is valid or not.

I don't want to add ticket as parameter to each function that requires authentication, and I believe there should be a way to implement this. I've looked through several articles about JAAS custom login module, but still can't find a non-vendor specific way to do this. (And I am trying to avoid vendor specific implementation)

If JAAS can't do the job, is there anything like "header" in EJB?
Answer: Couldn't you just use roles to perform this authorization?  Instead of granting a ticket to a user, assign him a role.
Then, it's just a matter of using the inbuilt functionality of checking whether a user is in a role or not.
Answer: Although I agree with @EdH, i.e. use @RunAs, you can accomplish what you want by adding to the EJB context your token.
Red Hat does something similar here by using the interface EJBClientInterceptor.
By looking the code of ReceiverInterceptor (which implements the EJBClientInterceptor) you can see how to modify the EJB context (on the client-side) and add your token:

context.setReceiverInvocationContext(new
EJBReceiverInvocationContext(context, receiverContext));
context.sendRequest();

EJB authentication


Non separable, non homogeneous, linear equation

Question: <code>  y'=(2x-y+3) / (x+3y-2)
</code>
if the coefficients are same this equation can be solved by replacement by a variable function (V) but here in this case coefficient are not same. how would it be solved ?
(just curious and cannot think of any solution)
Comment: this is an equation of Abel type
Comment: Also after shift $u = x + a$, $w = y + b$ you can make similar equations homogeneous. But if it's exact, it is much easier to solve it as an exact equation :)
Answer: Hint
Change variable defining $x+3y-2=z$. Replace and simplify. The equation will become $$z'=\frac{7 (x+1)}{z}$$ which is separable and looks quite simple.
Edit
Suppose the equation to be $$y'=\frac{a x+b y+c}{x+d y+e}$$ $$x+d y+e=z \implies y=\frac{z-x-e}{d}\implies y'=\frac{z'-1}{d}$$ Replace an simplify. You should arrive to $$-d (a x+c)+b (e+x)+z \left(z'-b-1\right)=0$$ which becomes separable if $b=-1$ (which is your case). In such a case,
$$z \,z'=x (a d+1)+(c d+e)$$ which is simple too.


Is there a measure to describe the degree of linear separability?

Question: I know that given two sets of points, one can use linear programming to see if there is a solution/hyperplane that linearly separates the two data sets. But this holds for completely linearly separability. I wonder in case that the two sets can only be linearly separated by neglecting some points in both sets, then is there a measure to describe the degree of linear separability?

In other ways, the problem may be transformed to

At least how many points we need to kick out to have linear
  separability? (and the degree may be measured by the number of points
  to be kicked out divided by sample size)

But is this computationally expensive to implement using computers? Or is there any better way to measure the degree of linear separability?
Comment: See [here](http://www.joyofdata.de/blog/testing-linear-separability-linear-programming-r-glpk/)@hxd1011
Comment: @hxd1011: See also [Konis (2007), "Linear programming algorithms for detecting separated data in binary logistic regression models", DPhil., U. Oxf.](http://ora.ouls.ox.ac.uk/objects/uuid:8f9ee0d0-d78e-4101-9ab4-f9cbceed2a2a).
Comment: use linear programming to see if it is separable? Could you give me a reference for that?
Comment: @Scortchi thanks for great reference. It is good to see it is a PHD dissertation, I thought it is trivial and everyone knows, but I do not know....
Comment: For linear programming, also see [this answer](http://stats.stackexchange.com/a/94537/127790). For the original question, you might be able to formulate using a "soft margin" classifier (e.g. [SVM](https://en.wikipedia.org/wiki/Support_vector_machine#Computing_the_SVM_classifier)), and then use the lagrange multipliers to diagnose the "degree of linear separability".
Answer: As noted in the question and comments, a dataset of $m$ points $(\boldsymbol{x}_i,y_i)$ with $\boldsymbol{x}_i\in\mathbb{R}^n$ and $y_i\in\{-1,+1\}$ is linearly separable if we can find a normal vector $\boldsymbol{a}$ and scalar bias $b$ such that the linear inequality
$$y_i(\boldsymbol{a}^T\boldsymbol{x}_i+b)\geq 1$$
is satisfied for all $i=1,\ldots,m$. Physically this says that for each point $\boldsymbol{x}_i$, the signed distance $d_i$ to the separating plane has sign $y_i$ and magnitude at least $\|\boldsymbol{a}\|$.
This can be written also as
$$\boldsymbol{w}^T\boldsymbol{z}_i \geq 1$$
where
$$\boldsymbol{z}_i = \begin{bmatrix}\boldsymbol{x}_i \\ 1\end{bmatrix} y_i
\text{ , } \boldsymbol{w}=\begin{bmatrix}\boldsymbol{a} \\ b\end{bmatrix}$$
As noted in the question, this is essentially a linear program with a "0" objective function.
The proposed "degree of separability" measure $S_\min$ can be expressed as
$$ \min_{\boldsymbol{\sigma},\boldsymbol{w}} S[\boldsymbol{\sigma}] $$
where $\boldsymbol{\sigma}\in\{0,1\}^m$, the function $S$ is defined by
$$ S[\boldsymbol{\sigma}] = \sum_i\sigma_i  = \boldsymbol{1}^T\boldsymbol{\sigma} $$
and the minimization is subject to the constraint
$$ \sigma_i(\boldsymbol{w}^T\boldsymbol{z}_i - 1) \geq 0 \text{ , } i=1,\ldots,m$$
This is a (slightly nonlinear) "mixed integer programming" problem, a problem class which is NP hard (even in the linear & binary case).
Now a more feasible alternative could be to solve a "soft-margin" classification problem using a standard approach like SVM*. The tolerance and/or lagrange multiplier variables could then be used to quantify "degree of separability".
(*For $\lambda\approx 0$ the SVM will essentially reduce to a "softened" version of the linear program above. However to get meaningful distances, you will have to normalize tolerances by $\|\boldsymbol{a}\|$.)

Update: Using something like soft-margin SVM can give you an idea of which points are "hard" to separate, but it would not necessarily address your question of "how many points must be removed to allow a hard-margin split?"
However, I think that if you pre-process the $\boldsymbol{X}$ matrix by whitening, then it should be possible to get some more consistent results. (In terms of numerical offset-scales and directional clustering of the problem points.)


Why is InputStream.close() declared to throw IOException?

Question: The java.io.InputStream.close() method is declared to throw an IOException. Under what circumstances would such an exception actually be thrown?
Edit: Yes I have read the javadoc. Can anybody be more specific than "when an I/O error occurs"? What I/O error can occur while closing an InputStream?
Comment: if an I/O error occurs.
Comment: @Martinsos: The JavaDoc of `java.io.Closable.close` writes: If the stream is already closed then invoking this method has no effect.
Comment: Maybe if it is already closed?
Comment: @meriton I think you will find your answer to "What I/O error can occur... " question in the IOException class not in InputStream class javadoc. As mentioned in my answer I too expected it to be in InputStream, could not find it and had my "Ahha" moment when looking at all the subclasses of IOException.
Answer: In the case of input stream reading from a file system, an error can be raised while the file system itself updates the last access time metadata, or some other metadata, on a file during closure. Anyway, this happens almost never in practice.
In the case of an input stream reading from a network connection, an error on closure is a bit more conceivable. A normal closure of a network socket actually involves a closure request (TCP/IP FIN packet) being sent over the connection and waiting for the other end to acknowledge this closure request. (In fact, the other end of the connection then in turn sends a closure request, which the closing end acknowledges.) So in the case of a socket input stream, a closure operation actually involves sending traffic over the connection and the closure can thus fail with an error.
Note that in many implementations, close() generally doesn't throw an IOException if the stream is already closed; it simply fails silently to close the stream again.
Answer: I'm looking through the Java source code, and have found something interesting which is indicative of the IOException reason. InputStream is an abstract class. We therefore can't predict the kind of input which will be closed, so it's good to keep information flowing.
Whatever code uses that input stream needs to be able to throw an IOException, because there is a chance that closing the input stream may fail. If it fails, whatever's using the implementation needs to know about it, because there's a good chance it needs to be handled.
It's important to understand the layout of the Exception structure in Java. Every exception, of course, extends Exception. However, there are also broader categories of exceptions: java.lang.IOException is one of these, and covers all possible input/output exceptions. When we say there has been an I/O error, we're referencing anything which falls under IOException. As a result, many exceptions extends this one, e.g. FileNotFoundException, EOFException, etc. as it's important to have a broad, overarching exception to manage these.
As a result, any IO class will need to be able to throw any of the various IOExceptions on close. close() therefore must throw IOException - this gives its implementation the ability to throw any of the extensions of IOException as well. This is why close() throws IOException - exceptions are inherited, and you need to be able to any of the IOExceptions when closing a stream.

Here are a couple scenarios worth noting:

You can't close an IOStream twice, though this generally doesn't throw an exception if you do
The content becomes inaccessible (e.g. a disk was unmounted) (The close() is actually critical for the operating system, as it needs to have an indicator of when the file is no longer busy)
The generic source has closed
Any generic failure not covered by all other subclasses of IOException (e.g. FileNotFoundException)

You can check what caused an IOException by running Exception.getMessage().
Comment: I may be wrong, but it seems like throwing some kind of unchecked Exception would have been a better design choice for the `close()` operation.
Comment: Closing a closed stream "has no effect" according to the JavaDoc of `java.io.Closable.close`. As for the other causes, I see how they could occur when opening or reading from a stream, but when closing?
Comment: @mertion Well... yes. For instance, if you're reading from a disk, the closure step is _critical_ in telling the operating system nothing's using the file anymore. If the program can't do that, it makes sense to alert the program.
Comment: @meriton I figured out the exact reason why it exists. Please see my edits.
Comment: Why could telling the operating system that it may free the file descriptor fail? And what good would it to to tell the program about that? I mean, if the operating system won't close the file when asked, what can the progam do?
Comment: @meriton The program can handle the error, or not. It's really up to the implementation of `InputStream` - remember, **InputStream is abstract**. We can't predict the kind of input which will be closed, so it's good to keep information flowing. I would be livid if I needed to handle that error, but couldn't, because there was an un-overridable implementation. That's why we throw exceptions in the first place: so the rest of the code can handle them, or not. Additionally, freeing the file descriptor may fail if the disk is no longer accessible at the time of closure.
Comment: @meriton Edited again (reorganizing, and clarifying some key points)
Answer: The underlying close system call will have to be made eventually, e.g. on linux http://linux.die.net/man/2/close. That call is documented to fail with EIO: "An I/O error occurred." So the reason is, that the underlying file system close call can fail.
Answer: I have wondered about this myself and have done a little research on this topic few years ago. This is what I know....
If you look at the javadoc in the link you provided, it clearly states that  "The close method of InputStream does nothing", so there is no way it would throw an exception, correct? But then looking at all of the subclasses of IOException you will see that there are many situations where subclasses of inputstream may not be able to close the stream. So my best guess is that this exception is designed for subclasses to make use of it.
http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html
In some cases, it is nothing more than a nuisance, and in others it clearly indicates that something went wrong. It all depends on what type of inputstream implementation you are making use of.
Comment: And by the way, StackOverflow showed me this in the right column which I thought was an interesting discussion on a very similar topic. See if this helps explain... http://stackoverflow.com/questions/2766450/when-does-java-util-zip-zipfile-close-throw-ioexception?rq=1


From github to bitbucket

Question: Imagine situation like this:
You have a working repo in bitbucket - you were pulling revisions from another bitbucket repo in Windows 7 through TortioseHG.
Now the second project has moved to Github system and you can not pull from it anymore.
So my question is like this:
How can i somehow create new repo in bitbucket where I will pulling changes from github and from this repo i can easily pull in Tortiose HG to my working repo?
I do not want to use Github etc, so please do not advice it to me etc just help me with my question. Thank you.
Answer: The ideal solution consiste to keep local Mercurial repo, and work only with this local repo to the existing bitbucket Mercurial remote repo.
With a plugin like Hg-Git, you can at least push to and pull from a Git server repository from Mercurial, allowing you to pull from the GitHub repo to your local Mercurial repo.

From that local (Mercurial) repo, you can then work as usual with the bitbucket remote repo.

The OP adds:

It didn't work for me so i tried to transfer git repo to hg repo and from this repo pull to my working repo with changes - but it says that: abort: repository is unrelated - but I merged a lot from it. Any help here?

That makes senses, if both repos have been developed separately, you cannot push/pull 2 (mercurial) repos one into another.
This is confirmed at the bottom of the page "Understanding Mercurial", and detailed in the blog post: "What Mercurial Can't Do: Subtree Repos".
The more practical solution would be to make one extra repository (a "parent one") with your two repos declared in it as nested repository.
It would keep both repos independent, allowing to push back to the GitHub repo from your second mercurial repo.
If you don't have to push back to GitHub, but really want to have one repo in which you merge common files, then you can look in "Merge tip from an unrelated repository with Mercurial", but that is much more complex.
I would rather:

keep both repos separate
delete from the first one the common files you need to merge in the second one.
report and merge those common files in the second one.
Comment: how to install this plugin to windows seven mercurial?
Comment: @Byakugan: you need the python setuptool installed first (http://packages.python.org/distribute/easy_install.html) before trying `easy_install hg-git` (which means also you have python installed first)
Comment: OK i have installed python and its setuptools so what now exactly to make it work? :-)
Comment: @Byakugan: that means you have access to the command 'easy_install'. From there, I don't have many much details than the ones described in the "Installing" section of http://hg-git.github.com/
Comment: I am trying but still when i execute this in command shell in windows it still says no such command or something like that ...
Comment: @Byakugan: right, probably a `PATH` issue, see for instance http://blog.sadphaeton.com/2009/01/20/python-development-windows-part-2-installing-easyinstallcould-be-easier.html
Comment: oh my god is it really so hard?
Comment: there has to be easier way to do this.
Comment: @Byakugan: no, I believe this is the recommended process when having to deal with those two different DVCS. Granted, a bit of perseverance is needed, but that is what makes this job fun ;)
Comment: It didnt work for me so i tried to transfer git repo to hg repo and from this repo pull to my working repo with changes - but it says that: abort: repository is unrelated - but I merged a lot from it. Any help here?
Comment: @Byakugan: that is an error which makes sense and seems normal to me. I have expanded my answer to address this new issue.
Comment: No I copied first and did some changes there and every day i merged around 15 new revisions to my modified repo which was the same one year ago and every day i merged it without any problem. Now after conversion it does not work.
Comment: @Byakugan: I would expect that, after conversion, those two repos wouldn't work well together, since their SHA1 could be different. The "merging changeset" tip might be appropriate then in this case.
Comment: So I finally get through http://blog.sadphaeton.com/2009/01/20/python-development-windows-part-2-installing-easyinstallcould-be-easier.html this manual and get easy_install working (i have to close and open command window after every step :-( I do not have to in unix - almost after adding part compiler=mingw32 to file and executing "easy_install hg-git" i get this error: http://pastebin.com/C3i1hMJB and i have every compiler installed - i searched the internet and found only linus solution to install dev package od python ... Any ideas? Thx
Comment: I have found some manual and updated some pathc and copy files from system32 and now i have this error: _objects.exp: file not recognized: File format not recognized
collect2: ld returned 1 exit status
dllwrap: gcc exited with status 1
error: command 'dllwrap' failed with exit status 1
Comment: @Byakugan: interesting. At this point, it could be interesting to describe precisely your steps in a new question in order to let other contributors to help you. I fear this long thread of comments isn't visible enough for others to assist.
Comment: Ok here it is :-) http://stackoverflow.com/questions/4585776/installing-hg-git-on-windows-7-64bit

From github to bitbucket


Am I applying MAX Modulus principle correctly here?

Question:
$(1)$ Find all possible entire functions s. t. $$|f(z)|\leqslant2|z|+1.$$
$(2)$ Prove you have found all such functions.

According to my understanding of $MAX$ modulus principle, $|f(z)|$ doesn' t have a $\max$ in a domain $D$, if it is not constant in $D$, but if it is continuous on a closed, bounded region of $D$, then even if $f$ is not constant, it attains its max, on the boundary of the region.
So here, since $|f(z)|$ has a max for ALL z, by MMP, $f(z)$ must be constant.
but then I randomly tried other functions for example $f(z)=z^2$ also works for some $z$ ( well not for all $z$ ). I am not sure if I am correct and how to show I' ve found ALL such functions.
Answer: $$f''(z)=\frac{2!}{2\pi i}\int_{\gamma}\frac{f(w)}{(w-z)^3}dw$$
Where, $\gamma : |w-z|=r $
(And above integral is independent of any $r>0$, as $f$ is an entire function.)
So we have,
$$\pi|f''(z)|\leq \int_{\gamma}\frac{|f(w)|}{|(w-z)^3|}|dw|\leq \int_0^{2\pi} \frac{2|w|+1}{r^3}(rdt)\leq \frac{2|z|+2r+1}{r^2}(2\pi)   \tag{$\forall r>0$}$$
(Since, $ \text{sup}\{|w| \ | w\in \gamma\}=|z|+r$ )
Taking $r \to \infty$,we get
$f''(z)=0$
Hence , $f(z)=az+b$   for some  $a,b\in \Bbb C$
Using similar argument with $f'(z)$ and $f(0)$ we can infer $|a|\leq 2$ and $|b|\leq 1.$...
(Which are neccessary conditions.)
Now , $|f(z)|=|az+b|\leq 2|z|+1$
Hence these neccessary conditions are sufficient as well.


Update query on sqlite3 does not work

Question: Update query on Sqlite3 Does not work
-(void)updateAlarms:(AlarmsBean *)todoItem//TodoItem: (AlarmsBean*)todoItem
{
    if (_updateAlarmsStatement == NULL)
    {
    sqlite3_prepare_v2(_database,

    "UPDATE AlarmSetting SET Sound = ?, Sensitivity = ?, Label = ? , Repeat = ? ,
 time = ? , On_Off = ? WHERE ID = ?",
                           -1,
                           &_updateAlarmsStatement,
                           NULL);
    }
    sqlite3_reset(_updateAlarmsStatement);
    sqlite3_bind_text(_updateAlarmsStatement, 1,
 [todoItem.AlarmSoundName UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_int(_updateAlarmsStatement, 2, todoItem.AlarmSensitivity);
    sqlite3_bind_text(_updateAlarmsStatement, 3, [todoItem.AlarmName UTF8String], -1,
 SQLITE_TRANSIENT);

    sqlite3_bind_int(_updateAlarmsStatement, 4, todoItem.AlarmRepeat);

    sqlite3_bind_text(_updateAlarmsStatement, 5, [todoItem.AlarmTime UTF8String], -1,
 SQLITE_TRANSIENT);

    sqlite3_bind_int(_updateAlarmsStatement, 6, todoItem.AlarmOnOff);
    sqlite3_bind_int(_updateAlarmsStatement, 7, todoItem.AlarmID);
    sqlite3_step(_updateAlarmsStatement);
}

In other class:
AlarmsBean * todoItem1 = [[AlarmsBean alloc] init];

database = [[ClassAlarmDB alloc] init];

            todoItem1.AlarmID = 1 ;
            todoItem1.AlarmSoundName = @"28.png";
            todoItem1.AlarmSensitivity = 1 ;
            todoItem1.AlarmName = @"ahmad" ;
            todoItem1.AlarmRepeat = 1;
            todoItem1.AlarmTime = @"00 : Am";
            todoItem1.AlarmOnOff = 4 ;
              NSLog (@"Befor Update");
            [database updateAlarms: todoItem1];

But the database is not updated.
Comment: What is the error message? Do you already have a row with `id==1` in that table?
Comment: yes i have row id = 1  but  no error message and DataBasa is not updating
Comment: where is your database file stored on the device?
Answer: Check the return code from sqlite3_step(..), and probably also sqlite3_prepare_v2(..).  If it's not SQLITE_OK or SQLITE_DONE, print out sqlite3_errcode(_database) and sqlite3_errmsg(_database).
This should give you some information to go on.
Comment: all statement is true - but database is not updating

Update query on sqlite3 does not work


Playing and recording Audio simutaneouly with headset jack pin in iOS?

Question: I am developing an iPhone application which requires to play and record Audio(I am doing this with help of AudioQueues) simultaneously. I am using headset jack pin with mic for recording and playing and the playing sound is a wav file of 5kHz.
The problem here is it's recording the sound that is playing out through output AudioQueues as well as the sound that is coming into headset mic. but I need to record only the sound that is coming through the headset mic.
I am unable to find the problem is with the headset jack pins(I have tested with lot off headset jack pins) or any programming settings like AudioSessions. the same is with the AVAudioPlayer and AVAudioRecorder too.
Can anyone tell the problem and some help and suggestions would very helpful. Thanks.
Comment: Do you have the proper 3-ring-plus-tip mike adapter?  It should look like a zebra: http://lh4.googleusercontent.com/public/_lMbkhC-RNOfLBVTQABxsqJUoxjTvT-XYcWlwgHgVtOr-5A9UaYsc6NhHoTonK1PE1DYIte6QPsb1IdcUb67tmwkAnsRKu0i797ymQxtiySwNyzsJao3zSPytf_ckgQ
Comment: Yes, I have 3-ring-plus-tip mike adapter, through which recording the sound is happening but playing sound also recording. through jack pin it should only record the sound that is coming through jack pin's mic. right?
Comment: I think there's a setting in the sound stuff, either on the mike side or the earphone side, that "bridges" between the two.  I don't recall the details, though.  Also, if your adapter is incorrectly constructed it could cause "bleed" between the two.  The wiring of the plug is a hair illogical.  IIRC, the ring farthest from the tip is the mike, and the one next to that the common ground (but the chart is on the internet in several locations to check that).
Answer: In this case you have to pump the input sound using external amplifier/ mixer. Mic alone will not work properly. If you increase the recording volume in your pc you will hear louder hissing sound and at the same time it will continue to record the playback sound. So the only solution is use external source (amply/mixer) to raise the level of the input mic.


LIMIT do SQL retorna sempre os mesmos 3 últimos registros

Question: Estou com um problema em um select. Tenho a seguinte tabela
id   id_de      id_para      mensagem
---  ---------  -----------  -----------
1    10         20           Oi David.
2    20         10           Oi José
3    10         20           Tudo bem?
4    20         10           Sim, e com vc?
5    10         20           Estou ótimo?

Onde id é o identificador de cada mensagem, id_de é o id de quem está enviando a mensagem e id_ para é o id de quem está recebendo a mensagem.
Meu select é:
$select = BD::conn()->prepare("SELECT * FROM `mensagem` WHERE (`id_de`= ? AND `id_para` = ?) OR (`id_de` = ? AND `id_para` = ?) LIMIT 3");
            $select->execute(array($_SESSION['id_user'], $id, $id, $_SESSION['id_user']));

Mas o problema é se eu enviar mais mensagens de um usuário para outro, ele sempre vai fazer o select das mesmas 3 mensagens. Se eu tirar o LIMIT do Select, ele retorna todas as mensagens corretamente.
Por favor se alguém puder me ajudar, serei grato.
Answer: Isto acontece pq o LIMIT vai retornar apenas os 3 primeiros registros.
Você pode dar um order by id desc, mas vai trazer de trás pra frente. Essa é a maneira mais fácil de resolver seu problema.
Para resolver o problema da ordem eu sugiro o seguinte:

Faça sua query e use o order by id desc conforme te orientei.
Transforme esta query num sub select. Este sub select você ordena por id novamente.

É feio, mas vai resolver seu problema.
Comment: Resolveu mais ou menos minha questão, porque ele exibiu as mensagems ao contrário, assim:

Estou ótimo
Sim, e com vc?
Tudo bem?
Oi José
Oi David.

No caso eu queria que fosse assim:
Oi David.
Oi José
Tudo bem?
 Sim, e com vc?
= Estou ótimo?
Comment: Veja se meu edit ajuda


Change text of td element

Question: I've been trying to change a text of a td element however I am not able to make it work:
http://jsfiddle.net/9HkWH/
What could be wrong in that fiddle?
Actually this is just my first step to do my actual goal that is to prettify a date using:
http://timeago.yarp.com/
Updated:
Where I need to do:
$(function() {
   $('td[kind="date"]').html("Hello?");
})

Comment: You need to escape those quotes or did you want to concatenate? Something is wrong check the syntax highlighting...
Comment: oops sorry, I was thinking in java haha. Anyway, I updated the fiddle already, but still does not work
Comment: Hey, don't downvote me! :-)
Answer: There are multiple problems

Your script has a syntactical error, the quotes are not properly escaped
Your html is not valid, there is no opening/closing <table tags
Selector p[kind=date] is invalid since there is no p element, a td has the attribute kind="date".

So
$(function() {
   $('td[kind="date"]').html("test");
})

Demo: Fiddle
Comment: Arun, I have updated my answer with this code you have but still does not work in jsFiddle.
Comment: Oh I get it, sorry, this is result of a GWT developer tinkering in Javascript :-)
Answer: First,you write the wrong selector,there is not 'p' element,your should try
$("td[kind='date']").html("test");
Second,the quotation marks in selector should be single not double.
Last and most important,your html code missed 'table' tag,so the html will render as text not a table,that's why your selector will not work even you change the selector by other's advices.
Check this Demo,it works fine.
Answer: Can you please refer the below code.
function changeText() {
    $("#demoTable td").each(function () {
       $(this).html().replace("8: Tap on APN and Enter www", "");
    }
}

Replace text inside td using jQuery

Change text of td element


Loss of precision in float operations, due to exponent differences?

Question: I have a program where I represent lengths (in cm) and angles (in radian) as floats. My lengths usually have values between 10 and 100, while my angles usually have values between 0 and 1.
I'm aware that precision will be lost in all floating point operations, but my question is:
Do I loose extra precision because of the magnitude gap between my two numerical realms? Would it be better if I changed my length unit to be meters, such that my usual length values lies between 0.1 and 1, which matches my usual angle values pretty evenly?
Comment: IMO: use cm as this is have less numbers after the decimal
Comment: floating point is nothing more than grade school math should be able to figure this out.  in part it depends on the operations.  with addition as we know from grade school math you have to align the decimal points which is exponent driven the smaller number has its mantissa shoved off into the ether.  but for multiplication for example as we know in grade school math the mantissa's are computed and the upper half of the result retained, the exponents are summed, separately managed, precision is not lost.
Comment: 1.234 * 10^10 + 1.234 * 10^1 with 3 digits of mantissa.  when you align the decimal points you get 1.234 + 0.000 = 1.234.  but multiply  you get 1.523 * 10^11.
Comment: dont see how adding or subtracting the same number from each exponent would affect the math  1.234*10^10 + 1.234*10^1 vs 1.234*10^12 + 1.234*10^3 does not change the precision until you get to a magnitude that is on the edge of exponent maximum, and I assume meters or centimeters you are not measuring distances between planets or the size of the universe.
Comment: How do you use lengths and angles together? Does your program interpret angles as arc length of unit radius? That's the only legitimate case I see for adding angles to lengths directly.
Comment: i don't think so but if you want to use the separate ranges it's pretty easy to map one to the other and vice versa
Comment: For example, I have a length along a circle and wan't to know the corresponding angle in radians. So I divide the length by the radius of the circle and get the angle. So, yes, by using radians I interpret angles as arc length of unit radius.
Answer: The point of floating point is that the point floats. Changing the magnitudes of numbers does not change the relative errors, except for quantization effects.
A floating point system represents a number x with some value f and an exponent e with some fixed base b (e.g., 2 for binary floating point), so that x = f be. (Often the sign is separated from f, but I am omitting that for simplicity.) If you multiply the numbers being worked with by any power of b, addition and subtraction will operate exactly the same (and so will multiplication and division if you correct for the additional factor), up to the bounds of the format.
If you multiply by other numbers, there can be small effects in rounding. When an operation is performed, the result has to be rounded to a fixed number of digits for the f portion. This rounding error is a fraction of the least significant digit of f. If f is near 1, it is larger relative to f than if f is near 2.
So, if you multiply your numbers by 256 (a power of 2), add, and divide by 256, the results will be the same as if you did the addition directly. If you multiply by 100, add, and divde by 100, there will likely be small changes. After multiplying by 100, some of your numbers will have their f parts moved closer to 2, and some will have their f parts moved closer to 2.
Generally, these changes are effectively random, and you cannot use such scaling to improve the results. Only in special circumstances can you control these errors.
Comment: @foldrup: Changing from cm to m will not "natural cut off two digits of precision from the significand". In decimal floating point, 257 centimeters would be represented as 2.57 • 10\*\*2, and 2.57 meters would be represented as 2.57 • 10\*\*0. In binary, the significands would change since the factor, 100, is not a power of two. But the number of bits available in the significand is **fixed by the format**. It is not a function of the magnitudes of the numbers. You do not get more bits one way or another. Whether in m or cm, a fixed number of bits is used to represent the significand.
Comment: "you cannot use such scaling to improve the results".
Except that, as old_timer said, when it comes to addition, I *can* control the loss, by ensuring harmony between the exponents of the two numbers being added.
Comment: @loldrup: You are not being clear. If you want to add *a* and *b* and you "harmonize" the exponents by multiplying one of them, say *b*, to change its exponent and then add, then the result is *a* + *b* • *h* for some *h*. If "harmonized" the exponents properly, that result may have a much smaller rounding error in the addition, but it has a whopping huge error in that it added the wrong value to *a*.
Comment: Agree, I cannot harmonize like that. I can only harmonize by adopting meters as units from the very start of my calculations. Using meters 'natively', so to say.
Comment: @loldrup: That is the same thing as multiplying by a factor, adding, and dividing by a factor, and the answer above applies. Adding in meters, feet, or furlongs is just a matter of scale. It is irrelevant to floating-point except for the effectively random quantization effects.
Comment: Then I fail to see how  a + b • h will add the wrong value to a. I scale my b to be in meters. This scaling has no bad effect, as it happens at precomputation time (by me changing all input values from cm to meter).
Though, now I think of it, representing lengths in meters instead of cm will naturally cut off two digits of precision from the 'significand' of my floating point number. So this might make any precision gained in addition operations moot.
Comment: @foldrup: If *a* is 4 to represent 4 meters and *b* is 3 to represent 3 meters, then the desired result of adding *a* and *b* is 7 for 7 meters. Adding *b* • *h* to *a* will not produce 7 for any value of *h* other than 1, so multiplying *b* to add it to *a* by any value other than 1 produces an incorrect result.
Comment: good point! thanks
though we still seem to talk past one another when it comes to the a + b • h equation. I think that 4m * (3cm / 100) is the same as 4m * 0.03m. Especially since the (3cm / 100) part would never be computed. I'd simply write it as 0.03 when I give the numer as imput to the program.


Configurações da linguagem Go

Question: Preciso fazer um trabalho da faculdade e escolhi fazer na linguagem Go pois queria aprender uma linguagem nova. Ontem instalei o .msi do site e vi que precisava configurar as variáveis GOPATH, PATH e GOROOT. Eu configurei elas da seguinte maneira:

GOPATH = C:\Users\Gustavo\goprojects (onde a pasta goprojects eu criei e é onde eu quero que fique todos os meus projetos da linguagem Go)
GOROOT = C:\Go\ (pasta onde foi instalado a linguagem Go)
PATH = C:\Users\Gustavo\goprojects\bin

Até ai tudo bem. Porém eu uso a IDE Eclipse e pesquisando eu vi que tem um plugin chamado GoClipse que faz o Eclipse ser uma IDE da linguagem Go, então eu a instalei pelo marketplace do próprio Eclipse.
Depois de tudo isto feito, criei um novo projeto Go e coloquei para o projeto ser no caminho C:\Users\Gustavo\goprojects, e criei um novo .go dentro de uma pasta que esta fica dentro da pasta src. Quando fui escrever um Hello World, toda vez que eu tentava fazer ele completar sozinho o código ele aparece um erro ai eu fui ver e vi que precisava baixar um outro plugin para funcionar o auto-completing, e este plugin chama gocode que é um projeto que está no GitHub.
E aqui está meu problema. Onde e como eu devo baixar esta pasta e como ativá-la no meu Eclipse? Eu configurei as variáveis corretamente? Preciso fazer algo a mais?
P.S.: Uso Windows 8.1, tenho o git instalado.
Comment: normalmente você não substitui o PATH completamente, mas adiciona novos diretórios/pastas; no seu caso seria assim: PATH = %PATH%;C:\Users\Gustavo\goprojects\bin
Answer: Supondo que o projeto gocode ao qual se refere é este: https://github.com/nsf/gocode,
basta rodar o comando:
go get -u github.com/nsf/gocode

Isso fará com que o pacote seja devidamente instalado e seu binário fique disponível na pasta $GOPATH\bin.
Answer: Gustavo,
estou programando em GO, aconselho muito focar nessa linguagem.. e uma sugestão pois sou programador a muitos anos..
Usa o linux para programar em GO, pode ser até uma VirtualBox e eu gosto de usar o ATOM, tem vários plugins interessantes.
Answer: Independente de qualquer projeto que usar, eu recomendo usar a recomendação de workspaces do Go.
Na documentação eles explicam como você deve criar esses workspaces.
Com isso você consegue deixar seus projetos muito bem estruturados, e padronizados.

Configurações da linguagem Go


SSL connection with certificate

Question: I would like to replicate the following Python code into an equivalent in Java:
import socket, ssl, pprint

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s,
                           ca_certs="server.crt",
                           cert_reqs=ssl.CERT_REQUIRED)

ssl_sock.connect(('localhost', 10023))
ssl_sock.write("boo!")

if False:
    data = ssl_sock.read()
    ssl_sock.close()

I came up with the following code (which is not working) but I still have two questions:
abstract class Connection extends AsyncTask<String, Void, String> {

    boolean Connect(){
        try
        {
           SSLSocketFactory factory=(SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket mySSLSocket=(SSLSocket) factory.createSocket("localhost", 10023);

            DataOutputStream myOutPutStream = new DataOutputStream(mySSLSocket.getOutputStream());
            myOutPutStream.writeBytes("Hello World!");

            myOutPutStream.close();
            mySSLSocket.close();

            return true;

        }
        catch(Exception e)
        {
            return false;
        }

    }

}

By executing the code I get the following Java Error:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Where do I save the certificate in my Android Application Project (Android Studio)?
What is the equivalent for the code below in Java?
ssl_sock = ssl.wrap_socket(s,
                           ca_certs="server.crt",
                           cert_reqs=ssl.CERT_REQUIRED)
Answer: Try -Djavax.net.ssl.trustStore=/path/to/keystore, where '/path/to/keystore' is the absolute file path of the alternative keystore.
This needs to be a VM option for running your code / project.

SSL connection with certificate


Z80 16-Bit Load Instruction and Endianness

Question: I'm writing a ZX Spectrum emulator in C# "for fun" (I think I regret starting already).
I know the Z80 is little endian, so in RAM the low-order byte is stored first.
What I can't seem to find a definitive answer to, is how it behaves with a 16-bit LD instruction.
For example:
LD BC, 0x1234

After this, does B contain 0x12 and C contain 0x34 or vice-versa?
So, after the above, if I execute:
LD A, 0x56
LD (BC), A

Will memory 0x1234 or 0x3412 contain 0x56?
It would be nice if someone could provide a link to a reliable source.
Comment: There is other register pair.. HL... It works in the same manner... Guess what H and L stands for...
Comment: Values in asm source are *values*, not encodings; they use normal most-significant-digit first order.
Comment: You wrote the instruction the way a disassembler displays it or you write it in assembly.  It uses the "natural" order, humans like their most significant byte on the left and the least significant on the right.  Same story for register pairs, BC has the most significant register on the left.  Your emulator however sees 0x01 0x34 0x12.  Little-endian, 0x34 is first.  Only the memory bus interface has the endian detail.
Answer: Endian-ness only comes into play when we break a 16-bit value into two 8-bit pieces, and there is a choice of approaches, which happens when such a 16-bit value is stored in memory so, for example:

With the encoding of immediates in instructions, such as ld bc, 0x1234: looking at the individual bytes of the machine code for this instruction, we will see 0x01 0x34 0x12, storing the 0x1234 in little endian byte order.

With a 16-bit value as data in memory, and looking at the individual bytes in memory, needs an endian-ness, so use little endian.

However, if the BC register pair is loaded with a value 0x1234, then that's the memory address that indirect use of BC will work with.  There's no issue of endian-ness with this, since we're not looking at the individual bytes in this scenario.
Now, if you want to know how the BC register composes from B and C then we have to know which is the high order and which is the low order.
From the manual:

PUSH BC is PUSH B then C

So, that means that the stack memory will have the value from C then the value from B at the address +1 higher than where C was stored.  Since 16-bit data in memory is stored using little endian byte order, we can conclude that C is the low order and B is the high order of the BC 16-bit register pair.
Thus, BC is B * 256 + C.  Let's note though, that this is simply by definition, but doesn't really go to endian-ness — since there's no "addressing" of the individual bytes, there's also no other ordering as there is with memory (due to memory's having of both addresses and values).
However, the choice of which is high and which is low doesn't change that together they hold the value 0x1234, as per our examples.
Comment: That seems to make sense, thank you for providing a clear explanation.
Comment: If you're ever in doubt, sometimes the easiest way is to test it yourself. Now, emulators are not always accurate, but if you don't have the real hardware, they're your best option.  For something like this you can trust nearly all emulators to get it right
Comment: @puppydrum64, this is a good comment, but more appropriate to direct to the OP rather than me.
Comment: Whoops, I commented on the wrong post!
Answer: Is a manufacturer datasheet reliable source?
Z80 user manual
And of course in memory after opcode is firstly 0x34 then 0x12
Comment: I have that manual... it just says "Upon the execution of an LD HL, 5000h instruction, the HL register pair contains 5000h". Not terribly clear.
Comment: The question could have been answered by page 46 / 47 of the user manual which describes how ``ld de,0659h`` is encoded, unfortunately figure 37 was botched and shows ``and 7`` instead :-)


Uncaught SyntaxError: Unexpected end of input

Question: Meu código está gerando erro e pelo que pesquisei seria erro de sintaxe mas não to conseguindo achar aqui e o Sublime Text 2 não tem corretor. Poderiam me ajudar? Segue o código:
var Padrao = {

    /**
    * Init
    */
    init : function(){

        //Exibe Tela de Login/Minha Conta
        $('.login').click(Padrao.abreLogin);

        //Exibe Carrinho de Compras
        $('.carrinho-botao').click(Padrao.exibeCarrinho);

        //Chama o carrousel de Banner
        Padrao.carrouselBanner();
    },

    //Exibe Tela de Login/Minha Conta
    abreLogin : function(){
        $('.minha-conta').toggle(200);
    },

    //Exibe Carrinho de Compras
    exibeCarrinho : function(){
        $('.carrinho-aberto').toggle(200);
    },

    //Carrousel de banner
    carrouselBanner : function(){

        //recupera a qtd de elementos da lista
        var elementos = $('.destaque-banner ul li').length;

        //atribui automatico o valor de width para a ul
        $('.destaque-banner ul').css({width : 990 * elementos});

        //define e imprime a quantidade de bullets de acordo com o numero de elementos
        for(var i = 0; i < elementos; i++){
            if(i == 0){
                $('.bullets-area ul').append('
 x
');
            } else {
                $('.bullets-area ul').append('
 x
');
            }
        }

        $('.bullets-area ul li a').click(function(){
            var desloca = $(this).attr('index');
            //alert(desloca);
            $('.destaque-banner ul').animate({'margin-left': desloca * -1000});
        });
    }
};

$(Padrao.init);

Comment: Poste-o como resposta @user5101 :}
Comment: O erro é só `Uncaught SyntaxError: Unexpected end of input`? Não tem mais nenhum detalhe que poderia ajudar a identificar o erro?
Comment: Não tem nada de errado com seu código, testei em um compilador e não acusa erros. Onde você o está declarando/chamando na sua página?
Comment: Amigo Paulo Roberto. O erro que o navegador acusava era ali onde eu defino href="javascript:void". Tinha faltado o (0). Falha minha mas já descobri. Agradeço a ajuda.
Comment: Como PauloRoberto falou, poste como resposta e selecione a sua própria resposta
Answer: Podes usar o javacriptlint para isso.
Só copia e cola o código lá e ele te mostra erros de sintaxe.
O site é uma ferramenta lint. Infelizmente não tem uma página na wiki para ferramentas lint em português ainda, mas são ferramentas que analisam o código procurando erros de sintaxe e algumas más práticas. A grande maioria das linguagems de programação tem ferramentas desse tipo.
Comment: @Heitor podes usar qualquer outro site que faça lint, por exemplo, [jslint](https://www.jslint.com/)
Comment: Tentei e mesmo assim não apresenta nada. Apenas uns warnings que corrigi mas aparentemente nada fora do normal.
Comment: @user5101 O erro possívelmente está em algum código que foi declarado anteriormente, então.
Comment: Estou usando apenas a biblioteca jquery, esse arquivo que postei (padrao.js) e a biblioteca less.js!
Comment: O link está quebrado!
Comment: @fotanus obrigado, descobri qual era meu problema, era questão de encoding de caracteres, meu json estava correto de acordo com vários sites que usei, mas em tempo de execução dava esse erro de input...
Answer: Amigo, tenta colocar uma virgula no final por exemplo:
 $('.bullets-area ul li a').click(function(){
            var desloca = $(this).attr('index');
            //alert(desloca);
            $('.destaque-banner ul').animate({'margin-left': desloca * -1000});
        });
    },
};

$(Padrao.init);

Answer: Não tem nada de errado com o código em si. O problema está oculto nos links com Javascript que são adicionados pelo código.
Ao invés de:
x

Faça:
x

Answer: Aqui está seu código corrigido
var Padrao = {

    /**
    * Init
    */
    init : function(){

        //Exibe Tela de Login/Minha Conta
        $('.login').click(Padrao.abreLogin);

        //Exibe Carrinho de Compras
        $('.carrinho-botao').click(Padrao.exibeCarrinho);

        //Chama o carrousel de Banner
        Padrao.carrouselBanner();
    },

    //Exibe Tela de Login/Minha Conta
    abreLogin : function(){
        $('.minha-conta').toggle(200);
    },

    //Exibe Carrinho de Compras
    exibeCarrinho : function(){
        $('.carrinho-aberto').toggle(200);
    },

    //Carrousel de banner
    carrouselBanner : function(){

        //recupera a qtd de elementos da lista
        var elementos = $('.destaque-banner ul li').length;

        //atribui automatico o valor de width para a ul
        $('.destaque-banner ul').css({width : 990 * elementos});

        //define e imprime a quantidade de bullets de acordo com o numero de elementos
        for(var i = 0; i < elementos; i++){
            index = parseInt(i,10); // faltou um parametro aqui, parseInt(string, radix), você não tinha passado o radix
            if(i === 0){ // como era uma comparação de tipos o lint pede que seja feita uma comparação usando "==="
                $('.bullets-area ul').append('
 x
');
            } else {
                $('.bullets-area ul').append('
 x
');
            }
        }

        $('.bullets-area ul li a').click(function(){
            var desloca = $(this).attr('index');
            //alert(desloca);
            $('.destaque-banner ul').animate({'margin-left': desloca * -1000});
        });
    }
};

$(Padrao.init);

Na linha 40 jslint estava reclamando da falta do segundo parâmetro no parseInt() por recomendação ele deve receber 2 parâmetros onde o segundo é opcional parseInt(string, radix)

Parameter - (string)  Required. The string to be parsed
Description - (radix) Optional. A number (from 2 to 36) that represents the numeral system to be used

Na linha 41 o jslint estava reclamando do tipo de comparação então a comparação foi trocada de == para ===
Comment: O parseInt() funciona sim com um parâmetro, mas como o @ErlonCharles colocou nos comentários, o JSLint não "aconselha" o uso dessa forma, pois se passar "0x16" (hexadecimal) como parâmetro ele vai virar o inteiro 22 e não 0 ou 16 como é de se esperar.
Comment: Faltou dizer o que estava errado. :)


Continuation Passing Style In Common Lisp?

Question: In an effort to find a simple example of CPS which doesn't give me a headache , I came across this Scheme code (Hand typed, so parens may not match) :
(define fact-cps
    (lambda(n k)
        (cond
            ((zero? n) (k 1))
            (else
                (fact-cps (- n 1)
                          (lambda(v)
                             (k (* v n))))))))
(define fact
    (lambda(n)
        (fact-cps n (lambda(v)v))))  ;; (for giggles try (lambda(v)(* v 2)))

(fact 5) => 120

Great, but Scheme isn't Common Lisp, so I took a shot at it:
(defun not-factorial-cps(n k v)
    (declare (notinline not-factorial-cps)) ;; needed in clisp to show the trace
    (cond
        ((zerop n) (k v))
        ((not-factorial-cps (1- n) ((lambda()(setq v (k (* v n))))) v))))
       ;; so not that simple...
(defun factorial(n)
    (not-factorial-cps n (lambda(v)v) 1))

(setf (symbol-function 'k) (lambda(v)v))

(factorial 5) => 120

As you can see, I'm having some problems, so although this works, this has to be wrong. I think all I've accomplished is a convoluted way to do accumulator passing style. So other than going back to the drawing board with this, I had some questions: Where exactly in the Scheme example is the initial value for v coming from? Is it required that lambda expressions only be used? Wouldn't a named function accomplish more since you could maintain the state of each continuation in a data structure which can be manipulated as needed? Is there in particular style/way of continuation passing style in Common Lisp with or without all the macros? Thanks.
Answer: The problem with your code is that you call the anonymous function when recurring instead of passing the continuation like in the Scheme example. The Scheme code can easily be made into Common Lisp:
(defun fact-cps (n &optional (k #'values))
  (if (zerop n)
      (funcall k 1)
      (fact-cps (- n 1)
                (lambda (v)
                  (funcall k (* v n))))))

(fact-cps 10) ; ==> 3628800

Since the code didn't use several terms or the implicit progn i switched to if since I think it's slightly more readable. Other than that and the use of funcall because of the LISP-2 nature of Common Lisp it's the identical code to your Scheme version.
Here's an example of something you cannot do tail recursively without either mutation or CPS:
(defun fmapcar (fun lst &optional (k #'values))
  (if (not lst)
      (funcall k lst)
      (let ((r (funcall fun (car lst))))
        (fmapcar fun
                 (cdr lst)
                 (lambda (x)
                   (funcall k (cons r x)))))))

(fmapcar #'fact-cps '(0 1 2 3 4 5)) ; ==>  (1 1 2 6 24 120)

EDIT

Where exactly in the Scheme example is the initial value for v coming
  from?

For every recursion the function makes a function that calls the previous continuation with the value from this iteration with the value from the next iteration, which comes as an argument v. In my fmapcar if you do (fmapcar #'list '(1 2 3)) it turns into
;; base case calls the stacked lambdas with NIL as argument
((lambda (x) ; third iteration
   ((lambda (x) ; second iteration
      ((lambda (x) ; first iteration
         (values (cons (list 1) x)))
       (cons (list 2) x)))
    (cons (list 3) x))
   NIL)

Now, in the first iteration the continuation is values and we wrap that in a lambda together with consing the first element with the tail that is not computed yet. The next iteration we make another lambda where we call the previous continuation with this iterations consing with the tail that is not computed yet.. At the end we call this function with the empty list and it calls all the nested functions from end to the beginning making the resulting list in the correct order even though the iterations were in oposite order from how you cons a list together.

Is it required that lambda expressions only be used? Wouldn't a named
  function accomplish more since you could maintain the state of each
  continuation in a data structure which can be manipulated as needed?

I use a named function (values) to start it off, however every iteration of fact-cps has it's own free variable n and k which is unique for that iteration. That is the data structure used and for it to be a named function you'd need to use flet or labels in the very same scope as the anonymous lambda functions are made. Since you are applying previous continuation in your new closure you need to build a new one every time.

Is there in particular style/way of continuation passing style in
  Common Lisp with or without all the macros?

It's the same except for the dual namespace. You need to either funcall or apply. Other than that you do it as in any other language.
Comment: Crap, I almost had this from the start, but I **didn't** funcall #'k the second time and never noticed... #@!$. But I learned a lot from it. If you could expand on the other questions, that would be great.


Controlling finger reaction

Question: This is a follow up question of Guitar Muscle memory lesson plan for fine motor skill deficit
While melodies get longer, I'm confusing, and especially if finger path are crosssing itself a lot such as
E7 - E10 - E12 - E9
I'm almost inevitably messing it up like
E7 - E9 - E12 - E10 et cetera.
or say a simple melody
E3 - E7 - E5
I'm often playing it like
E3 - E7 - E3 or
E5 - E7 - E5 etc.
Are there specific exercise or methods to clear up this type of problems??
Update: @Tim wrote "there is often no need to move up or down a string 3 or 4 frets" however I try to play this style of guitar

and  I follow her channel. I use the same technique  Is it wrong method to play?
Comment: See my answer to your last question - it's a matter of adapting that idea. There's often no need to move up or down one string more than three or four frets, that's because the guitar is designed for those of us humans with four fingers!
Comment: Try to sing or hum the melody while you're playing it. This helps to map a tone to a finger movement in your brain.
Comment: On your update. That's hardly muscal guitar playing. It's how some of my students play when they start with me. Sorry, but that sounds very, very amateur, and certainly won't align with what I include in my answer. If nothing else, the phrasing cannot be played effectively. There must be a thousand better channels to follow.
Comment: 'Wrong' is rather subjective. But if my students ended up playing like that, I'd pack up immediately!
Comment: @Tim see update on my question.
Comment: @flappix make it an answer
Comment: @Tim Thank you. So its amateurish but not "wrong" okey?? or it is technically wrong?
Answer: Practice everything so slowly that there is no way you can play it wrong (if necessary extremely slowly). Then increase the speed so gradually that you still play it correctly every time. If you make a mistake slow down again.

Controlling finger reaction


Length of a curve is independent of parameterization

Question: Suppose that $P:[a,b]\to \mathbb{R}^n$ and $Q:[c,d]\to \mathbb{R}^n$ be two parameterizations of the same continuously differentiable curve $\Gamma$. Can some one give a hint on how to prove that the length of the curve $\Gamma$ is independent of both $P$ or $Q$? If you can also point out the important intrinsic things one should remember when dealing with curves, it would be great. Thanks.
Comment: its a substitution in the integral
Comment: @DominicMichaelis: $P$ is not necessary a reparametrization of $Q$. In fact, it is not obvious; the only reference I have is in French, I will try to sum up the main idea later.
Comment: @DominicMichaelis: If I make the substutuition $t=P^{-1}(Q(s))$ in the integral $\int_a^b\|P'(t)\|dt$, I would get $\int_c^d\|P'(P^{-1}(Q(s)))\|(P^{-1})'(Q(s))Q(s)ds$. How can I prove the above equal to $\int_c^d\|Q'(t)\|dt$? Am I proceeding in the right direction? Or do you mean some other substituition?
Answer: Let $\Gamma$ be a curve. Define the length $\ell g(\Gamma)$ of $\Gamma$ as the supremum of $\displaystyle \sum\limits_{i=1}^n d(A_i,A_{i+1})$ over the partition $A_1,...,A_{n+1}$ of $\Gamma$ (in particular, the sequence $(A_i)_i$ is monotonic along $\Gamma$).
Now, if $\varphi$ is a regular parametrization of $\Gamma$, you can show that $\displaystyle \ell g(\Gamma)= \int_0^1 ||\varphi'(t)||dt$.
Therefore, the integral does not depend on the regular parametrization you choose, since $\ell g(\Gamma)$ is here geometrically defined.


Difference between intersection of infinite sets having finite, and having infinite elements

Question: I could find individual answers for both of these, but can someone compare how being a finite set or an infinite changes the final outcome?
(a) If A1 ⊇ A2 ⊇ A3 ⊇ A4 · · · are all sets containing an infinite number of
elements, then the intersection $$ \bigcap_{n=1}^{\infty} A_n $$ is infinite as well. - False
(b) If A1 ⊇ A2 ⊇ A3 ⊇ A4 · · · are all finite, nonempty sets of real numbers,
then the intersection $$ \bigcap_{n=1}^{\infty} A_n $$ is finite and nonempty. - True
This is from the book Stephen Abbott, Understanding Analysis
Comment: For the first point, let $A_n=[-1/n,1/n]\subseteq \Bbb R$. Then the intersection is just $\{0\}$. Even better, let $A_n=(n,\infty)$, and the intersection is empty. I think the main difference is that with infinite sets, you can have an infinite chain of strictly decreasing, non-empty sets, while that's impossible in the finite case.
Comment: @arthur That is exactly the point I was thinking of making having read the answers but not the comments. I think it deserves a mention in some answer, because really the issue is one of the **existence** of a sequence. This generalizes quite a bit the easy basic generalization is assume all $A_\alpha$ are countable and you're intersecting over an uncountable set. (I'm sure full generality is just an appropriate use of cofinalities but would have to think a bit.)
Answer: In (b) the sequence is bound to stabilize: some $n$ exists such that $k\geq n\implies A_k=A_n$.
The finite number of elements of $A_1$ can only be 'diminished' a finite number of times. This combined with the condition that $A_n\neq\varnothing$ assures that the intersection is not empty.
In (a) that obstacle does not appear. Every element in $A_1$ can be "thrown out" at some time.
Answer: I think you're asking what the relationship is between the two. The relationship is clearest when the statements are changed slightly.
Let $A_1 \supseteq A_2 \supseteq A_3 \supseteq \dots$ be a descending sequence of nonempty sets. Must their intersection be nonempty?
The answer is no in general, but yes if all the sets (or even just one of the sets) are assumed finite. This appears paradoxical because finite sets are smaller than infinite ones, so one would naïvely expect their intersection to be smaller too.


Has anyone implemented a tablesort with ajax?

Question: I would like to sort on a column with a round trip but no page reload. The table is very large and has to be paged in, which I am doing manually with an ajax select element. I know TableSort is available to extend the query but I've only seen examples that reload the page.
Comment: First, why would you need AJAX if you already have the table data? And secondly, how does this pertain to Drupal specifically? Seems like you might have better luck on one of the other SE sites.
Comment: I updated the question with a bit more info.
Answer: here you go mate:
ajax table sorting
Answer: Why not to use Views module to display your data? Views already has AJAX paging, sorting and filtering.
Comment: Update: I decided to use views :)
Comment: I would have to integrate my entity with views to do that. Does views create a TableSort-extended output? I don't use Views that much in custom modules.
Comment: What do you mean "TableSort-extended"?

Views provides table sorting and it can be done by AJAX out off the box.
Comment: Tablesort is a Drupal query extender - not just "sorted table" in general. http://api.drupal.org/api/drupal/includes!tablesort.inc/class/TableSort/7
Comment: For what purpose do you need "Tablesort"?
If you want allow users to sort table rows by clicking on their headers - then views can do it for you.
If you use Views module - you do not need use Drupal query manually.
Comment: If I wanted to use views, I would have to do all the work of integrating my entity with views. I'm not interested in views.


Por que está dando erro na chamada de um método?

Question: Estou tentando este código:
class Car:
    def beep():
        print('Beep')

car = Car()
car.beep()

TypeError: method() takes 0 positional arguments but 1 was given

Por que dá o erro?
Comment: @FourZeroFive se for python3 esta "quase" certo, mas o autor não informou se é 2 ou 3, que já é um problema da pergunta ... se for 2 vai ter o erro: `TypeError: unbound method beep() must be called with Car instance as first argument (got nothing instead)`, tem que ter certeza se o caso é de fato OO ou outra coisa que o autor deseja, retirar `()` pode resolver aparentemente, mas não adianta "resolvermos" sem que a necessidade técnica real seja evidente, porque na verdade pode apenas estar gerando outro problema.
Comment: Tira o () de Car()
Comment: Olá @MarconcilioSouza, é um bom link, mas como já disse, precisamos ter certeza qual a necessidade real do código, se é realmente OO, se precisa do método, se ele estiver aprendendo OO não adianta muito só chegar e demonstrar o "meios" sem ter um contexto claro de suas necessidades. O link não é ruim, como já disse, mas é só uma série de como resolver problemas sem entender para que servem.
Comment: Olá @MarconcilioSouza removida não, editada pelo autor e detalhada. Eu não acho que o link seja ruim como eu disse antes, até explica algumas coisas, mas a resposta abaixo também explica (vale lembrar que somos uma comunidade em português). Mas estou apenas tentando orientar a "todos" que a pergunta esta com problema, só me segurei para fecha-la porque vi atividade de 3 usuários, fora o autor e estou avaliando como fazer isso sem causar mal estar a ninguém. Espero que compreenda que vim aqui apenas querendo ajudar e claro esperando ver suas opiniões também. Obrigado.
Comment: A pergunta não está na melhor forma, mas não tem muita dificuldade em responder isso. Eu fiquei curioso em saber o que a resposta tem de errado, porque eu mesmo quero aprender com a pessoa que negativou e sabe de algo que eu não sei sobre o assunto.
Comment: @MarconcilioSouza Que detalhes você quer? Não importa a versão do Python para resolver isso. O erro nada tem a ver com o primeiro comentário, que aliás desviou completamente do assunto real da pergunta e aí tem gente começou achar que a pergunta é sobre outra coisa, mas é culpa dos comentários e não da pergunta. Se a resposta não está errada, não merece negativo. E a resposta resolveu o problema, o AP até chegou comentar, mas eu apaguei porque não é comentário relevante. Vocês querem mais detalhes, mas a pergunta é muito simples, isso virou uma torre de marfim. Não tem o que problematizar.
Comment: @MarconcilioSouza eu vi oportunidade de explicar algo que muita gente confunde, infelizmente o fuzuê que fizeram jogou tudo no lixo, e quando tiver outras oportunidade dessa terei que responder de novo. O site existe para criar conteúdo que ensina as pessoas resolver seus problemas e a pergunta era boa pra isso, pena que estragaram. Se teve essa oportunidade e dava pa responder bem não tem porque ser fechado. Vocês criaram uma situação confusa, a pergunta não era confusa, só não era uma maravilha.
Comment: As pessoas precisam entender qual é o objetivo do site e aqui foi atingido (exceto por esse monte de negativos em algo que não é tão ruim, tem coisa muito pior, coisa errada, que desensina, que causa problemas que não tem tanto assim. E esse tip ode atitude já foi discutido antes no meta, as pessoas entram em uma espiral positiva ou negativa de acordo com o fluxo e não de acordo com a qualidade do conteúdo. Não merece positivo, mas não esse negativos todos. A resposta então nem se fala, nem quem deu concorda que ela está errada.
Comment: Pode sinalizar ou discutir no meta todas perguntas elaboradas que foram fechadas. Escrever um monte de coisa não significa que dá pra responder bem, geralmente é o que causa confusão. Algumas pessoas acusam o SOpt de não gostar de novatos, eu gosto, tanto que perguntas simples são respondidas por mim. Eu não gosto de gente sem noção, que pega algo complexo pra fazer e não tem condições, quer que outras pessoas resolvam pra ela. Quem não gosta de novato é quem não entende o site.
Answer: O método beep() não tem parâmetro algum, e você está passando um argumento quando chama ele. Colocando o parâmetro self que é sempre obrigatório quando está criando um método resolve o problema:
class Car:
    def beep(self):
        print('Beep')

car = Car()
car.beep()

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Quando chama car.beep() na verdade está chamando uma função dessa forma: Car.beep(car), ou seja, está chamando uma função chamada beep() com sobrenome Car, já que ela só é vista dentro dessa classe, e está passando o valor da variável car como argumento da função. Então tem que ter uma variável como parâmetro dessa função, e se convencionou que sendo um método o nome desse parâmetro é self.
Assim também funciona:
class Car:
    def beep():
        print('Beep')

car = Car()
Car.beep()

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Mas não é o que deseja, isso não é um método de instância, ele [e estático.


Embedding base64 encoded Java-Applet in HTML

Question: I tried to embed a base64 encoded Java-Applet in my HTML-file.
I thought I could use a data-url like in my example below:
<applet
    name="AppletName"
    id="AppletId"
    code="Applet.class"
    archive="data:application/x-jar;base64,UEsDBBQAAAAIAGY/eziUsj5wxAAAABwB...
</applet>

This did not work. In my tests Firefox and Chrome crashed.
I also tried different MIME types.
Any Ideas?
Thanks in advance!
Comment: Java applets aren't meant to be base64-encoded. Also, why is this tagged [tag:javascript]?
Answer: There are a few issues:

The tag applet does not have the correct attribute values
The base64 encoded data URI must be able to be decoded by a browser, not a plugin


Statıstıc problem

Question:
Will I use binomial distribution for this question? Can you help me please thnk you
Comment: Yes, you should use the binominal distribution. What are your ideas ?
Comment: Your solution is correct. :)
Comment: My sollutıon is correct or not? @calculus
Comment: :) thnk you @calculus
Answer: You are correct!
$p^m (1-p)^{n-m}$ is the probability of winning $m$ out of $n$ games in a specific order, ie. e.g. win, then lose, then lose, then win, then win... To get the probability for any order you multiply by ${n \choose m}$ which is exactly what you have done.
Comment: Thnk you :) @jolle

Statıstıc problem


regex to match a substring, but not starting with certain characters

Question: I am searching for a substring e.g. test , in a longer string e.g. alongstringtest.
In this example it would match ok
but I want to exclude certain cases ( when 'test' preceded by certain characters)
e.g.

do not match 'a-test'   (because of '-' )
do not match 'abcgtest'   (because of 'g' )
do not match 'abc"test'   (because of '"' )

I haven't written any regex for a long time, so this has me pulling my hair out abit !
Comment: not sure why I've been marked down for asking a question, have i done something wrong ?
Answer: Use negative lookbehind:
(?<![-g"])test

Answer: The simplest answer is
/(?<![g"-])test/

But there is room for optimization if you need more performance. If test can't appear at the very start of the string, then the following is a clear winner in terms of simplicity and performance:
/[^g"-]test/

Otherwise, I'd try the following:
/test(?<![g"-].{4})/s

/^test|[^g"-]test/

/^test/ || /[^g"-]test/

Note: - can have special meaning in character classes, but not if it's the first character, the first character after the negating ^, or the last character. I always use it last; it keeps things nice and simple.


Who gets the point in this hypothetical badminton move?

Question: There are two badminton players, A and B.
A makes a sort of eccentric move. This involves a woodshot by the tip of the racket that caused the shuttlecock to turn into boomerang, first moving vertically backwards, then upwards and forwards above the net, crossing to the other side, then moving down and backward again like going full circle, finally touching the net on the side of player B, before dropping down on the side of B. The entire sequence is so swift it is almost impossible for player B to catch the shuttlecock before hitting the net on his/her side.
I have hypothesized this as a special move in the novel I am writing about badminton. I am aware of two conflicting rules here:

Whoever hits the shuttlecock last before it hits the net loses the point to the opponent (in this case A loses);
Whose side the shuttlecock falls upon loses the point (in this case B loses).

Regarding this certain move, it is mere hypothetical but I think it is possible to execute if physics is concerned, but given the force it requires, it can destroy the feathers of the shuttlecock in the process, so I dub it the Birdkill move in my novel draft.
So the question is will this kind of move be beneficial to player A or will it be considered a fault giving the score to player B?
Answer: What you describe is just a fancy tumbling net cord shot. These shots can certainly touch the net or come close to it on the returner's side of the net. See this video for ample samples, and some examples of people returning these shots.
In the official Laws of Badminton, there is no rule saying that whoever hits the shuttle last into the net loses a point. The relevant rules are (emphasis mine):

§15.1 A shuttle is not in play when it strikes the net or post and starts to fall towards the surface of the court on the striker's side of the net.
§15.2 A shuttle is not in play when it hits the surface of the court.

§15.1 does not apply here since the shuttle touches the net on the returner's, and not the striker's side. So if B is unable to return the shot, then it's simply a point for A because the shuttle lands within the court boundaries.
In real life, this shot does not require force but control, and is thus played with the strings rather than the frame.
A has another problem though: Since the shot completely destroys the shuttle, it's going to be a let:

§14.2.4 It shall be a let if during play, the shuttle disintegrates and the base completely separates from the rest of the shuttle.

If you hit a shuttle really hard, it won't disintegrate right away; top players do that all the time. But shuttles will break much faster the harder you hit.
However, the resulting shot of hitting with a lot of force is a very fast smash, and definitely not tumbling. Drag grows quadratically with speed, so the forces acting on a shuttle to stabilize are much stronger for fast shuttles.
So why not have A be able of very fast smashes, faster than B can react? This moves the ability from fantastical (which is fine if you're aiming for a Dragon Ball or Harry Potter style, but strange if the novel is set in real life) to something that is certainly possible:
Usually the fastest smashers are professionals, but it is absolutely not unheard of for strong amateurs – or professionals who lack in other areas of the game – to get the timing and technique of an extremely hard smash just right. Maybe A has this timing down, trains smashes all the time, has the perfect arm length, and does plenty of relevant strength work in the gym.
This allows you to not alienate badminton-aware players, keep the Birdkill name, and have A have a finishing move (although maybe B can find a strategy to negate this?).
Alternatively, A may be an excellent net player, somebody who can play excellent tumbling net shots, maybe tricking their opponent as to whether the shot is going long-line or cross. This keeps the results of the shot you envision, but it does not destroy shuttles, and the player archetype is more of a trickster rather than brute force guy, even if in real life net shots requires a lot of repetition too.


Isometric to Dual implies Hilbertable?

Question: Let $X$ be a Banach space and suppose that $X$ is isometric to its continuous dual space $X^*$. Must $X$ be hilbertable in the sense that there exists an inner product which induces the norm on $X$? The converse of this statement is the Riesz representation theorem for hilbert spaces; I am wondering if the theorem can be stengthened to "if and only if".
Comment: More examples are given in this [MO](https://mathoverflow.net/questions/91326/self-dual-normed-spaces-which-are-not-hilbert-spaces) post.
Comment: @Theo: well, you took the time to give more detail, so you deserve the points! Tangentially related: I believe it is an open problem whether $X$ and $X^{\ast\ast}$ are necessarily isomorphic whenever $X$ and $X^{\ast\ast}$ are isomorphic to complemented subspaces of one another. Meanwhile, it is known that $X$ and $X^{\ast\ast}$ needn't be isomorphic if $X^{\ast\ast}$ is isomorphic to a complemented subspace of $X$.
Answer: Here's a construction:
Take any reflexive Banach space $X$. Take the direct sum $E = X \oplus X^{\ast}$ and equip it with the norm $\|(x,x^{\ast})\|_E =
\left(\|x\|_{X}^2 + \|x^{\ast}\|_{X^{\ast}}^2\right)^{1/2}$. This space is usually denoted by $E=X \oplus_2 X^{\ast}$ for short.
Then $E$ is isometric to its dual space $E^{\ast} = X^{\ast} \oplus_2 X^{\ast\ast}$: An isometric isomorphism is given by $(x,x^{\ast}) \mapsto (x^{\ast},i_{x})$ where $i:X \to X^{\ast\ast}$ is the canonical inclusion (by reflexivity of $X$ the map $i$ is an isometric isomorphism).
The space $E$ won't be isomorphic to a Hilbert space unless $X$ is itself isomorphic to a Hilbert space.
In fact, a (real) Banach space is "Hilbertable" if and only if every closed subspace has a complement by a (very deep) Theorem of Lindenstrauss and Tzafriri.
So: If $X$ is not isomorphic to a Hilbert space, it has a subspace that isn't complemented, and thus so has $E$.

Isometric to Dual implies Hilbertable?


How to get process network usage in Windows in python?

Question: I'm using Python 2.7 and Windows 7 (but I need it to work on at least XP as well).
How can I get the percentage of the network bandwidth used by my program written in Python? So if the internet speed is 20 Mbit/s, and my program is connecting to the web at a "full speed", it'd write 100%, etc.
Thanks in advance!
Answer: You would need to develop a windows network driver with such capability.
Check the related answer at:
Monitor a process's network usage?


Display referencing entity in panels

Question: I have two content types.
1. Lecture
2. Notes
Notes have an entity reference field which references lecture.
Different users create different notes each referencing to a lecture.
Now,
How do I display note created by user on lectures page.
Answer: I know how to do it with Views and Panels modules.
First you need to create two Views:

First one is Lecture_view create a block and add fields you want to display(Title, body, most important - Content: Nid  and any other fields your Content type has).
Second one is Notes view, create same block but fields for notes to display, and also in a
Contextual filters menu add  new filter (Content) Content: Nid

Now you should go to Lecture view and in Advanced menu, click on theme information link, and you need to create template file, find row with Field Content: Nid and create one of suggested fields, something like (views-view-field--conversations--page--nid-1.tpl.php) in /sites/all/themes/YOURTHEMENAME/views/YOURVIEWNAME(lecture_view--block)/YOURTEMPLATEFILE(views-view-field--conversations--page--nid-1.tpl.php) in this file you will past code from theme view, its something similar to
<?php print render($output); ?>

you need to add one more thing embed that views:
<?php print views_embed_view('notes', $display_id='default', $row->nid); ?>

your contextual filter should work, and now you can add this view to your Panel to display, in Panel menu.
Maybe this is not the best way to do this

Display referencing entity in panels


Duvida replace no pandas

Question: Duvida no replace no dataframe pandas
texto = 'Vírus de computadores são uma lenda urbana.'

dado = {'texto': [texto]}
df = pd.DataFrame(dado)

df['nova_coluna'] = df.texto.str.replace('urbana', '')

Ao criar essa nova coluna podemos comprarar que a palavra 'urbana' foi retidada
porém se colocar essa expressão dentro do for não da certo
palavras = 'computadores', 'uma', 'lenda'

for palavra in palavras:

    df['nova_coluna'] = df.texto.str.replace(palavra, '')

é criado a coluna mas as palavras não são trocadas
Answer: O problema é que quando você faz df['nova_coluna'] = df.texto.str.replace(palavra, '')
você esta alterando o texto original a todo o momento, ou seja, uma iteração você remove 'computadores' e não salva, depois 'uma' e não faz nada.
import pandas as pd

texto = 'Vírus de computadores são uma lenda urbana.'

dado = {'texto': [texto]}
df = pd.DataFrame(dado)

palavras = 'computadores', 'uma', 'lenda'

for item in range(len(palavras)):

    texto = texto.replace(palavras[item], '')

df['nova_coluna'] = texto

Answer: Primeiro palavras terá conteúdo: "lenda". A declaração correta de listas é:
palavras = ['computadores', 'uma', 'lenda']

Depois vem o próximo problema. df['texto'] tem apenas 1 valor (o termo correto é outro na verdade) e se substituir os valores da lista palavras, meu df['texto'] teria 3 valores. O que é um problema. Então vou mostrar uma forma de resolver e depois você adapta para o que realmente precisa :)
import pandas as pd

texto = 'Vírus de computadores são uma lenda urbana.'

dado = {'texto': [texto]}
df = pd.DataFrame(dado)

df['nova_coluna'] = df.texto.str.replace('urbana', '')

for palavra in palavras:
   df['nova_coluna'] = df.texto.replace(palavra, '')
df

Nesse caso o valor de df.nova_coluna é apenas um. Porém, ela passou por 3 valores em cada iteração do laço:

1: 'Vírus de são uma lenda urbana.'
2: 'Vírus de computadores são lenda urbana.'
3: 'Vírus de computadores são uma urbana.'

Pois o valor de df.texto ('Vírus de computadores são uma lenda urbana') vai ser sempre usado para definir o valor de df.nova_coluna.

Duvida replace no pandas


How do I write a structure containing a dynamic allocated array to a binary file?

Question: #include <stdio.h>
#include <stdlib.h>

struct SomeStruct{
    int id;
    int* dynamicArray;
};

int main(){
    struct SomeStruct test;
    test.id = 5;
    // allocate array
    test.dynamicArray = malloc(sizeof(int)*100);
    // save struct to a file
    FILE* handle = fopen("data", "wb");
    fwrite(&test, sizeof(test), 1, handle);
    fclose(handle);
    return 0;
}

After running this code the size of data file is 16 bytes.obviously an integer pointer has been written to the file instead of whole dynamicArray elements. How can I write such structure correctly in a file?
Comment: There is no merit in writing the pointer to file - you should write the data it points to. It would be advantageous for the `struct` to have a member `size_t size` so you know how much memory to allocate, and elements to read, when you reload the file later.
Comment: Also consider how you would read the data back from a file, that should also hint to how you want to write the data.
Comment: Write the data pointed to by `dynamicArray`, and not the struct, which contains the ***pointer to the data of the array***, and not the array itself.
Comment: You should create some simple format to store data. At least the dynamic array content should be stored in the file( more complicated if itself contains pointers), and a way to associate `SomeStruct` with that data in the format.
Comment: You keep track of how many entries are active in the array (or the max array size if you wish) and write that out after you write the id.  Might be nice to write out the number of used elements into the structure as well for ease of reading later...
Comment: Thanks for answers. seems this is not a good way for storing structures :(
Answer:
Write the id.
Then write the array.

fwrite(&test.id, sizeof(test.id), 1, handle);
fwrite(test.dynamicArray , sizeof(test.dynamicArray[0]), 100, handle);

I want to point out that use of the hard coded number 100 is problematic.

You have to make sure that the read function also assumes that.
If you decide to change the number of elements allocated, you'll have to remember to go back to both places (the write and the read) to update them.

It will be better to store the size in the struct itself.
struct SomeStruct{
    int id;
    size_t size;
    int* dynamicArray;
};

and
test.id = 5;
test.size = 100;
// allocate array
test.dynamicArray = malloc(sizeof(int)*test.size);

Then you can update the write logic to:
fwrite(&test.id, sizeof(test.id), 1, handle);
fwrite(&test.size, sizeof(test.size), 1, handle);
fwrite(test.dynamicArray , sizeof(test.dynamicArray[0]), test.size, handle);

When you read the data back in, you will have the size information available to you and you can allocate the right amount memory for the dynamicArray member.
Comment: you are right. it should work. but as @Nit mentioned it is hard to read data back from file.


D7 - download files works for admin, not for other users

Question: There is a content type for accepting job applications, including resumes and cover letters as files uploaded. The files are set to private.
The form/page is set to unpublished by default - largely to 'fix' some other wonkiness.
Users with admin privileges have no trouble downloading the resume and cover letter files.
The more limited users in HR cannot - Drupal returns a message

You are not authorized to access this page.

I've been tweaking permissions trying to find the magic bullet. The HR user can 'Edit' the individual's application form, but even though the associated resume or cover letter file is shown as a link, once again, the HR role is not authorized.
Any ideas what permission I need to toggle? What's blocking the ability for the HR role to download the file?
Comment: Can you find how they have done the "private upload" feature? Does "HR" role has permission to "administer content"?
Answer: As you setup the content type default as unpublished, this will prevent any one to see the individual content but the author of the content(if he or she has permission to "View own unpublished content") and User with the privilege of "Bypass content access control"
which probably you don't want to give it to any one but admin, so basically there is a better approach to this :
I recommend to
1) setup content type default as published
2) Setup Content Access module http://drupal.org/project/content_access
3) Setup content type access permission by Content Access module.
3-1) Use Content access module to prevent any user but HR to have access to the specified content type. This will prevent any one to have access to following content type but HR, so you don't need to worry about content being published.
3-2) give permission to the specified rules (maybe anonymous or authenticated) to be able to create the specified content type.
Note: Don't do this in production environment, first test it to make sure everything is as you want it since "content access" module will rewrite your current website permissions.
If it still seems confusing let me know I will add photos to explain it.
Comment: Narek, thanks! I'll try this - and in staging of course!


Prove these two integrals are equal.

Question: Prove that:
$$\forall n,m \in \Bbb N:\int_0^1 x^m(1-x)^n \,dx=\int_0^1(1-x)^mx^n \,dx$$
I really have no idea.
Comment: Slow day on the hot questions.....
Answer: Hint: with $u = 1-x{{{{{}}}}}$.
Comment: Can you tell me more? I tried to use $u=1-x,$ but I was failed.
Answer: Setting $t=1-x\iff x=1-t$, we have $\mathrm d\mkern1mu x=-\mathrm d\mkern1mu t$,  hence the change of variable formula yields:
$$\int_0^1 x^m(1-x)^n \,\mathrm d\mkern1mu x=\int_1^0(1-t)^m t^n (-\mathrm d\mkern1mu t)=\int_0^1t^n(1-t)^m \,\mathrm d\mkern1mu t=\int_0^1 x^n(1-x)^m \,\mathrm d\mkern1mu x. $$
Comment: Because $t$ and $x$ are dummy variables. It is the same with `\sum_{i=1}^5 (2i-1)=\sum_{k=1}^5 (2k-1)`: they're both equal to `25`. In other words: theyre just place-holders.
Comment: One also says *bound variable*.
Comment: I don't see your last step. Why $\int_0^1 t^n(1-t)^m dt=\int_0^1 x^n(1-x)^m dx$ ?
Comment: Is "dummy variable" the official name of it?

Prove these two integrals are equal.


Como faço para disparar um alert com o click de um botao em javascript?

Question:

let iniciar = document.getElementById("iniciar")
let pausar = document.querySelector('.pausar')

iniciar.addEventListener("click", function(event) {
  alert('Cliquei no iniciar')
}, true);

pausar.addEventListener('click', function(event) {
  alert('Cliquei no pausar')
});
<button id='iniciar'>Iniciar</button>
<button class='pausar'>Pausar</button>
Answer: Complementando a resposta do pedro, é legal separar JavaScript de html. Ficaria assim:

document.getElementById("btnAlerta").addEventListener('click', MeuAlerta);

function MeuAlerta() {
  alert('Escreva a mensagem');
}
<button type="button" id="btnAlerta">Alerta</button>
Answer: Tente isso:

function MeuAlerta() {
  alert('Escreva a mensagem');
}
<button type="button" id="btnAlerta" onchange="MeuAlerta();">Alerta</button>
Comment: Obrigado.... =)
Comment: Esse código não funciona.