Value do Input Submit com duas cores

Question: Minha primeira pergunta aqui... iniciando meus estudos...
Estou com o seguinte problema:
<input type="submit" value="Enviar E-book">

Preciso que no texto do bt, "Enviar" seja de uma cor e "E-book" de outra. É possível?
Não consigo trocar por <button>, porque é um form importado que já vem com essa tag input.
Comment: primeiro qual a finalidade disso? ou seja, para que?
Comment: finalidade estética, é o que a pessoa quer
Comment: Se a resposta abaixo resolveu o seu problema e não restou nenhuma dúvida, marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida. Se ainda te resta alguma dúvida ou gostaria de maiores esclarecimentos, fique à vontade para comentar.
Answer: Veja a documentação <button>: The Button element :

Conteúdo permitido: Permitido conteúdo fraseado mas não conteúdo interativo.

Então apenas coloque um conteúdo válido dentro do botão e aplique um estilo.

.txt1 {
  color: red;
}

.txt2 {
  color: blue;
}
<button class="button">
  Enviar
  E-book
</button>

Então no seu caso como o botão do servidor vem como <input> e esse elemento não suporta conteúdo aninhado. Pegue a referência do input e substitua por um <button> usando a propriedade Element.outerHTML que descreve o código HTML do elemento incluindo seus descendentes.

const btn = document.getElementById("btn");

btn.outerHTML = `
   <button class="button">
      Enviar
      E-book
   </button>`;
.txt1 {
  color: red;
}

.txt2 {
  color: blue;
}
<input type="button" id="btn">
Comment: @LeAndrade, dá uma olhada.
Comment: Entendi Augusto : )
Comment: +1 pelo ideia de usar `outerHTML`. Não sabia dessa...
Comment: No relato dele, ele não consegue trocar o tipo do elemento de **input** para **button**, logo, não daria para aplicar sua resposta Augusto.
Comment: Eu estava com medo da pergunta ser fechada antes de conseguir responder e mandei metade

Value do Input Submit com duas cores


Is $L=\{w\mid \text{ same number of 010 and 101}\}$ regular?

Question: I tried to prove that this language is regular using NFA or regular expressions and didn't succeed.
I would like to see some solutions
Comment: Why do you think it is regular? Also, what do you mean by "same number"? How are you counting? Does $010111010$ count?
Comment: @ThomasAndrews Thanks for the clever edit, I learned of $\mid$. thank you
Comment: I am not sure its regular. and I count every instance even if there is an intersections
Answer: This is not a regular language. The "problem" is you need to count how many $010$ and how many $101$ strings appear in a word and regular languages don't know how to do this.
For a more formal proof start by defining a homomorphism $0 \mapsto 00100$ and $1 \mapsto 11011$. If your language was regular, then the inverse image of the homomorphism is also regular, but this inverse image is just
$$\{ w \mid 0,1\; \mbox{appears the same number of times}\}.$$
Intersecting it with the language $\{0^n 1^m\}$ (which is also regular) you get another regular language which is $\{0^n 1^n\}$ - contradiction.
Comment: @ThomasAndrews : Thanks, corrected it.
Comment: Can you explain why is {w∣0,1 appears the same number of times}. is the inverse of the homomorphism?
Comment: @Eyalbason : If w is any word and $\varphi(w)$ is its image, then the only way 010 can appear in the image is inside $\varphi(0)=00100$ and similarly 101 appears only in $\varphi(1)=11011$


The fastest way to get the last key/value pair of an associative array in PHP?

Question: What is the fastest way to get the last key/value pair of an associative array in PHP? I know there are some wordy ways to do this. But what's the most concise and efficient way?
Answer: <code>end($array); //value
current($array); //another way to get the last value after calling end
key($array); //key (after calling end)
</code>


What is the significance of string data member?

Question: String data
What I am particularly confused about is this statement
"Its contents are guaranteed to remain unchanged only until the next call to a non-constant member function of the string object."
Can someone clarify what does this mean? When to use this and when to avoid using this?
Answer: They mean that you could store the pointer and use it later. If some non-const method is called between two accesses the contents of the buffer your stored pointer is set to may change and your will face unexpected behaviour.
Answer: const char* data() const;

This is saying that the const char * returned by calling str.data() will not change unless someone modifies the string that it came from.  Once someone calls a non-constant member function, the returned pointer could be invalid, or could point to different data from what it pointed to immediately after the str.data() function returned.
It means you can pass the returned data to C functions, for example.  It means you should not do something like:
const char *old = str.data();
size_t      len = str.length();
...call a function that modifies str...
// cout << old << endl;
// Since old is not guaranteed to be null terminated (thanks MSalter),
// do something else with the old data instead of writing to cout.
// Inventiveness not at a high this morning; this isn't a particularly
// good example of what to do - a sort of string copy.
char buffer[256];
memcpy(buffer, old, MIN(sizeof(buffer)-1, len));
buffer[len] = '\0';

By the time the I/O memory copying is done, old may not be valid any more, and len may also be incorrect.
Comment: Addition:
Usually operations on a string cause changes of c-string that is wrapped inside string. As operations like append require reallocation of c-string, it's previous memory location is freed and not used anymore.
Comment: "Usually" being the important word, because there are a number of implementations of std::string that don't wrap a C string (the singlemost common exception is not having a \0 in the wrapped char[])
Comment: Oh, the example is wrong BTW: cout requires a null-terminated string, and data() in general isn't.
Comment: @MSalters: so you are saying - if the member function had been `c_str` instead of `data`, then the result would be guaranteed null terminated, but given that it is `data`, the result is not guaranteed to be null terminated? ...from the URL in the Q: "_Notice that no terminating null character is appended (see member c_str for such a functionality)_"; OK.  My bad.  I'm not sure what you can do safely with the result from `data`; you need to know the length, somehow; presumably string::length() gives the right answer.  Thanks for the heads up - I missed that detail.
Answer: Sometimes, you need to have access to the string formatted as an array of characters - usually because you need to pass the string to some function which expects the string like this (for example strcmp). You can do this by using the data or c_str members, but you have to respect the rules for calling the function which are spelled out plainly in the link you provided:

The returned array points to an
  internal location which should not be
  modified directly in the program. Its
  contents are guaranteed to remain
  unchanged only until the next call to
  a non-constant member function of the
  string object.

You cannot modify the array of characters - the string object assumes that you do not, and if you do this will lead to undefined behaviour.


How to restrict access to specific php file to only athenticated users

Question: I manually made a php file that has the ability to connect to the database and create table entries, it works fine, but now the problem is that if I leave it there, anyone will be able to access it to create entries.
So I want to restrict the access to that file to only authenticated users, I think this may be posible using the .htaccess file, but I don't know how just yet.
Answer: .htaccess won't help with this; Apache doesn't know what an authenticated Drupal user is, and there's no easy way to grant it that knowledge. Fortunately there's a much better option:
Create a route in a custom module, and execute your code in its controller. You can easily protect the route with permissions, or by role. Aside from the flexibility this gives you around access control, you can also refactor your custom DB code to use Drupal's database API, making your code more future-proof.
The other option, less desirable IMO for your requirements, is to bootstrap Drupal in your custom PHP file, and use the current_user service to determine whether the user has access to your script.
Comment: And inside the controller you can always use the drupal way of writing queries, with entity query api etc... now it depends on your use case but I personally believe it's always better @julianx2rl


Confusion on the proof of continuous time optional stopping time theorem.

Question: In the proof of Doob's (continuous version) optional stopping time theorem, most of the literates claims the follows:

Given an $\mathcal{F}_{t+}-$stopping time $\tau$, define $$\tau_{\ell}=\dfrac{[2^{\ell}\tau]+1}{2^{\ell}}=\sum_{k\in\mathbb{N}}\dfrac{k}{2^{\ell}}\mathbb{1}_{\{\tau\in[\frac{k-1}{2^{\ell}},\frac{k}{2^{\ell}}]\}}, \ \ \ \ell\in\mathbb{N}.$$
Then it is clear that $\tau_{\ell}$ is a stopping time with respect to $\mathcal{F}_{t}$, $\mathcal{F}_{\tau_{n}}\supset\mathcal{F}_{\tau+}$ and $\tau_{n}\searrow\tau $.

However, I don't quite see why this claim is true.
One of the note online provides the proof of $\tau_{\ell}$ being a $\mathcal{F}_{t}-$stopping time:

Fixing $\ell\in\mathbb{N}$, let $\mathbb{Q}^{(2,\ell)}=\{k2^{-\ell}:k\in\mathbb{Z}_{+}\}$  By construction of $\tau_{\ell}$, it takes values in $\mathbb{Q}^{(2,\ell)}\cup\{\infty\}$. With $\{\tau<t\}\in\mathcal{F}_{t}$ for any $t\geq 0$ it follows that for any $q\in\mathbb{Q}^{(2,\ell)}$, we have $$\{\omega:\tau_{\ell}(\omega)=q\}=\{\omega:\tau(\omega)\in [q-2^{\ell},q)\}\in\mathcal{F}_{q}.$$ Thus, $\tau_{\ell}$ is an $\mathcal{F}_{t+}-$stopping time.

I understand most of it, but it only proves $\{\tau_{\ell}(\omega)=q\}\in\mathcal{F}_{q}$, why does this implies $\tau_{\ell}$ is a $\mathcal{F}_{q}-$stopping time? Wouldn't we need to show $\{\tau_{\ell}\leq q\}\in\mathcal{F}_{q}$?
Also, I have no idea about how to show $\mathcal{F}_{\tau_{n}}\supset\mathcal{F}_{t+}$ and $\tau_{n}\searrow\tau$, any idea?
Thank you!
Answer: Note that $\tau_\ell$ is a way to discretize $\tau$. You create $\tau_\ell$ as follows:

Split $[0,\infty)$ evenly into intervals of length $1/2^{\ell}$, i.e. intervals of the form $[(k-1)/2^\ell,k/2^\ell]$  for $k=1,2,\ldots$
If $\tau$ takes value in $[(k-1)/2^\ell,k/2^\ell]$, define $\tau_\ell$ as $k/2^\ell$.

For example, if $\ell=1$, you first split $[0,\infty)$ into the intervals $[0,1/2]$, $[1/2,1]$, $[1,3/2]$, and so on. You then check where $\tau$ lies. If it lies in $[3,7/2]$, for example, you define $\tau_\ell$ as $\tau_\ell = 7/2$.
Note that by this construction, $\tau_\ell$ will be larger than $\tau$. And as you increase $\ell$, the split of $[0,\infty)$ into the intervals $[(k-1)/2^\ell,k/2^\ell)$ will become finer and finer (i.e. the intervals will become smaller and smaller), and the value you select for $\tau_\ell$ will become closer and closer to the actual value of $\tau$. This is why $\tau_\ell \downarrow \tau$.
I add that this is a well-known discretization/approximation technique, and it is usually used to prove the monotone convergence theorem in measure-theoretic probability. You might want to look that up to understand this construction better.
The reason it is sufficient to show that $\{\tau_\ell=q\} \in {\cal F}_q$ is that $\tau_\ell$ takes only countably many values (it can only be $k/2^\ell$ for some $k \in \mathbb{N}$), so $\{\tau_\ell \leq q\} = \cup_{x \leq q} \{\tau_\ell=x\}$ is a countable union of sets from ${\cal F}_q$, which is in ${\cal F}_q$.
For the claim ${\cal F}_{\tau+} \subset {\cal F}_{\tau_\ell}$, do you know the defition of ${\cal F}_{\tau_\ell}$?
Comment: Yes, I know the definition, $\mathcal{F}_{\tau_{\ell}}$ is the collection of set $A$ such that $A\cap\{\tau_{\ell}\leq n\}\in\mathcal{F}_{n}$ for all $n$. Thus, by your argument, it suffices to show $A\cap\{\tau_{\ell}(\omega)=q\}\in\mathcal{F}_{q}$ for any $A\in\mathcal{F}_{\tau+}$? (I am sorry that I mean $\mathcal{F}_{\tau+}$ instead of $\mathcal{F}_{t+}$, I will edit my post).
Comment: Do you have any reference for me to read a formal proof of $\tau_{\ell}\searrow \tau$? Thank you so much!
Comment: I am going to assume that in the definition of $\tau_\ell$, there is a half-open interval $[(k-1)/2^\ell,k/2^\ell)$ in the indicator, so that $\tau_\ell > \tau$. This property is used in the argument you present for $\tau_\ell$ being a stopping time. In that case, take $A \in {\cal F}_{\tau+}$. Since $\tau_\ell > \tau$, we have $\{\tau_\ell \leq t\} = \{\tau_\ell \leq t\} \cap \{\tau < t\}$. Then $A \cap \{\tau_\ell \leq t\} = \{\tau_\ell \leq t\} \cap (A \cap \{\tau < t\})$, and both sets are in ${\cal F}_t$.
Comment: For the reference, you can for example take a look at the below link, in particular the figures on page 4. Note that in this reference, the approximation gives a lower-bounding function, while we are looking for an upper-bounding function here. You can get more references by searching for something like "approximating measurable functions by simple functions". https://people.math.gatech.edu/~heil/6337/spring11/section4.1.pdf
Comment: Thank you so much!!


Rotating vector around arbitry axis when vector is in origin {0,0,0} (3D)

Question: I'm trying to rotate a vector that is at the origin {0,0,0} around an arbitrary axis (in this case the rotation is around {40,30,30} through {40,31,30}).
The problem appears to be that I can't rotate a {0,0,0} vector, because it always remains 0. I remedied this by moving it towards the point I want to rotate around ({40,30,30}) and moving it back after the rotation.
However, I don't know if this is the right way to do it, and I'm having a hard time finding anything about it.
As far as I understand, the translation towards the origin before rotation should take care of the problem that the vector to rotate is at the origin itself, but it doesn't appear to be working as such.
It's software that I wrote myself, so it's possible I messed something up. But I'm really not sure anymore.
Comment: Sometimes we view vectors as just an arrow that has length and direction.  Sometimes we view them as an arrow with the root attached to some point in space.  The first is more common.  For the first the only rotation you can do is to change the direction of the vector.  As you say, you can't rotate a zero length vector because it has no direction.  For the second, you can rotate the location of the root of the vector even if it is the zero vector.
Comment: If you say the vector is at $(0,0,0)$ that could mean it is the zero vector with zero length or it could mean you are regarding the root as being at the origin but the head is somewhere else.  You need to make clear what you are trying to do.
Comment: It is a zero vector with zero length.
Since I'm trying to rotate it around a different axis, it should still be possible to move it, right? I'm not trying to rotate it around the origin, but around a different vector in space.
Comment: The zero vector has no length, hence it has no angle with. rotating it will not change anything because it can be view as a point. If you want to rotate a vector that start at $(0,0,0)$: https://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions and http://mathworld.wolfram.com/RodriguesRotationFormula.html
Answer: You can certainly rotate the point $(0,0,0)$ around your axis.  Your axis is parallel to $y$ and offset from the origin by $50$ units.  The easiest way to do this is to translate your axis and all of space to put the axis through the origin, rotate the space, and translate back.  Your translation is then by $(-40,0,-30)$ so your zero vector moves to $(-40,0,-30)$.  Now if you rotate this by an angle $\theta$ it becomes $(-40 \cos \theta -30 \sin \theta,0,30 \sin \theta -40 \cos \theta)$ if our sign conventions agree.  Translating back then gives your final point as $(40-40 \cos \theta -30 \sin \theta,0,30+30 \sin \theta -40 \cos \theta)$
Comment: This is what I'm doing right now, but it's not working. I assume there's a mistake in my code somewhere, or possibly that I'm doing some translations in the wrong order. Thanks for at least confirming what I thought I had to do.


Huge difference of sample size

Question: I have two samples, one has 34 measurements the other one has over 10000, neither of them follow normal distribution. Are there any pitfalls directly comparing two samples with huge different sizes? I am thinking of using the Mann-Whitney test.
Should I first do downsampling first? to equal the sample size?
Thanks
Answer: Comparing two samples of such different sizes, when one sample is large, is actually quite similar to doing a one-sample comparison to a known distribution.  To see this, imagine the more extreme case where you are comparing a sample of size $34$ to a sample of size $\infty$.  In the latter case, the infinite sample is equivalent to knowledge of the superpopulation, so you effectively have a one-sample test.
In the present case, the sample with $10,000$ values is going to tend to give you a highly accurate estimate of the underlying population distribution, and so having this sample is somewhat "close to" having knowledge of the population.  Most of the uncertainty in this comparison is going to come from the first population, where you only have a small sample size.  There are no inherent pitfalls in comparing samples of such different sizes, but obviously it would be desirable if you could get more data from the first population.
Comment: Thank you so much

Huge difference of sample size


Java Color(int rgba) constructor and int overflow

Question: According to the docs, this constructor exists:
public Color(int rgba,
         boolean hasalpha)

I'm failing to see how you could use this to create the equivalent of Color(255,255,255,255) (e.g. 0xFFFFFFFF) given that java has no unsigned ints, however.
How do you use this constructor for a "big" color?
EDIT
Evidently the constructor can be used (surprise), but parsing an RGBa color string like this fails:
    int x = Integer.parseInt("0xFFFFFFFF", 16); // Number format error
    Color c = new Color(x, true);

The solution seems to be to use BigInteger to do the parsing. Sorry for the misdirected question!
Answer: Your question is not misdirected, but you seems to have misunderstood Kon's answer:
You are right about Java's Integer being signed all the time, but this doesn't mean that there are less bits of information in that number.
When you create a Color:
new Color(255, 255, 255, 255)

it is the same as using:
new Color(0xFFFFFFFF, true)

or using:
new Color(0b11111111111111111111111111111111, true)

0xFFFFFFFF is in fact -1, but this doesn't mean that any of the bits change; It's only a question of representation. The Color just cuts out the necessary bits for each color component.
So you can, in fact, create your desired color using:
Color c = new Color(-1,true);
System.out.println(c);
System.out.println(c.getAlpha());

which yields:
java.awt.Color[r=255,g=255,b=255]
255

Comment: Helpful, thanks. More of my confusion was coming from the behavior discussed [here](http://stackoverflow.com/questions/4355619/converting-string-to-intger-hex-value-strange-behaviour).
Answer: Go binary.
Color c = new Color(0b11111111111111111111111111111111, true);
As per the Java docs, "alpha component is in bits 24-31, the red component is in bits 16-23, the green component is in bits 8-15, and the blue component is in bits 0-7"
Comment: So? The docs explain the aRGB bit positions, so it's an easy way to do it and make it clear. Not worth a -1 because the answer is correct, I just used the literal definition of the Javadocs linked by OP to stress the point.
Comment: 0xFFFFFFFF is exactly the same number. And the binary representation only work for java 7 and up.
Comment: I misunderstood that you actually did comprehend the problem at hand, because in my eyes your answer did not reflect it. I'll be able to remove my downvote if you edit your answer to make that point more clear.
Comment: No worries, I didn't really provide an explanation so your concern is understandable. I added a blurb about how I got to my answer.


Using pure javascript to prefill a textbox with a url hash

Question: I have a textbox on a web page. I would like to get the value of a URLs hash e.g. 12345 and place it as the value of the textbox upon loading the page (if there is a value), otherwise, I would like the textbox to remain blank.
I have tried using this code:
var hash = window.location.hash.substr(1);

function onoff(){
// pre-fill chat id textbox
  if(hash){
    var hash_value = window.location.hash.replace('#','');
    document.getElementById("chat").value = hash_value;
  } else {
    document.getElementById("chat").value = '';
  }
}

And in the html code(I am having trouble in calling the function).
<input type="text" id="chat" maxlength="5" required="">

If I were to change the value of the hash, would it be possible to have this fill the text box on load?
Comment: window.onload=onoff();
Answer: Sure thing! Just pass your function into window.onload:
var hash = window.location.hash.substr(1);

window.onload = function onoff(){
// pre-fill chat id textbox
  if(hash){
    var hash_value = window.location.hash.replace('#','');
    document.getElementById("chat").value = hash_value;
  } else {
    document.getElementById("chat").value = '';
  }
}

<input type="text" id="chat" maxlength="5" required="">

Hope this helps! :)
Answer: Execute your function on DOMContentLoaded. Note that this function can be limited to this:
function onoff(){
    document.getElementById("chat").value = window.location.hash.substr(1);
}

document.addEventListener("DOMContentLoaded", onoff);

To also capture pure changes to the hash (in which case the page is not reloaded), also capture the corresponding hashchange event:
window.addEventListener("hashchange", onoff);


How to inverse transform sample with a PDF that maps $\mathbb R^2$ to $\mathbb R$?

Question: Given a PDF:
$$
p(x,y) = \frac{\pi^2\sin(\pi x)\sin(\pi y)}{4}.
$$
I obtain a CDF using double integral:
$$
P(x,y) = \frac{(1-\cos(\pi x))(1-\cos(\pi y))}{4}.
$$
And then I'm stuck, normally one would proceed to invert the CDF, but I can't really invert a multivariate function, can I?
Comment: That is correct, which is why cdf can't be inverted for a multivariate function.  Fortunately, since your distributions has X and Y independent, you can simply calculate the cdf's of the marginals and invert them separately.
Answer: Since your distribution has $X$ and $Y$ independent of each other, you can calculate the cdf's of the marginals and invert them separately.  The marginal for $x$ is
$$p(x)=\frac{\pi}{2}sin(\pi x)$$
with cdf
$$P(x)=\frac{1}{2} -\frac{1}{2} cos(\pi x)$$ which inverted gives
$$x = \frac{1}{\pi}cos^{-1} (1 - 2P(x))$$


AngularJS: controlling ng-show from outside ng-repeat

Question: I'm in the middle of learning Angular, and I am attempting to show or hide contents in a content div depending on side menu items being clicked.

Side Menu

      API Name: {{ item.name }}

Content

Debug: {{ item.debug }}

Window: {{ item.window }}

What do I have to add to controller ng-show from the other div?
Comment: it looks like item.debug and item.window are outside the markup being generated using ng-repeat.  I would move them up/enclose them in the div that has ng-repeat on it
Answer: Use $parent:
ng-click="$parent.collapsed=!$parent.collapsed"

Example: http://jsfiddle.net/cherniv/6vhH3/
Read this to understand the most important basics of Angular' scopes.
Comment: Close, but `item.debug` and `item.window` don't display anything. I updated the [fiddle](http://jsfiddle.net/evanemolo/6vhH3/1/).
Comment: @EvanEmolo ah , i see.. no problem , take a look : http://jsfiddle.net/cherniv/hn55a/


Upgrade Rails App From 1.2.3 to 3.1.0?

Question: I'm working on Rails 1.2.3 version. Now I want to upgrade the Rails version as well as ruy version from 1.8.6 to 1.9.7.
Is it a major pain to work with such older version but it is in running condition. Now i want advance features of Rails but not supporting this older version .
Please suggest me the way to upgrade the version and ruby version.
Thanks....
Comment: I don't think there's a reasonable one-step process for this. I recommend upgrading to Rails 2 using a guide, making sure all your tests pass (and maybe give it a few days/weeks in production just in case...), then follow the upgrade guides from Rails 2 to Rails 3.
Comment: @Jordan : Thanks Man. But I did not have sufficient time to follow this step. If you have any idea to upgrade this then please let me know. I will try that approach.
Comment: @Jordan : Do you have any reference doc for this to upgrade Rails 1 to Rails 2 version. ? If you have then Please share... Thanks
Comment: Thanx Man for reply. I am following this blog : http://marklunds.com/articles/one/409 Please have a look and tell your view about this blog.
Answer: That is quite a leap. Your best bet is to create a new rails 3.1 app and then manually migrate your code over.
gem install rails #=> will install the latest stable release from rubygems
gem install bundler
rails new myapp

The first thing you'll need to do is open up Gemfile and add in any gems you're using in your current application, and it would also be a good idea to find the gem versions of any plugins you're using (in vendor/plugins). Also make sure you have the proper gem installed for the type of database you're using (mysql2, sqlite3, or pg).
After you've added all the gems you need, run bundle install to bundle all the gems with your application.
As far as views, models, and controllers, that stuff should all be okay to just copy over to the new application. You will probably need to tweak a few things, but for the most part that stuff should all work.
You'll also need to open up config/application.rb and configure your application. You can use your old environment.rb file as a reference.
The last step before you can start your application is to change your routes.rb file to the new Rails 3 format. This is probably the worst part of migrating, as you'll first need to learn how to write a Rails 3 routing file, and then manually write in your routes. More information can be found here.
I never used Rails 1 so it's possible that you may have to change some other things. These three Railscasts will definitely be a helpful resource for you.
Comment: Thanks Boss. Steps given by you is really fine or me. You said very well that Routing is going to kill me.
Answer: I have migrated a major application from 2.3.10 to 3.0.9
it's a very painful process and if I wanted to move to 3.1 it would have been even worse.
Depending on your application size, I would definitely recommend to create a new application and copy over the stuff.
Migrating from this old version of rails to the newest is definitely not in a single leap, there are so many different things to consider.
BUT, the best thing about my answer is that I DO recommend you do that, the process of testing, finding compatible gems etc... is so much nicer in rails 3 and ruby 1.9.2
Comment: Yes Man, You are right. It is better to make new application as clone of existing project. And we can use the logic as well as few code can be re-used. Otherwise whole junk code will create trouble while execution.
Answer: wow, as bricker said, it's quite a leap!  I used Rails 1 ages ago.. I didn't upgrade to Rails 2, I re-wrote.
How big is your Rails 1.2.3 application?
So many things have changed, features in Rails, so many Gems, Routing, Asset Pipeline, Named Scopes, the ActiveRecord Query API, ... even Ruby has changed --  it would be a bad idea to just upgrade.  There are many new concepts and features, which you will have to think about, and it will be much better to start from a clean slate.
This can be a blessing in disguise. I think this is a great opportunity for you to improve your code base by re-writing and re-architecting it in Rails 3.1 :-)
I would suggest to start from scratch on the Rails 3.1 application with the most critical features, while keeping the 1.2.3 application around in maintenance mode.
It's probably also a good chance to get rid of some 'features' of your app, which are hardly ever used...
Comment: Yes You are right. I am also thinking the same thing. Thanks for making my decision strong.
Comment: it might be a tough sell for your boss - just don't tell :) -- in the end s/he will be happy
Comment: Thanks Man. My Boss know everything and Even I explained these terms to Client as well. Client is also ready for this.

Upgrade Rails App From 1.2.3 to 3.1.0?


Compute $\sum_{n=1}^{\infty}\left(\frac{\sin(n)}{n}\right)^2$

Question: How would you evaluate
$$\sum_{n=1}^{\infty}\left(\frac{\sin(n)}{n}\right)^2$$
Wolfram|Alpha says it equals $\;\pi/2-1/2.\;$ If the solution is complicated, ... I can handle complicated.
Comment: Does this answer your question? [Evaluating $\sum_{k=1}^{\infty}\left(\frac{\sin(tk)}{k}\right)^2$](https://math.stackexchange.com/questions/3611785/evaluating-sum-k-1-infty-left-frac-sintkk-right2)
Comment: I disagree that the proposed duplicate https://math.stackexchange.com/questions/3611785/evaluating-sum-k-1-infty-left-frac-sintkk-right2 is in fact a duplicate. In that question, the OP specifically requested a solution using the Poisson summation formula, so the answers use that method. But there are other approaches, including my answer below which uses Parserval's theorem (and which would therefore be inappropriate as an answer to the proposed duplicate) but which is in fact easier because computing Fourier coefficients for a rectangular pulse is easier than for a triangular pulse.
Comment: Some context would help. Do you know about Fourier series and [Parseval's theorem](https://en.wikipedia.org/wiki/Parseval%27s_theorem#Statement_of_Parseval's_theorem)?
Answer: $\displaystyle\sum_{n=1}^∞ \dfrac{\sin(nx)}{n} =\frac{1}{2i} \sum_{n=1}^∞ \dfrac{(e^{ix})^n}{n}-\dfrac{(e^{-ix})^n}{n}=-\frac{1}{2i}({\log(1-e^{ix})-\log(1-e^{-ix})})$
$= \displaystyle \dfrac{1}{2i} \log\left(\frac{(1-e^{-ix})}{(1-e^{ix})}\right)= \dfrac{1}{2i} \log(-e^{-ix})= \dfrac{\log(e^{iπ})-\log(e^{ix})}{2i} =\dfrac{π-x}{2}. $
Now $\displaystyle\int_0^x \sum_{n=1}^∞\dfrac{ \sin(nx)}{n}dx = \int_0^x \dfrac{π-x}{2}dx $
$\implies \displaystyle -\sum_{n=1}^∞ \left(\dfrac{\cos(nx)}{n^2} -\dfrac{\cos(0)}{n^2}\right)= \dfrac{2πx-x^2}{4}$
$\implies \displaystyle\sum_{n=1}^∞ \dfrac{2\sin^2(\frac{nx}{2})}{n^2} = \dfrac{2πx-x^2}{4} .$
Put $x=2$ the answer will be $\displaystyle\sum_{n=1}^∞ \dfrac{\sin^2(n)}{n^2} =\dfrac{π-1}{2} $.
Edit
In this way we can also solve Basel problem.
$\displaystyle\sum_{n=1}^∞ \dfrac{\sin^2(\frac{nπ}{2})}{n^2} = \dfrac{\frac{π}{2}(π-\frac{π}{2})}{2} = \dfrac{π^2}{8} $
Which means $\displaystyle\dfrac{1}{1^2} +\dfrac{1}{3^2} +\dfrac{1}{5^2} +...= \dfrac{π^2}{8} \implies \dfrac{3\zeta(2)}{4} =\dfrac{π^2}{8} \implies \zeta(2)=\dfrac{π^2}{6}$
Comment: If your answer is different from those found in the duplicate, it is advised to answer that question instead. If a rather similar anwer is given for the duplicate, do not answer at all.
Comment: @Gary I disagree that the proposed duplicate https://math.stackexchange.com/questions/3611785/evaluating-sum-k-1-infty-left-frac-sintkk-right2 is in fact a duplicate. In that question, the OP specifically requested a solution using the Poisson summation formula, so the existing answers use that method and any future answers to that question should do the same.
Answer: The proposed duplicate Evaluating $\sum_{k=1}^{\infty}\left(\frac{\sin(tk)}{k}\right)^2$ does this the hard way, using the Poisson summation formula, which requires finding the Fourier series for a triangular function. (The OP of that question explicitly requested a Poisson summation formula solution.)
It's easier to compute the Fourier series for a rectangular function and use Parseval's theorem, so my solution uses that approach.
Let $f$ be the $2\pi$-periodic function defined as follows:
$$f(x) = \begin{cases} 1 & \text{if }|x| < 1 \\
0 & \text{if }1 \leq |x| \leq \pi \\
\end{cases}$$
Then $f$ has a Fourier series representation
$$f(x) = \sum_{n=-\infty}^{\infty}a_n e^{inx}$$
where
$$a_n = \frac{1}{2\pi}\int_{-\pi}^{\pi}f(x)e^{-inx}$$
for each $n \in \mathbb Z$. When $n=0$, this reduces to
$$\begin{aligned}
a_n &= \frac{1}{2\pi}\int_{-\pi}^{\pi}f(x)\ dx \\
&= \frac{1}{2\pi}\int_{-1}^{1}\ dx \\
&= \frac{1}{\pi}
\end{aligned}$$
For $n \neq 0$ we have
$$\begin{aligned}
a_n &= \frac{1}{2\pi}\int_{-\pi}^{\pi}f(x)e^{-inx}\ dx \\
&= \frac{1}{2\pi}\int_{-1}^{1}e^{-inx}\ dx \\
&= \frac{1}{-i2\pi n}(e^{-in} - e^{in}) \\
&= \frac{\sin(n)}{\pi n}
\end{aligned}$$
Now we can apply Parseval's theorem, which says that if $a_n$ are the Fourier coefficients of $f$ and $b_n$ are the Fourier coefficients of $g$, then
$$\frac{1}{2\pi}\int_{-\pi}^{\pi}f(x)\overline g(x)\ dx = \sum_{n=-\infty}^{\infty}a_n \overline b_n,$$
where the bar denotes complex conjugation. (In words, the inner product of $f$ and $g$ equals the inner product of their Fourier coefficient sequences.) In particular, for the special case $f=g$, Parseval's theorem gives us
$$\frac{1}{2\pi}\int_{-\pi}^{\pi}|f(x)|^2\ dx = \sum_{n=-\infty}^{\infty}|a_n|^2$$
For our function $f(x)$, we have $|f(x)|^2 = 1$ for $|x| < 1$ and $|f(x)|^2 = 0$ otherwise, so the integral on the LHS becomes
$$\frac{1}{2\pi}\int_{-1}^{1}\ dx = \frac{1}{\pi}$$
And, since our Fourier coefficients are real and even ($a_n = a_{-n}$), the sum on the RHS becomes
$$a_0^2 + 2\sum_{n=1}^{\infty}a_n^2 =
\frac{1}{\pi^2} + \frac{2}{\pi^2}\sum_{n=1}^{\infty}\left(\frac{\sin(n)}{n}\right)^2 = \frac{1}{\pi^2} + \frac{2}{\pi^2} S$$
where $S$ is your desired sum. Summarizing:
$$\frac{1}{\pi} = \frac{1}{\pi^2} + \frac{2}{\pi^2} S$$
Multiplying by $\pi^2$ gives us
$$\pi = 1 + 2S$$
and therefore $\displaystyle S = \frac{\pi - 1}{2}$ as desired.


Regex to strip HTML tags

Question: I have this HTML input:

some text

 another text

I'd like to use regex to remove the HTML tags so that the output is:
some text
another text

Can anyone suggest how to do this with regex?
Comment: Don't try to parse HTML with regular expressions. It will only end in tears.
Comment: Please read this answer to a similar question: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
Comment: Further Reading: http://stackoverflow.com/questions/832620/stripping-html-tags-in-java
Answer: Since you asked, here's a quick and dirty solution:
String stripped = input.replaceAll("<[^>]*>", "");

(Ideone.com demo)
Using regexps to deal with HTML is a pretty bad idea though. The above hack won't deal with stuff like

<tag attribute=">">Hello</tag>

etc.
A better approach would be to use for instance Jsoup. To remove all tags from a string, you can for instance do Jsoup.parse(html).text().
Comment: The `>` is allowed as a literal character in quoted attribute values.
Comment: Ok, if it was something as simple, as stripping tags in uncomplicated HTML, I may have chosen to go with a regexp. In your scenario, I believe that you're better off with a proper parser.
Comment: May I suggest input.replaceAll("<[^>]+>","");
Comment: Before this tag I hade Head , tilte all those things are there by using above snippet I am getting head,titile text also.i need only this part of text only I tried with
Comment: private static final Pattern BetweenTags = Pattern.compile("([^<]+?)+");
Answer: Use a HTML parser. Here's a Jsoup example.
String input = "
some text
\n
another text
";
String stripped = Jsoup.parse(input).text();
System.out.println(stripped);

Result:
some text another text
Or if you want to preserve newlines:
String input = "
some text
\n
another text
";
for (String line : input.split("\n")) {
    String stripped = Jsoup.parse(line).text();
    System.out.println(stripped);
}

Result:

some text
another text

Jsoup offers more advantages as well. You could easily extract specific parts of the HTML document using the select() method which accepts jQuery-like CSS selectors. It only requires the document to be semantically well-formed. The presence of the since 1998 deprecated  tag is already not a very good indication, but if you know the HTML structure in depth detail beforehand, it'll still be doable.
See also:

Pros and cons of leading HTML parsers in Java
Comment: Just a note that using Jsoup actually does not only strips away html tags, it adds spaces as well to separate elements. The text letter count will be greater than that of the html text e.g. written in tinymce editor if that is why you need to strip away the tags.
Answer: You can go with HTML parser called Jericho Html parser.
you can download it from here - http://jericho.htmlparser.net/docs/index.html
Jericho HTML Parser  is a java library allowing analysis and manipulation of parts of an HTML document, including server-side tags, while reproducing verbatim any unrecognized or invalid HTML. It also provides high-level HTML form manipulation functions.
The presence of badly formatted HTML does not interfere with the parsing
Comment: Jsoup expects well formed HTML so it's NOT better than Jericho when you are dealing with arbitrary HTML.
Answer: Starting from aioobe's code, I tried something more daring:
String input = "
some text
\n
another text
";
String stripped = input.replaceAll("</?(font|p){1}.*?/?>", "");
System.out.println(stripped);

The code to strip every HTML tag would look like this:
public class HtmlSanitizer {

    private static String pattern;

    private final static String [] tagsTab = {"!doctype","a","abbr","acronym","address","applet","area","article","aside","audio","b","base","basefont","bdi","bdo","bgsound","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dir","div","dl","dt","element","em","embed","fieldset","figcaption","figure","font","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","isindex","kbd","keygen","label","legend","li","link","listing","main","map","mark","marquee","menu","menuitem","meta","meter","nav","nobr","noframes","noscript","object","ol","optgroup","option","output","p","param","plaintext","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","tt","u","ul","var","video","wbr","xmp"};

    static {
        StringBuffer tags = new StringBuffer();
        for (int i=0;i<tagsTab.length;i++) {
            tags.append(tagsTab[i].toLowerCase()).append('|').append(tagsTab[i].toUpperCase());
            if (i<tagsTab.length-1) {
                tags.append('|');
            }
        }
        pattern = "</?("+tags.toString()+"){1}.*?/?>";
    }

    public static String sanitize(String input) {
        return input.replaceAll(pattern, "");
    }

    public final static void main(String[] args) {
        System.out.println(HtmlSanitizer.pattern);

        System.out.println(HtmlSanitizer.sanitize("
some text

another text
"));
    }

}

I wrote this in order to be Java 1.4 compliant, for some sad reasons, so feel free to use for each and StringBuilder...
Advantages:

You can generate lists of tags you want to strip, which means you can keep those you want
You avoid stripping stuff that isn't an HTML tag
You keep the whitespaces

Drawbacks:

You have to list all HTML tags you want to strip from your string. Which can be a lot, for example if you want to strip everything.

If you see any other drawbacks, I would really be glad to know them.
Answer: If you use Jericho, then you just have to use something like this:
public String extractAllText(String htmlText){
    Source source = new Source(htmlText);
    return source.getTextExtractor().toString();
}

Of course you can do the same even with an Element:
for (Element link : links) {
  System.out.println(link.getTextExtractor().toString());
}

Regex to strip HTML tags


Show that the map is an injective linear transformation and determine a basis of the image

Question: Hi im having trouble with this homework question:
"For any polynomial function $f : R → R$ of degree at most $n$, the
function $I(f) : R → R$,$s → \int_0^s f(u) du$, is a polynomial function of degree at most $n + 1$. Show that the map $I : P_n → P_{n+1}, f→ I(f)$, is an injective linear transformation and determine a basis of the image of $I$."
I've managed to show that it is a linear transformation by checking the requirements for a linear transformation but I don't know how to show that the transformation would be injective. Usually what I would do to show a transformation is injective is I would be given a matrix and then show that the null space just consists of the zero vector by using row operations, then to find a basis for the image I would perform column operations on the same matrix.
Any help with this would be very much appreciated.
Answer: We can try this representation
$$
p \in P_n \\
p(x) = \sum_{k=0}^n a_k x^k
\leftrightarrow (a_0, \dotsc, a_n)^T \in \mathbb{R}^{n+1}
$$
Then
\begin{align}
I(p)
&= s\to \int\limits_0^s \sum_{k=0}^n a_k x^k dx \\
&= s\to \sum_{k=0}^n a_k \left[\frac{1}{k+1} x^{k+1}\right]_{x=0}^{x=s} \\
&= s\to \sum_{k=0}^n \frac{a_k}{k+1} s^{k+1} \in P_{n+1} \\
&\leftrightarrow
\left( 0, a_0, \frac{a_1}{2}, \dotsc, \frac{a_n}{n+1} \right)^T
\in \mathbb{R}^{n+2}
\end{align}
So we can write $I$ as matrix $A$ acting on the coefficient vectors $a$:
$$
A =
\begin{pmatrix}
0 & 0 & 0 & \dotsb & 0 \\
1 & 0 & 0 & & 0 & \\
0 & 1/2 & 0 & & 0 & \\
0 & 0 & 1/3 & & 0  \\
\vdots & & & \ddots & \vdots \\
0 & 0 & 0 & \dotsb & 1/(n+1)
\end{pmatrix}
\in \mathbb{R}^{(n+2)\times (n+1)}
$$
Answer: A more direct approach that doesn't require computing a matrix for $f$: The kernel of $I$ consists of polynomials $f$ such that $\int_0^sf(u)\,du=0$. The value of this integral is $F(s)-F(0)$ for some polynomial function $F$, and for this to vanish for all $s\in\mathbb R$, $F$ must be constant. The derivative of a constant polynomial is $0$, therefore the kernel of $I$ is trivial.


How can I check if multiple array keys exist?

Question: Is there a simpler, smarter and clearer way to write this?
if (array_key_exists("name", $array) AND array_key_exists("age", $array) AND array_key_exists("size", $array) AND array_key_exists("gender", $array) {
    echo "Keys exist!";
}

Comment: Probably go for `in_array()` with `array_keys()`
Comment: http://stackoverflow.com/questions/13169588/how-to-check-if-multiple-array-keys-exists
Comment: `$keys = ['name','age','size','gender']; $existCount = count(array_intersect_key(array_flip($keys), $array)) == count($keys);`
Comment: Hmm, all the answers are even longer code than mine. I hoped there is a more simpler solution with less code
Answer: Use simply isset(), a language construct.
Language constructs are much more faster than functions.
<?php
$findKeys = array('name', 'age', 'size', 'gender');
if (! empty($findKeys) && ! empty($array)) {
    foreach ($findKeys as $findKey) {
        if (isset($array[$findKey])) {
            echo 'Keys exist!';
        }
    }
}

Explanation:
1) Create an array of 4 keys you need to find.
2) Loop over this array and use isset() to find out if the key (element) exists.
Answer: You can do it like this:
<?php

$array = array(
    'index1'=>'value1',
    'index2'=>'value2',
    'index3'=>'value3'
);

$indexesToSearch = array('index1', 'index2');

if(count(array_intersect(array_keys($array), $indexesToSearch)) == count($indexesToSearch))
{
    // ... do something
}

Answer: use can also use this way..
<?php
function array_keys_exist($keys, $array){
    foreach($keys as $key){
        if(!isset($array[$key]))return false;
    }
    return true;
}
?>


How to unmarshall config entry header with Go Viper package?

Question: I have a configuration file that looks like the following:
apps:
    customer1:
      upload_path: "/opt/uploads/customer1"
      local_path: "/opt/ready/customer1"
      bucket: "b1"
    customer2:
      upload_path: /opt/uploads/customer2
      local_path: opt/ready/customer2,
      bucket: "b2"

I am using Viper to load and read the configuration file.
I am unmarshalling the above config and mapping it to the following struct:
type AppConfig struct {
UploadPath string `mapstructure:"upload_path"`
LocalPath  string `mapstructure:"local_path"`
Bucket     string `mapstructure:"bucket"`
}

appconfigs []*AppConfig

viper.SetConfigName(configName)
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.UnmarshalKey("apps", &appconfigs)

The problem I am trying to solve is getting the entry header (ie customer1 and customer2) without having to have a redundant field in my config file and ending up with:
apps:
    customer1:
      name: customer1
      upload_path: "/opt/uploads/customer1"
      local_path: "/opt/ready/customer1"
      bucket: "b1"

Answer: The configuration can be unmarshaled to a map:
var appconfigs map[string]*AppConfig

viper.UnmarshalKey("apps", &appconfigs)

You can get the names from the map key.
Comment: Thank you, the answer was right in my face and I did not see it.  I just had to grab the actual keys from the map.


scrapy splash to solve recaptcha

Question: I am using scrapy+splash to web scrape,I have a "anti recaptcha" third party service that can solve the recaptcha, the way the recaptcha solver works is that  they an array of what I should click on (correct images). How can I click on the pictures using scrapy+splash ?
Answer: You need to learn Splash scripting.

scrapy splash to solve recaptcha


Chamar um executável sem ser pelo Process em c#

Question: Existe alguma forma de chamar um executável sem ser pelo processo?
Preciso de alguma coisa que não use o código abaixo para chamar um executável pois quando finalizo um processo de uma aplicação que não é nativa do Windows, não consigo chamá-la novamente com o comando:
foreach (Process pr in Process.GetProcessesByName(nomeExecutavel))
        {
            if (!pr.HasExited)
    pr.Start();
        }

Obs.: É um console Application em C#
Comment: Podes explicar melhor o que pretendes fazer?
Answer: Você pode executar uma aplicação pelo caminho do executável:
Process.Start("c:\\caminho do executável.exe");

Comment: Preciso chamar uma aplicação WPF sem utilizar o Process.Start dentro de um console application. Dessa forma não funciona também
Comment: O que acontece quando você chama o executável da aplicação WPF usando o `Process.Start`? Dá exceção?
Comment: Ficou um pouco lento com o Process.Start mas funcionou.


How to disable the click on an icon after one click?

Question: After clicking on the icon with ids (#prevleft and #nextright) , an ajax function is called. During the time ajax function loads a new table, I want to disable the icon click.
HTML Code:
hrHTML='
' +"Weekly Utilization"+'

';

The table row is appended dynamically as shown above. Want to disable #prevleft and #nextright after one click.

The following line doesn't work:

$('#prevleft').prop("disabled", true);

I am new to coding, so all help is appreciated.
Comment: Will the  be replace by ajax function?
Comment: How about `$('#prevleft,#nextright').off('click')` ?
Comment: @VietHuongBui no, onclick of the icon inside  an ajax function is being called.
Comment: Are you trying to disable an element that exists in `document` before `$.ajax()` is called?
Comment: @guest271314 After ajax is called, a new table is loaded with a new #prevleft icon. so i dont think it already exists in document. i do not want the users to click the button multiple times while the ajax is loading the table, so i want to disable the click.
Comment: Disable the click at an element other than `"#prevleft, #nextright"`? Are you trying to disable `click` event at element which calls `$.ajax()` until `$.ajax()` completes?
Answer: Just check with the version of the jquery your using, I hope that your using jquery 1.5 or below
For jQuery 1.6+
Use can use .prop() function:
$('#prevleft').prop("disabled", true);
$("#nextright").prop("disabled", true);

For jQuery 1.5 and below
You need to use .attr() and disable the icon
$("#prevleft").attr('disabled','disabled');
$("#nextright").attr('disabled','disabled');

and for re enable the icon (remove attribute entirely):
$("#nextright").removeAttr('disabled');
$("#prevleft").removeAttr('disabled');

Assuming you have an event handler on a icon, in any version of jQuery you can use the following property to check if your icon is enabled or not
if (this.disabled){
   // your logic here
}

Answer: Bind simple a click event when clicked on prevleft and prevright id icon.
$("body").on("click","#prevleft ,#prevright",function(){
var _this = $(this);
 $(this).prop("disabled","true");
 // ajax call code right here

  // on ajax success function right this line
    success: function(resp){
      _this.prop("disabled","false");
    }});

})

Answer: You have attached an event listener to one or more elements that do not yet exist in document. You can use event delegation, or jQuery() function to attach event to element when created.
Pass html string to jQuery(), use .find() to get "#prevleft", #nextright selectors, attach click event using .one(), append jQuery() object to document
$(elementWherehrHTMLIsAppended)
.append(
  $(hrHTML)
  .find("#prevleft, #nextright")
  .one("click", function() {
    $(this).prop("disabled", true)
  }).end()
);

Comment: This worked for me. I added the line `$(this).prop("disabled", false)` in the ajax success to re-enable the click. Thanks!!
Answer: You can add a class to the element and check for the class when the user clicks.
For example:
$('#prevleft').click(function(){
    if($(this).hasClass('clicked')){
         // do nothing or return false
     }else{
          // ajax call
          // on a successful call you can add the class using:
          $('#prevleft').addClass('clicked');
     }
});

Let me know if this is what you were asking for. This also gives you the ability to add an alert or do something if the button was already clicked.
Hope this helped!
Answer: Try my code, this event only called when icon hasn't class 'clicked', in the first call we will add 'clicked' class to prevent this event from this time.
$('#prevleft:not(.clicked), #nextright:not(.clicked)').on('click', function(){
    $(this).addClass('clicked');
});

Hope this can help you!


postgreSQL kubernetes helm installation - reading from slaves

Question: I've gone ahead and used the postgres helm release to install a small "cluster" on an on premise kubernetes cluster.
the installation went smoothly - we have an master instance and two slaves to which the data is being replicated (the single restart seen below is OK as it was done manually for testing).
prod-postgres-postgresql-master-0   2/2       Running   0          15h
prod-postgres-postgresql-slave-0    1/1       Running   0          16h
prod-postgres-postgresql-slave-1    1/1       Running   1          9d

These pods came with their respective services (I am using a NodePort since there is no cloud provider to add an external IP to a LoadBalancer):
prod-postgres-postgresql            NodePort    10.96.119.67    <none>        5432:31920/TCP   9d
prod-postgres-postgresql-headless   ClusterIP   None            <none>        5432/TCP         9d
prod-postgres-postgresql-metrics    ClusterIP   10.106.163.49   <none>        9187/TCP         9d
prod-postgres-postgresql-read       ClusterIP   10.97.58.56     <none>        5432/TCP         9d

The values used for the installation are the same as the production values on the repo with the small change of password and storage-class (for which I manually provided the needed PVs)
My question:
How do I now use this DB deployment for reading from all postgres nodes?
I understand that:

just the master writes
this helm chart does not offer any form of failover once a master is dead (say the pod is in crash-backoff for some reason).
the master has its own service: prod-postgres-postgresql
the slaves have their own service: prod-postgres-postgresql-read

Since the services are different, how can I tell my app it's allowed to read from more than just the master?
If this is not supported then what is the "point" of this helm chart? Along with the lack of failover the slaves seem pointless.
Answer: To be honest I too have this question. The documentation doesn't clearly state how to handle/enable this. The only solution I've been able to come up with, which I don't think is optimal nor do I know if it's the "right" approach is to, on the app side of things (not k8s), connect to the right K8s service (master (db-postgresql) for read/writes & slaves (db-postgresql-read) for reads-only) based off the type of DB operation intended. Would certainly like more guidance here too. I've been looking into Stolon as an alternative.


Maximal $k$-split torus and the Weyl group. Why is this a root system?

Question: Let $G$ be semisimple algebraic group over a field $k$.  Let $T$ be a maximal torus of $G$ which is defined over $k$, and let $K$ be a finite Galois extension of $k$ over which $T$ is split.  Let $\Gamma = \textrm{Gal}(K/k)$. Then $\Gamma$ acts on $G(K)$, as well as on the group $X$ of characters of $T$: specifically, if $\sigma \in \Gamma, \chi \in X$, then $\chi^{\sigma}$ is the unique character of $X$ satisfying $\chi^{\sigma}(t) = \sigma \chi(\sigma^{-1} t)$ for all $t \in T(K)$.
Let $V = \mathbb{Q} \otimes X$, and $\Phi \subseteq X$ the set of roots of $T$ in $G$.  Then $(V,\Phi)$ is root system.  Let $W$ be its Weyl group.  Let
$$X_0 = \{ \chi \in X : \sum\limits_{\sigma \in \Gamma} \chi^{\sigma}  = 0\}$$  $$V_0 = \mathbb{Q} \otimes X_0$$ $$A = \bigcap\limits_{\chi \in X_0} \textrm{Ker } \chi$$
Then $A$ is connected and defined over $k$, and is the largest subtorus of $T$ which is $k$-split.  Let $\Phi_0 = \Phi \cap X_0$, and let $W_0$ be the subgroup of $W$ generated by all reflections $w_{\alpha}$ with $\alpha \in \Phi_0$.  Then $W_0$ stabilizes $X_0$ and $\Phi_0$, and hence restricts to a group of automorphisms of $V_0$.

Proposition: $(\Phi_0,V_0)$ is a root system with Weyl group $W_0$.

This is what I am having trouble seeing.  The only nonobvious thing is why $\Phi_0$ spans $V_0$.  All we have to go on is that $\Phi$ spans $V$ (since $G$ is semisimple).  I've been trying to prove this for awhile with no success.  If $\chi \in X_0$, we can write
$$\chi  = c_1\alpha_1 + \cdots + c_n\alpha_n$$ for some $\alpha_i \in \Phi$ and $c_i \in \mathbb{Q}$.  Let's say that only $\alpha_1, ... , \alpha_t$ lie in $\Phi_0$.  Applying $\sigma$ and summing, we get that
$$ 0 =\sum\limits_{i=t+1}^n c_i \sum\limits_{\sigma} \alpha_i^{\sigma}$$
Answer: The trouble comes from the fact that the proposition is not true: In general, $\Phi_0 := \Phi \cap X_0$ does not span $X_0$ (or, a fortiori, $V_0$).
For example, in quasi-split forms, $\Phi_0$ is empty, whereas $X_0$ is not just $\lbrace 0 \rbrace$. E.g. take a quasi-split form of $\mathfrak{sl}_3$ (root system of type $A_2$), where the Galois action switches the two basis roots $\alpha_1$ and $\alpha_2$. Then $V_0$ is the one-dimensional subspace $\mathbb{Q} \cdot (\alpha_1-\alpha_2)$, which however contains no roots.
As another example, over $\mathbb{R}$ as well as over $p$-adic fields, there exists a form of type $A_3$ with quadratic splitting field such that the generator $\sigma$ of the Galois group operates via
$\alpha_1 \mapsto \alpha_2+\alpha_3$
$\alpha_2 \mapsto -\alpha_2$
$\alpha_3 \mapsto \alpha_1+\alpha_2$.
on the three basis roots $\alpha_1, \alpha_2, \alpha_3$. (Over the reals, it's the form with Lie algebra called $\mathfrak{su}_{1,3}$ here; likewise, the group would be the (projective) special unitary group w.r.t. to a hermitian form of index 1 on $\mathbb{C}^4$.)
Then $V_0$ is the two-dimensional space spanned by $\alpha_2$ and $\alpha_1-\alpha_2-\alpha_3$, but $\Phi_0$ just consists of $\pm \alpha_2$.

What is true is that $\Phi_0$ is a root system in the subspace it spans (if $\Phi_0$ is not empty): It is the root system of the "anisotropic kernel" of the form.


Convert signed float to uint8 image opencv

Question: I have an image from cv2.matchTemplate that is float range -1,1:
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)

res has values like: [[ 0.00730964 -0.00275442 -0.02477949 ... -0.16014284 -0.13686109
  -0.13015044]
I can see graycale map of pattern matching with:
cv2.imshow("Match", res)

However I want to see in colormap, using:
resC = cv2.applyColorMap(res, cv2.COLORMAP_JET)

Using this I immediately have issues like:
"cv::ColorMap only supports source images of type CV_8UC1 or CV_8UC3 in function 'operator()'"
So I try skimage convertion:
from skimage import img_as_ubyte
res = img_as_ubyte(res)

or
from skimage import exposure
res = exposure.rescale_intensity(res, out_range=(0, 255))

With them I get outputs like:
[[48 46 42 ... 14 19 20]
 [52 56 54 ... 22 28 30]
Better now, integers. However, something is wrong cause I get only (blue) monochrome colormaps, not the nice ones from cv2.COLORMAP_JET range. It seems is shifted somehow.
Any hints on how to convert from -1,1 to 0,255 properly?
Answer: why this doesn't work:
I don't think this function is doing the rescaling you are hoping for.  Consider the example from the reference manual below:
>>> image = np.array([-10, 0, 10], dtype=np.int8)
>>> rescale_intensity(image, out_range=(0, 127))
array([  0,  63, 127], dtype=int8)

It maps the minimum number in the input array to 0 and the largest number to 1.  If you don't have the exact values of -1, and 1 in your input array then using this function will not work.

what you can do instead:
I recommend writing a simple function to rescale the values from -1 to 1 into  0 to 255:
>>> image = np.random.uniform(-1,1,(3,3))
>>> scaled = (image + 1)*255/2.
>>> image
array([[ 0.59057256,  0.01683666, -0.24498247],
       [-0.25144806, -0.32312655, -0.02319944],
       [ 0.50878506, -0.04102033,  0.3094886 ]])
>>> scaled
array([[ 202.79800129,  129.64667417,   96.26473544],
       [  95.44037187,   86.3013643 ,  124.54207199],
       [ 192.37009459,  122.26990741,  166.95979601]])

How it works:

image + 1 shifts all numbers to the [0,2] range
(image +1)/2. scales all numbers to [0,1]
(image +1)*255/2. scales the numbers from [0,1] to [0,255]
Comment: Great. Worked very fine, Thank you!
Comment: I only added
"scaled = np.uint8(scaled)"
to truncate decimals. So that I can use standard opencv image manipulations.


vectorize numpy array multiplication

Question: a = np.array([[20, 12,  6],
              [12, 24, 18],
              [ 0, 14, 30]])
b = np.array([1,0.5])
c = np.array([b ** i for i in range(0, 3)][::-1])
array([[1.  , 0.25],
       [1.  , 0.5 ],
       [1.  , 1.  ]])

using the second column in c, I want to get
[[20*0.25, 12*0.25, 6*0.25],
 [12*0.5,  24*0.5,  18*0.5],
 [ 0*1,    14*1,    30*1]
].sum(axis=0)

I want to do this for each column in c.
For 1-d array of c, I can do (a * c[:,None]).sum(axis=0). How can I vectorize the multiplication here without using loop?
Comment: `a.T @ c` or `c.T @ a`
Answer: You are looking for np.eisum
np.einsum('ij,ik', a, c)

array([[32. , 11. ],
       [50. , 29. ],
       [54. , 40.5]])

Note that you could use broadcasting although not as efficient as eisum:
(a[:,None] * c[:, :,None]).sum(0)

array([[32. , 50. , 54. ],
       [11. , 29. , 40.5]])

vectorize numpy array multiplication


MySQL binlog reading

Question: I installed MySQL 5.5 on Windows 7 I did it as a general install. All my logs are stored under the C:\ProgramData\MySQL\MySQL Server 5.5\data\mysql-bin.00057 for example
when I try to run mysqlbinlog mysqlbin.000057 it gives me error 2 file not found
I have even tried mysqlbinlog C:\ProgramData\MySQL\MySQL Server 5.5\data\mysql-bin.000057 it also says it can't find the file.
Just wondering how I can use the binlog to read these files using mysqlbinlog
Comment: What if you cd to directory first? cd C:\ProgramData\MySQL\MySQL Server 5.5\data
Answer: MySQL server settings
server-id   = 100
log_bin = /var/log/mysql/mysql-bin.log
expire_logs_days = 12
max_binlog_size = 120M
binlog-format = row // very very important for read, update and delete

Source
https://github.com/aliozyildirim/mysql-binlog-reader-and-cdc/

Comment: this code records the log from the log database to the cdc database

MySQL binlog reading


Why Is My Music Waveforms Exported From LMMS So High?

Question: The height of music waveforms exported from LMMS are very high and I'm afraid it might lead to clipping or unbalanced volume when accompanied with video. The track in LMMS which is a 1-min loop was created using the a Bass preset (Bass 2) from ZynAddSubFX presets, along with a kick and a hihat. The only FX addon I applied on it is Calf Compressor LADSPA.
On the other hand, the waveforms of the audio recorded with Mac microphone is half way tall. The difference between waveforms is clearly visible in my video editor. Here's screenshots of both:
Music exported from LMMS:

Audio recorded by Mac:

I might be able to lower the waveforms, but I am looking for a way to do that in LMMS. So, in short, why does this happen and how can I prevent it?
By the way, the exported track does not sound much peaky and sounds OK, but why do the waveforms say otherwise?
Take a listen to the track:
https://vocaroo.com/i/s0xlaW5jHjNT
Comment: @leftaroundabout please see the updated post.
Answer: Without having listened to your track: it's not surprising at all it looks this way if this is just a bass-and-drums loop with not changes. How could it look anything but constant-peaks-amplitude, if it is a loop that literally repeats in exactly the same way?
The fact that this constant amplitude is actually 0 dB (i.e. the maximum possible) is just a matter of normalisation. It's standard practice to set the level as high as possible without clipping when exporting audio. Either the compressor plugin is set to normalise the output, or LMMS does that in the bouncing/exporting action.
Even if it wasn't a loop: a compressor has essentially the purpose to bring any audio closer to constant level. This is very often a desired thing, in particular for something like a video soundtrack: if there's lots of dynamic fluctuation, it's much harder to mix it together without the peaks disrupting the voice-over or else the music getting feeble in the background. Of course you will need to properly adjust the mix levels for the video cut, but that needs to be done either way. Your loud music track will probably need to have quite a low mix setting in the video, but that's not a pad thing per se.
Also in music production, especially pop, mastering engineers will often apply so much compression that the peak level across the track is almost constant 0 dB. This way the overall track will sound as loud as physically possible even on small speakers. The downside is that the music isn't as dynamic anymore. This has been a big debate termed the loudness war. But that doesn't really apply for you if you really have just a loop: there are no dynamics in the first place, so also no issue removing them with a compressor!
Bottom line: don't worry about this. You could certainly reduce the output level in LMMS, but if the track doesn't actually sound bad to you then there's no real reason. You should make sure you've actually checked it on studio monitors as well as headphones, to make sure it isn't also clipped after all.
Answer:
the exported track does not sound much peaky and sounds OK, but why do the waveforms say otherwise?

Each software can render waveforms differently, so I don't think judging audio level by inspection of the waveform is an accurate idea.
For example, in Reaper you can alter the size of the waveform. You can make it look as big or small as you want. Of course, all the levels are relative and are shown ok, but depending on your editing needs you might want them displayed bigger or smaller.
Measure your waveforms, watch the vumeter. Don't stay just with the inspection of the waveform.


Is there a stable way to fill a filefield/imagefield via bulk upload in D7

Question: OK, here's the deal. I've implemented image gallery nodes in D7 the straight-forward way, i.e. create node type 'gallery' and add an imagefield with unbounded number of values. Nice markup via Views/EVA, done.
Now, to make the image upload convenient, I tried the following ways and got the respective results:
Multiupload Filefield Widget: The uplaod goes through, images appear on server side, but php runs out of memory while computing the ajax response for the upload.
Plupload widget: Upload works, but side crashes on save. I get lot's of visible json instead of the saved side.
Plupload via Fielfield Resources: Upload goes through, after that no visible response. On save, I get a long list of copy/rename error messages above the actual side.
The problems are present for pure file fields, on a otherwise pure D7 installation, so image processing is off the table as well as memory polluting modules (up to the ones mentioned above, appearently).
So the question is, why is it so memory consuming to compute a not so lengthy ajax response? The side shall collect several galleries containing each around 200-400 pics, so a nice way to bulk upload those jpgs would be great.
Answer: For completeness, the only stable way I found (and it's still not perfect, though) is to use plupload in combination with block_upload to get a PLUpload widget on the content site once it is created. It still is not the perfect workflow, but it currently allows me to dump 100s of photos/files into one filefield. Using PLUpload during node creation didn't work, btw.


Solve the equation $2^{x^2 + x} + \log_2x=2^{x+1}$

Question:
Solve the equation $2^{x^2 + x} + \log_2x=2^{x+1}$ where $x$ is real.

I tried to use derivatives, without success.
It's obvious that $x=1$ is solution.
Also, if $x \gt 1$ then $2^{x^2 + x} \gt 2^{x+1}$ and $\log_2x \gt 0$ therefore the equation has no solutions $x \gt 1$.
Comment: Hint: try some easy test values for x
Comment: @WilliamStagner Probably x=1 is the unique solution
Comment: @egreg: Thanks; that was a misstep.
Answer: Similarly, for $0 <x<1$, we have $2^{x^2+x} <2^{x+1}$ and $\log_2{x} <0$
So, $x=1$ as for $\log_2{x}$ to be defined we must $x>0$
Comment: Yes, I've seen this also. I was about to write about it.
Comment: @EugenCovaci Sorry, but you didn't post it, so I answered.
Comment: It's OK, your answer solve the equation.
Answer: It's clear that $x=1$ is a solution. Let's look at two cases: $x>1$ and $x<1$.
If $x>1$, then $\log_2x>0$ and $x^2+x>x+1$, which implies that $2^{x^2+x}>2^{x+1}$. It's impossible.
If $0<x<1$, then $\log_2x<0$ and $x^2+x<x+1$, which implies that $2^{x^2+x}>2^{x+1}$. It's impossible.
In summary, we only have one solution $x=1$.


libsvm data format

Question: I'm using the libsvm (http://www.csie.ntu.edu.tw/~cjlin/libsvm/) tool for support vector classification. However, I'm confused about the format of the input data.
From the README:

The format of training and testing data file is:
 <index1>:<value1> <index2>:<value2> ...
.
.
.

Each line contains an instance and is ended by a '\n' character.  For
  classification,  is an integer indicating the class label
  (multi-class is supported). For regression,  is the target
  value which can be any real number. For one-class SVM, it's not used
  so can be any number.  The pair <index>:<value> gives a feature
  (attribute) value: <index> is an integer starting from 1 and <value>
  is a real number. The only exception is the precomputed kernel, where
  <index> starts from 0; see the section of precomputed kernels. Indices
  must be in ASCENDING order. Labels in the testing file are only used
  to calculate accuracy or errors. If they are unknown, just fill the
  first column with any numbers.

I have the following questions:

What is the use of the <index>? What purpose does it serve?
Is there a correspondence between the same index values of different data instances?
What if I miss/skip an index in between ?

I ask because the datafile *heart_scale* which is included in the package for libsvm, on line 12, the index starts from 2. Is the <value> for index 1 taken as unknown/missing?
Note: the tools/checkdata.py tool provided with the package says that the *heart_scale* file is correct.
Answer: This link should help:
http://www.csie.ntu.edu.tw/~cjlin/libsvm/faq.html#/Q3:_Data_preparation
It's mentioned that the data is stored in a sparse array/matrix form. Essentially, it means only the non-zero data are stored, and any missing data is taken as holding value zero. For your questions:
a) Index merely serves as a way to distinguish between the features/parameters. In terms of a hyperspace, it's merely designating each component:
Eg: 3-D ( 3 features) indices 1,2,3 would correspond to the x,y,z coordinates.
b) The correspondence is merely mathematical, when constructing the hyper-plane, these serve as coordinates.
c) If you skip one in between, it should be assigned a default value of zero.
In short,
+1 1:0.7 2:1 3:1 translates to:
Assign to class +1, the point (0.7,1,1).
Answer: Just small and fast guide:
LibSVM format means that your document needs to be pre-processed already. You need to know how many classification classes will be used (most likely 2) and feature space.
Classification class is something like true/false; 0,1,... Here you need to transform it into integers (e.g. 0,1).
Feature space is a space for your multidimensional data. Each feauture (vector) should have its own ID (index) and its value. E.g. 1:23.2 means that feature/dimension 1 has value 23.2
 <index1>:<value1> <index2>:<value2> ... <indexN>:<valueN>
...

Comment: In the case of regression, you can replace  by  (the target value to model)

libsvm data format


How do I change decimal dot into decimal comma?

Question: I have a column containing numbers with mixed decimal separators.

I need to use "," as separator.
How do I change dot into comma?
With ThisWorkbook.Worksheets("RAW").Range("A1")
    .Value = Replace(.Value, ".", ",")
End With

The point is stored as text

Is there any way to store it as general/numeric?
I tried this
With ThisWorkbook.Worksheets("RAW").Range("A1")
    .NumberFormat = "General"
    .Value = Replace(.Value, ".", ",")
    .NumberFormat = "General"
    .Value = .Value
End With

Comment: I got error: Type Mismatch :(
Comment: yeah, sorry. just typo
Comment: @JvdV could you please look at my answer below?
Answer: A single cell could be solved quick and dirty through:
.Value = Replace(.Value, ".", ",")*1

Or:
.Value = CSng(Replace(.Value, ".", ","))

If you happen to have a range to process, you could use:
Sub Test()

With ThisWorkbook.Worksheets("RAW").Range("A1:A3")
    .Replace ".", ","
    .TextToColumns
End With

End Sub

Per column:
Sub Test()

With ThisWorkbook.Worksheets("RAW").Range("C2:D4")
    .Replace ".", ","
    For Each col In .Columns
        col.TextToColumns
    Next
End With

End Sub

Comment: ok but I get error: "Microsoft Office Excel can convert only one column at a time. The range can be many rows tall but no more than one column wide. Try again by selecting cells in one column only"

how to iterate through multiple columns?


Xcode warning: "Multiple build commands for output file"

Question: I am getting an error like this:

[WARN]Warning: Multiple build commands for output file /Developer/B/Be/build/Release-iphonesimulator/BB.app/no.png
[WARN]Warning: Multiple build commands for output file /Developer/B/Be/build/Release-iphonesimulator/BB.app/d.png
[WARN]Warning: Multiple build commands for output file /Developer/B/Be/build/Release-iphonesimulator/BB.app/n.png

But I have checked Xcode and I don't see any duplicates of such files at all. As this post in the Apple Mailing Lists say, there are no duplicates.
Answer: In the Project Navigator, select your Xcode Project file. This will show you the project settings as well as the targets in the project.  Look in the "Copy Bundle Resources" Build Phase. You should find the offending files in that list twice. Delete the duplicate reference.
Xcode is complaining that you are trying to bundle the same file with your application two times.
Comment: Worth noting that if you have a large amount of duplicated files in the Copy Bundle Resources phase, you can click 'Validate Settings' on the bottom of this page and XCode will prompt you about the duplicates and will remove all of them if you click 'Perform changes'. Hell of a lot faster than hunting for them individually.
Comment: Happens to me when I deleted some assets from the build folder (using Finder). Assets replaced with those updated with the same names and dragging them within XCode flagging "add to target" options. It seems XCode goes out of synch duplicating those entries in Copy Bundle Resources
Comment: I wanted to add one thing to this. If you end up with a ton of duplicate references somehow (like I did), you can simply click "Validate Settings" and it will automatically delete duplicate references. Much easier than manually seeking them out
Comment: I had a similar issue. This answer was the closest. The .xcodeproj/project.pbxproj file had duplicate entries even though the project showed the files only once. This was a merging issue. editing with vi did the trick :) Thanks for pointing me in the right direction :)
Comment: I had a similar issue with SpriteBuilder templates when I re-added the "Published-iOS" to the project.  Turns out it wants it to be a "folder reference" and not a group, and had added that entire folder into the "Copy Bundle Resources".  So even if the individual resource does not appear in that list, check to make sure it's not being added from a folder.
Comment: How to "Go to the target you are building"
Comment: In the Project Navigator, select your Xcode Project file. This will show you the project settings as well as the targets in the project.
Comment: @Yeti42 That button does not exist, atleast at the time of writing and in Xcode 10.1
Comment: in my situation, "Copy Bundle Resources" only had 1 file reference, however the file was also referenced in "[CP] Copy Pods Resources", removing one of those references worked for me
Comment: @Greg Hilston : See Menu: Editor / Validate Settings.. worked for me.
Answer: This is easily caused when you add git based subprojects.  Xcode isn't smart enough to ignore the .git subfolder even though you can't see it from finder, so it will get very confused that there are multiple files named "master" or "exclude", (standard git repo files).  With Xcode4, go to the project (root of the left tree) then click your app target and expand "Copy Bundle Resources", then remove all the references to .git, you shouldn't need them baked into your app anyway.
Comment: I fumbled about for a second, so this may help someone: app target -> build phases -> copy bundle resources
Comment: I had multiple files with the same name (but in different directories) in my Xcode project. Accidently one of my had both of them in the Copy Bundle Resources step, which would result in one of them being overwritten in the resulting app bundle. Just remove one of them.
Answer: Actually, the answer to this is quite simple.
In your Xcode project search for the files which raise the warning, and just delete one of them.
Xcode will show only one reference of that file in the search results, but don't stop there, go ahead and delete it. (it's better to make a backup of your project file before deleting it)
Now build the project again. The warning should disappear now.
(this answer is for a previous version of xcode)
Comment: If you continue having trouble with this, just remove all files from Xcode (don't delete them on disk). Then drag them all back in. If you still have issues after than then you actually have some resources with the same name (maybe in different folders) - find and rename/delete. Xcode output goes into a flat folder so directory structure is ignored.
Comment: But the files don't come up in XCode's groups and files pane any more. What's the deal with this?
Answer: This is not an Xcode bug, though the warning message is not helpful enough to describe the real cause.
This error message occurs when you have several files in your project that have the same name. You just have to delete or rename the files with duplicate names and the problem is solved.
Comment: Yes, this is the correct answer. And the situation can easily arrive when you have resource files, e.g. pngs with the same name but in separate dirs on your file system - during the build process they all get copied to 1 dir, namely the app bundle.
Comment: @Brynjar is there a work around to allowing images with the same name? or to prevent the images from getting bundled together?
Comment: Actually I figured out that you can create Folder References to avoid the bundling.
Comment: Here is a way to find files with duplicate name, regardless of directory `find . | grep -v \.git | rev | cut -d/ -f1 | rev | sort | uniq -c | sort` however, this did not solve my problem
Answer: This happens if you have 2 files with the same name in the project. Even though files are in groups in XCode when the project is compiled all of the files end up in the same directory. In other words if you have /group1/image.jpg and /group2/image.jpg the compiled project will only have one of the two image.jpg files.
Answer: As previously mentioned, this issue can be seen if you have multiple files with the same name, but in different groups (yellow folders) in the project navigator. In my case, this was intentional as I had multiple subdirectories each with a "preview.jpg" that I wanted copying to the app bundle:

In this situation, you need to ensure that Xcode recognises the directory reference (blue folder icon), not just the groups.
Remove the offending files and choose "Remove Reference" (so we don't delete them entirely):

Re-add them to the project by dragging them back into the project navigator. In the dialog that appears, choose "Create folder references for any added folders":

Notice that the files now have a blue folder icon in the project navigator:

If you now look under the "Copy Bundle Resources" section of the target's build phases, you will notice that there is a single entry for the entire folder, rather than entries for each item contained within the directory. The compiler will not complain about multiple build commands for those files.
Comment: Best answer! It works for me on the Xcode 12.2
Answer: This is not a bug. Xcode assists can assist you. Select the target, to the left in the project Navigator. Click on "Validate settings" at the bottom of the settings. Xcode will check the settings and removes duplicates if possible.
Answer: another version of this situation can occur when there are duplicates in the Headers build phase.
to fix this …

go to your project target
choose Build Phases
choose the Headers build phase
enter the name shown in the warning
notice the two (or more) items
find the +|- boxes in the lower left corner
select one of the items, and click the - button
Answer: In my case the issue was caused by the same name of target and folder inside a group.
Just rename conflicted file or folder to resolve the issue.
Comment: This is similar to what I had. I had 2 separate targets with the same module name.
Answer: I found a pretty easy solution for this:

Select the file causing the problem from the project navigator
Uncheck the target membership from the file inspector
Build the project
Recheck the target membership for the file again

The warning is gone! Check this image for reference.
Answer: I'm pretty sure this can be caused by an XCode 4 bug, at least in the cases that I've encountered it in.
It happens if you add multiple language dependent files to the project at the same time.  I found this out by looking through the git differences. I did nothing in the commit but add some new localized nib files.  But looking back at the difference of the project.pbxproj file it showed a bunch of new duplicate references added for files that were already in the project before.  The files it did this too seemed random to me.
I reproduced this same exact behavior multiple times.
Deleting these files from the project does not fix the problem because it only deletes the original reference and leaves the duplicates.  The only way to fix it is to go back a commit and start over, or hand edit the project file, which is a really good way to screw it up even more since it's hard to tell which duplicates to remove and you have to do it in a ton of different places.
Xcode 4 is just a huge disappointment for me.
Comment: When you localize a file you're supposed to have the same file name for each localization, except in different directories. This was indeed a bug.
Comment: Looks like this is fixed in XCode 4.2. In earlier versions you can avoid this bug by first placing the file you're about to add localizations for into it's own "Group" (virtual folder in the project). Once you're done adding localizations you can put it back where it was and delete the temp Group you created.
Comment: This is not a bug. It is due to having more than one file with the same name in your project.
Answer: This happends because  ur "no.png" "d.png" and "n.png" are duplicated in resources . Just look for delete dublicated files and delete.
Answer: The error seem to appear when u have more than one reference of the same file.
I had 2 files of the same name and got this error. When I delete one of them the error disappear..
Answer: Yet another variation on this issue.  I had the same message come up none of the previously suggested solutions solved the problem (I definitely only had one copy of the offending file for instance).
My solution was to edit the project.pbxproj file in a text editor (after quitting XCode and backing up the file of course) and remove all references to the offending file.  Then, after starting XCode again, I manually added the file back into the project and everything was ok.
(My suspicion is that this problem happened to me because of a manual, ie: non-XCode, merge of the project file.)
Answer: Open the Frameworks folder in your project and make sure there are only frameworks inside. I added by mistake the whole Developer folder!
Answer: I had the same problem minutes ago. I've mentioned changing the 'deployment target' fixed my problem.
Answer: For me the Target > Build Settings > Packaging > Product Name was set to the same thing as another value referenced in a .plist file which was custom to my app. Eventually due to our build process this creates duplicate files.
Answer: Commenting use_frameworks! in PodFile worked for me.
#use_frameworks!

Note: Did this on XCode 10.1, pod version 1.8.4
Answer: Swift 3: (but also the older versions) it happen when I have assets with duplicates. Just rename the files with this issue and all go well.
It could happen also when you have made a Assets.xcassets and you have renamed the duplicates with new names so after time you forgot it and  remove it to add the folder references but this one return to the duplicate files problem..
Answer: One of simple way is,

Go to App target
Go to Build Phases
Output files
Delete path of out put files, then build project. It will run successfully.
Answer: The key was to do pod deintegrate and rm *.workspace file ! What a waste of time !
Answer: React-Native users.
goto file -> workspace settings -> build system -> change it to legacy build system.
and it should build fine now.
React-Native isn't compatible with the new file system yet.
Answer: This might also happen in cases where you have multiple xcode project which reference the same library in your workspace, the worksapce tries to copy the same library to the the BUILD dir even if you build a target that is dependent on a single framework.
To solve this I have used:
Select yout target and click:
-> Edit Sheme

-> Under build - UNCHECK Find implicit dependencies

In some cases I also had to unckeck Parallelize Build
Answer: "Product Name" in Build Settings was empty in my case. So the output becomes .app with empty name which leads multiple products. Set a product name and you are good to go.
Answer: For me this was because i changed project folder name.
and i solve it by changing the project folder name from Targer app > Build Settings > info.plist file change folder name here.
Answer: While I'm sure there is a better way, nuking only took me less than 60 seconds, and was the only thing I could find that worked.

Drag repo to the trash.
re-clone your repo.
set up your repo with correct remote tracking. git remote add <url.git>, or git remote set-url <url.git>


How much can the Pearson and Spearman correlation coefficients differ in a dataset? (edited)

Question: Probably this has been asked and answered before, but I could not find an answer. It can also be, that I don't find an answer, because it is not a meaningful question.
Nevertheless, I would be interested in a set of data with Pearson correlation above 0.95 and Spearman correlation below 0.6.
Comment: I did: it isn't clear what you mean by a "relationship" or even by "linear."  Are you implicitly equating the meanings of "monotonic" and "linear" with the Spearman and Pearson correlation coefficients, respectively?  If so, are you referring to the coefficients in the underlying model or in the data?  The answers clearly use different senses of "linear" and "monotonic," which is why some of them disagree.
Comment: Are you asking if it's possible to have a set of data w/ those values, or have you seen one & want to know how to interpret that?
Comment: I have not seen one like that, I am asking whether this is possible or not.
Comment: Could you please explain what you mean by a "linear" or "monotonic" relationship?  The reason why this needs elaboration is plain in some of the answers you are receiving, which exhibit scatterplots that are obviously neither linear nor monotonic.  The issue is whether you are asking about *data* or a *regression model.*
Comment: @whuber I am not sure how to do this. I do not think it is appropriate to change the title, although as I explained in my comment to the answer by Alexis, it would have been better to ask "Can a relationship measured to be strongly linear but not strongly monotonic?" I think, the text of the question is clear. I was looking for an example set of data with very specific Pearson and Spearman correlation coefficients. The answers I get are to this specific question. The reason I did not accept either of them, because they all give different perspectives.
Comment: That's precisely the problem: vague questions get varying answers depending on the interpretations.  That doesn't work out well in most instances: it confuses people and may even lead to extensive misunderstanding.  By clarifying the text and/or the title you can help people understand what the intended interpretation is.
Comment: @whuber Can you explain to me what is vague about the text itself?
Comment: No you did not. You explained why my title is vague. I agree. But titles are not to explain the full question. The question is very specific and clear. It may not have strong connections to the title, but nevertheless, it is a clear specific question and people answered to that clear, specific question. People, who wanted to understand the question did, and answered it.
Comment: And the fact that they answered the question in different ways is *prima facie* evidence of its ambiguity.
Comment: @whuber, can you please tell me what would be an acceptable title for you for the question I asked in the post itself: "I would be interested in a set of data with Pearson correlation above 0.95 and Spearman correlation below 0.6." ?
Comment: Looking over the answers, I see two of them responded to "linear/monotonic" dichotomy in the title and three responded to the question about correlation coefficients. Perhaps the best thing you can do at this point, then, is to alter the title to match the question.  Something a little more open-ended than stipulating values of 0.95 and 0.6, like "How much can the Pearson and Spearman correlation coefficients differ in a dataset?", might be the most helpful for understanding your intentions.
Comment: @whuber Thanks, I edited the title. However, I would like to point out, that this difference between title/text was exactly what I was mentioning in my reply to your very first comment and also in my comment in flagging this question for moderator attention that was promptly ignored.
Comment: That's right, and for good reason: material that appears only in comments usually is ignored.  Comments have second class status here.  To be on topic, the *question itself* must stand alone and be sufficiently consistent and understandable to be unambiguously answered.  As soon as you created those conditions for an answerable question, it was reopened.  But some damage has been done: at least two of the posted answers do not address the question.
Comment: We can argue about this all year long. Moderators, who censor questions should not ignore answer to their concern which themselves put as a comment. We would not be in this situation if you would have answered my very first reply in a more positive way. The "damage" is partly done by me by not being careful with the title, but partly done by you not replying constructively for a long time. If you go up and read my first comment, it does say I am not sure what to do and it does include a possible title change.
Answer: Sure.  We can achieve this result by adding a single extreme data point to an otherwise uncorrelated, and nonmonotonically related, set of data:
x <- c(rnorm(99), 100)
y <- c(rnorm(99), 100)

> cor(x,y,method="pearson")
[1] 0.990387
> cor(x,y,method="spearman")
[1] 0.02534653

Note that the first 99 values are uncorrelated with each other according to either definition of the term, but the 100th value is extreme.  This causes the Pearson correlation coefficient to be large, but the  Spearman correlation is less affected, as the rank of the largest value is 1 regardless of how large the value itself is.
Compare to a less extreme outlier:
x[100] <- 10
y[100] <- 10

> cor(x,y,method="pearson")
[1] 0.5148878
> cor(x,y,method="spearman")
[1] 0.02534653

And a plot:
Comment: It's possible to make this even weirder by giving a strong linear trend downward on that cluster of points. The Spearman will be strongly negative while Pearson is strongly positive!
Comment: Nice illustration of the leverage effect in regression/correlation.
Answer: An (less extreme) example without outlier is
x <- 1:200
y <- c(rep(0, 50), rep(1, 100), rep(2, 50))  - 0.001 * x

plot(y ~ x, type = "s")
cor(x, y)               # 0.90
cor(x, y, method = "s") # 0.69

Comment: This is not a linear relationship between $Y$ and $X$ without adding an additive interaction with at one additional variable creating the shifts in the intercept. Indeed the positive Pearson;s $r$ that must result from such a graph belies the *negative* association between $Y$ and $X$ which would result from conditioning on that/those other variables.
Answer: Part I. No: Linearity is one example of monotonicity.
A monotonic relationship between $Y$ and $X$ means "$Y$ never decreases as $X$ increases, but only increases or remains constant" (for positive monotonicity), or "$Y$ never increases as $X$ increases, but only decreases or remains constant" (for negative monotonicity). A positive linear relationship between $Y$ and $X$ fits the former relationship, and a negative linear relationship between $Y$ and $X$ fits the latter.
While we cannot validly infer that "monotonicity implies linearity" in precisely the same way that we cannot infer that "food implies apples," we can infer that "linearity implies monotonicity" in the same way that "apples imply food."
Correspondingly, a lack of monotonicity implies a lack of linearity, but a lack of linearity does not imply a lack of monotonicity.
Part II. Pearson's $r$ is a fragile measure of linearity
Pearson's $r$ is subject to particular assumptions in order to produce estimates which have reliable interpretations. For example, violation of the homoscedasticity assumption (familiar from linear regression) can produce more or less any value of $r$ in uncorrelated data (i.e. in data with no linear, and no monotonic relation) with the simple addition of a high leverage data point which is (1) an extreme value in the $X$ dimension, and (2) has a value of $Y$ for that extreme value of $X$ including some non-zero slope on the linear regression between $Y$ and $X$. In this way, you can obtain an arbitrarily strong (and invalid) estimate of linearity, with an arbitrarily weak Spearman's $r_{\text{S}}$.
Comment: Probably I was not careful enough phrasing the title. I was looking for an example that is given in the answer by @jbowman . Probably I should have asked "Can a relationship be measured to be much more linear than monotonic?" And apparently (contrary to my intuition) it can.
Comment: @FerencBeleznay Please see my update.
Answer: I cannot add comments comments right now, so I added this as a new answer.
Alexis is totally right, that there can't be linearity without monotonicity. However, it is still possible to get a higher Pearson than Spearman correlation coefficient.
Just correlate  1,2,3,1000000 wit 5,4,3, 1000000.
 The Pearson coefficient is close to 1, while the Spearman correlation coefficient is only 0.2.
Answer: Any kind of trend with seasonality data will fit your description. For instance, CPI not seasonally adjusted will have a strong linear trend, but CPI increase over time is clearly non-monotonic due to annual seasonality.
Comment: Not sure that the trend is "clearly linear" for *exactly* the same reasons that your describe the trend as "clearly non-monotonic." (I.e. a *monotonic* trend will not shift up and down, but likewise a *linear* trend will also not shift up and down; put another way: if you can blur your eyes on that curve to see *linear*, then you have already blurred your eyes enough to see *monotonic*).
Comment: The time trend is upwards, and could appear linear. It has to be, it's prices. Yet the increase over time is not monotonic.
Comment: "The time trend is upwards, and could appear linear. It has to be, it's prices" <—You have just made the argument that the *trend* in price is monotonically increasing.