Asymptotic behaviour of quantity related to an ODE

Question: Consider the differential equation
$$u''(t) + u(t) + u^3(t) = f(t) u(t) + g(t),\,\, u(0) = u_0, \,u'(0) = u_1$$
where $u :\mathbb{R}^+ \to \mathbb{R}$ is a bounded solution  and $f, g: \mathbb{R}^+ \to \mathbb{R}$ are given continuous functions such that $$\lim_{t\to \infty} f(t) = \lim_{t\to \infty} g(t) = 0.$$
Define the quantity $E(t) := \frac 12 (u(t))^2 +\frac 12 (u'(t))^2 + \frac 14 (u(t))^4.$
I want to study the asymptotic of $E$ when $t \to \infty.$  First, I considered many examples for $f, g$ using mathematica (See the attached images where I plotted $t\mapsto E(t)$). I'm interested in the case where
$\liminf_{t\to \infty}E(t) >0$ or roughly $\lim_{t\to \infty} E(t) >0.$ I wonder if this is the general case or it depends on the initial values $u_0, u_1$ and $f,g.$ In all the examples that I tested numerically, I found that $\lim_{t\to \infty} E(t) >0.$
My attempt started by differentiating $E$ with respect to $t.$ It seems that in the case where
$u'$ is bounded, we have $$\lim_{t\to \infty} E'(t) =0,$$
since $E' = (f u + g) u'.$ But this does not imply necessarily that $\lim_{t\to \infty}E(t) >0.$
The limit might be zero.
Thank you for any hint.
Comment: Interesting question. Is it physics related or pure maths?
Comment: You can certainly kill a carefully chosen solution by $f,g$. Just put $g=u^3$. Then all you need is to kill $u$ in the equation $u''+u=fu$. Now just take that harmonic oscillator and apply some decaying force against the motion when it is far from the origin (as long as it deviates a certain distance, you can keep the force fixed, so the energy is lost at a fixed rate). That will send everything to $0$ at $+\infty$
Comment: Mathematical physics :D
Comment: @fedja Do you mean that I just need to consider the harmonic oscillator with some decaying force $F,$ so that $u'' + u = F$? In that case and when coming back to the OP, $f$ will be $F/u.$ How can you chose $F$ such that $\lim_{t\ to \infty} f(t) = 0$?
I'd be grateful if you give more explicit details about the decaying force in the harmonic oscillator.
Answer: In order for the system to be well-behaved a sufficient condition is that $f$ and $g$ are integrable at infinity.
Consider some uniform bounds of the RHS in terms of the energy functional (a standard trick): The $f$ term behaves the best. By Cauchy-Schwarz you have $|uu'|\leq E$ whereas for the $g$ term you only have $|u'|\leq \sqrt{2 E}$. We thus get the crude bound:
$$ |E'| \leq |f| E + |g| \sqrt{2E}$$.
A special case is $g\equiv 0$ for which we get (use e.g. a Gronwall Lemma):
$$ |\log(E(\infty)) - \log(E(0)) | \leq \int_0^\infty |f(t)|dt.$$
In this case it suffices that $f$ is integrable in order for
$\lim_{t \rightarrow \infty}  E(t)$ to exist and be strictly positive.
When $g$ does not vanish you may put e.g. $E=\frac12 A^2$  which yields (as long as $A>0$):
$$ |A'| \leq \frac12 |f| A + |g| $$
When e.g. $f$ and $g$ are integrable then also in this case the  system never explodes (use again a Gronwall Lemma) and will have a finite limit  which, however, may be zero. You may also from this get conditions on initial values of $A$ which when large enough compared to the $L^1$ norm of $f,g$ give lower bounds that assures that the limit is strictly positive. For example, a sufficient condition is that
$$ A(0) \ (1 - \frac12 \|f\|_1) > \|g\|_1 $$
Comment: Thank you very much for this adequate answer. Under the same assumptions that you mentioned above (integrability of $f,g$), I was thinking of proving that $u$ converges to $v$ the solution of  $v'' + v + v^3=0$ but for unknown initial values.
Comment: You are welcome.  In the $(u,u')$ plane the solution is winding around and you would need to show that the perturbation only yields a finite 'phase'-shift when integrated forward in time (to infinity). This looks quite plausible.
Comment: It yields a finite phase shift and a change in the  "amplitude."
Comment: OK, looks reasonable and promising. Is this part of your research or just for fun?
Comment: Somehow a part of my research. It's a bit related to specific topic in the domain of semi linear wave equations. If you are interested, I'd be happy to send you more details and work together on it. I guess you are affiliated to a place where I did a part of my undergraduate edu. and worked as well :).
Comment: You are welcome to send me details. I like the problem. And yes, I am easy to find. All the best.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117924/discussion-between-a-pi-and-h-h-rugh).
Answer: If $\;t\to\infty,\;$ then the given ODE takes the form of
$$\ddot u+u+u^3 =0,\tag1$$
which does not contain variable $\;t.\;$
Substitution $\;P=\dot u,\;\ddot u = P'_u\, \dot u = P\,\dfrac{\text dP}{\text du},\;$ presents $(1)$ in the form of
$$P\,\text dP = -(u^3+u)\,\text du,$$
$$P=\dfrac12\sqrt{(a^2+1)^2-(u^2+1)^2},$$
$$\dfrac{\text du}{\sqrt{a^2-u^2}} = \sqrt{2+a^2+u^2},\tag2$$
and after substitutiion
$$v=\arcsin \dfrac ua$$
one can get
$$\text dv = \sqrt{2+a^2(1+\sin^2 v)}\,\text dt,$$
with the solutions
$$v(t) = \text{am}\left(\sqrt{a^2+2}\,(t+b)\bigg|\dfrac{a^2}{2+a^2}\right)$$
and
$$u(t) = a \text{ sn}\left(\sqrt{a^2+2}\,(t+b)\bigg|\dfrac{a^2}{2+a^2}\right),\tag3$$
where $\;\text{am}\;$ and $\;\text{sn}\;$ are the Jacobi functions.
The Jacobi functions looks too heavy for applying of the constant variations method.
Taking in account derivatives
\begin{cases}
\left(\text{sn}(x|m)\right)' = \text{cn}(x|m)\text{ dn}(x|m)\\[4pt]
\left(\text{cn}(x|m)\right)' = -\text{sn}(x|m)\text{ dn}(x|m)\\[4pt]
\left(\text{dn}(x|m)\right)' = -m\text{ sn}(x|m)\text{ cn}(x|m),
\end{cases}
looks possible to find parameters $\;a\;$ and $\;b\;$ for the given functions $\;f(t)\;$ and $\;g(t)\;$ numerically, using the next statement:

$E(t) = \dfrac14(2u'^2+u^4+2u^2) \ge 0,$
$E(0) = \dfrac14(2u_1^2+u_0^4+2u_0^2),$
$E'(\infty) = 0,$
$E(\infty) = E(0)+\int\limits_0^\infty(uf+g)\,\text dt.$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117782/discussion-between-a-pi-and-yuri-negometyanov).
Comment: Thank you for this nice answer to solve the limit equation (mentioned (1)). But still have some remarks/questions: Equation (1) is non linear and the right hand side of the original equation has $u$ as well. So how can you apply the "constant variation" method ?
In which sense the original ODE tends to (1)?
How can the proposed solution in your answer be useful to study the asymptotic of E when $t \to \infty$ ?
Comment: @A.PI Since $f(t)\to 0$ and $g(t)\to 0$ when $t\to\infty,$ then $(1)$ is the asymptotic case for the bounded solutions of the given ODE. On the other hand, the quantity $E$ contains only the derivative and the degrees of $u.$ At the same time, consideration of b  as the certain function looks as non-suitable way.
Comment: This means that the left hand side of the original equation tends to that of (1), but not necessarily for the solutions.  Check numerically  the example where $f(x) = g(x) = e^{-x}$  with initial values $u_0 = u_1 =0.$ It is clear that the corresponding unique solution for  equation (1) is $u =0.$ However, the original ODE seems to have nontrivial solution that doesn't tend to 0 when $t \to \infty$
Comment: @A.PI You are right, thanks! Fixed typo.
Comment: After many numerical tests for different examples of $f, g,$ It seems that the solution to the original ODE tends to a function of type (3) but with different values of $a, b$ than for (1).
Comment: @A.PI Thank you  for the comments! I'm glad that it works.
Comment: In fact, numerical tests are not a proof. What I wanted to say is that the solution to the original ODE behaves asymptotically when $t\to \infty$ as a solution of (1) but with "mysterious" initial values. This is still a conjecture.
Comment: @A.PI We can get E(t) and provide the conditions of OP via a and b values. This does not look misterious.
Comment: At this level you can not get any information about the asymptotic of $E(t)$ when $t\to \infty.$ Whereas, in the case of Equation (1) in your answer this quantity is clearly constant.
Answer: I'd be grateful if you give more explicit details about the decaying force in the harmonic oscillator
You can do it as I said or you can do it in an even simpler way and put $f=0$, $g=u^3-u'$ (effectively eliminating the non-linear term and adding the damping). Then you just have a linear equation $u''+u'+u=0$, which has an exponentially decaying solution, so your $g$, indeed, tends to $0$ at infinity. The more interesting question seems to be
Is there any pair $f,g$ tending to $0$ at $\infty$ such that all (or, at least, many) solutions decay to $0$ at infinity?
though, perhaps, I'm missing something simple here.


Word Problem about no. of square inches of pizza from GRE Quant

Question: Huey's Hip Pizza sells two sizes of square pizzas: a small pizza that measures $10$ inches on a side and costs $\$10$, and a large pizza that measures $15$ inches on a side and costs $\$20$. If two friends go to Huey's with $\$30$ apiece, how many more square inches of pizza can they buy if they pool their money than if they each purchase pizza alone?
My solution: I have solved that problem but however, my answer does not coincide with official answer. Here's my solution:
If they purchase alone they can buy $3$ small pizzas (in that case total area is $100\cdot 3=300$ square inches) or $1$ small+$1$ large (in that case total area is $100+225=325$ square inches). Hence when they purchase each pizza alone then the total area will be $2\cdot 300=600$ square inches or $2\cdot 325=650$.
If they purchase together they can buy:
(i) $6$ small pizzas then total area will be $6\cdot 100=600$
(ii) $1$ large + $4$ small then total area will be $225+4\cdot 100=625$
(iii) $2$ large + $2$ small then total area will be $2\cdot 225+2\cdot 100=650$
(iv) $3$ large then total area will be $3\cdot 225=675$
Eventually, the maximal difference is $675-600=75$.
Is my answer true?
Comment: Why are you subtracting $600$ instead of subtracting $650$?  That is not how I would interpret the question.  I would think it is "*What is the difference between the largest amount of pizza they could buy if they bought together and the largest amount of pizza they could buy if they bought separately.*"  $650$ square inches is the largest amount of pizza they could buy separately, not $600$ square inches.
Comment: If you are indeed interested in the "maximal difference" as you put it, then you are ignoring the possibility of them not buying any pizza at all.  It didn't say that they needed to use all of their money, so the least amount of pizza they could buy separately is $0$ square inches.
Comment: I think you must assume that they will be maximally efficient in their pizza spending going it alone or pooling.  $675-650 = 25$
Comment: how should I know that i need to substract the largest amount of pizza they could buy if they bought separately? In order to get maximal difference i need to substract from maximal term the least term.
Comment: It is *heavily implied* that they will be greedy and buy the most pizza possible with what money they have.  Also, I don't know where you got the phrase "maximal difference" out of this problem or what you specifically define that to mean.
Comment: @JMoravitz, yes you are right that the notion maximal difference sounds here little bit ridiculous. But what does mean "how many more square..?" Why we subtract only these numbers 675 and 650? That's I can't grasp.
Comment: You could use the rewording of the question I gave in my first comment, or you could think of it as having a missing phrase: "How many more square inches of pizza can they purchase if they pool their money instead of purchasing alone [*assuming they buy the most amount of pizza possible with their money within the constraints in both cases*]."  To be fair, that *is* an assumption, but more than a safe assumption because otherwise the problem is uninteresting.
Answer: Your assumption about buying $6$ small pizzas is correct but there is no incentive for that .
For $\$30$, each can get a large and a small $\quad \rightarrow 2(225+100)=2\times 325=650$
Combined, they can get $3$ large pizzas $\rightarrow 3(225)=675$
$$675-650=25$$
Your assumption about buying $6$ small pizzas is correct but there is no incentive for that .


Need to write a SQL query to fetch data from a Oracle database

Question:
Possible Duplicate:
Need to write a SQL query to fetch data from a Oracle database

I need to write a SQL query which can fetch a data from one table A.
Senario - Lets take table A has only two column C1 and C2. C1 has row_id's and C2 has vaues like "Site=google;site=gmail;yahoo"
Requirment - Need to write a query which can fetch all the row_id from column C1 of table A but the value should come for column C2 as "yahoo". Means if anything starts with "Site=" in any value of C2 column then it should not been shown in the data fetch.
Comment: Exact duplicate of "http://stackoverflow.com/questions/5091642/need-to-write-a-sql-query-to-fetch-data-from-a-oracle-database"?
Comment: @TToni: I just re-read this and thought to myself that my SO hadn't refreshed properly lol
Answer: Try
<code>select
   *
from
   tableA
where
   c2 not like 'site=%'
</code>
Comment: I think you have misunderstood the question.
Comment: No Jon, I think you got this wrong. Example - Suppose if a value is "Site=google;site=gmail;yahoo" then query should fetch "yahoo" only.
Comment: Ah, I see - give me a minute...
Comment: I see there's an answer on the other copy of this question. I'll leave it there.
Comment: Jon that was different question..Here is different. If you can, then please answer it here. It would be great help.


How to make Icon in QMenu larger (PyQt)?

Question: I did not yet find out how to make the icons in my QMenu larger. I have tried to define a stylesheet in which the icon size is enlarged. But it doesn't work. Here is my code:
menuStyleSheet = ("""
        QMenu {
            font-size: 18px;
            color: black;
            border: 2px solid black;
            left: 20px;
            background-color:qlineargradient(x1:0, y1:0, x2:0, y2:1, stop: 0 #cccccc, stop: 1 #ffffff);
        }

        QMenu::item {
            padding: 2px 20px 2px 30px;
            border: 1px solid transparent; /* reserve space for selection border */
            spacing: 20px;
            height: 60px;
        }

        QMenu::icon {
            padding-left: 20px;
            width: 50px;        /* <- unfortunately, doesn't work */
            height: 50px;       /* <- unfortunately, doesn't work */
        }
    """)

#####################################################
#               THE PYQT APPLICATION                #
#####################################################
class GMainWindow(QMainWindow):

    def __init__(self, title):
        super(GMainWindow, self).__init__()
            ...

    def setCustomMenuBar(self):
        myMenuBar = self.menuBar()
        global menuStyleSheet
        myMenuBar.setStyleSheet(menuStyleSheet)
        # Now add Menus and QActions to myMenuBar..

The result of this code is as follows:

I know that there is an old StackOverflow question about a similar topic, but it assumes that one is coding the Qt application in C++. So the situation is different. Here is the link: How to make Qt icon (in menu bar and tool bar) larger?
Any help is greatly appreciated :-)
EDIT :
Here are some details about my machine:

OS: Windows 10
Python: v3 (Anaconda package)
Qt: PyQt5
Comment: What if you create a `QStyleOptionMenuItem` and set the `maxIconWidth` variable?
Answer: After a long search, I finally found the solution.
Just copy-paste the code below, and paste it in a *.py file. Of course, you should replace the path to the icon with a valid path on your local computer. Just provide a complete path ("C:\..") to be 100% sure that Qt finds the icon drawing.
import sys
import os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

# Create a custom "QProxyStyle" to enlarge the QMenu icons
#-----------------------------------------------------------
class MyProxyStyle(QProxyStyle):
    pass
    def pixelMetric(self, QStyle_PixelMetric, option=None, widget=None):

        if QStyle_PixelMetric == QStyle.PM_SmallIconSize:
            return 40
        else:
            return QProxyStyle.pixelMetric(self, QStyle_PixelMetric, option, widget)

# This is the main window class (with a simple QMenu implemented)
# ------------------------------------------------------------------
class TestWindow(QMainWindow):
    def __init__(self):
        super(TestWindow, self).__init__()

        # 1. Set basic geometry and color.
        self.setGeometry(100, 100, 400, 400)
        self.setWindowTitle('Hello World')
        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(200, 200, 200))
        self.setPalette(palette)

        # 2. Create the central frame.
        self.centralFrame = QFrame()
        self.centralFrame.setFrameShape(QFrame.NoFrame)
        self.setCentralWidget(self.centralFrame)

        # 3. Create a menu bar.
        myMenuBar = self.menuBar()
        fileMenu = myMenuBar.addMenu("&File")

        testMenuItem = QAction(QIcon("C:\\my\\path\\myFig.png"), "&Test", self)
        testMenuItem.setStatusTip("Test for icon size")
        testMenuItem.triggered.connect(lambda: print("Menu item has been clicked!"))

        fileMenu.addAction(testMenuItem)

        # 4. Show the window.
        self.show()

# Start your Qt application based on the new style
#---------------------------------------------------
if __name__== '__main__':
    app = QApplication(sys.argv)
    myStyle = MyProxyStyle('Fusion')    # The proxy style should be based on an existing style,
                                        # like 'Windows', 'Motif', 'Plastique', 'Fusion', ...
    app.setStyle(myStyle)

    myGUI = TestWindow()

    sys.exit(app.exec_())

You will see a window like this, with a huge icon:

So how did I solve it? Well, apparently you cannot increase the icon size of a QMenu item in the usual way - defining the size in the stylesheet. The only way to do it is to provide a new QStyle, preferably derived from an existing QStyle. I found sources on how to do that in C++ (see http://www.qtcentre.org/threads/21187-QMenu-always-displays-icons-aty-16x16-px), but no explanation for PyQt.
After long trials and errors, I got it working :-)
Apparently more people struggle with this situation: http://www.qtcentre.org/threads/61860-QMenu-Icon-Scale-in-PyQt
Comment: This is 100% what  I am looking for, except PySide2 doesn't seem to provide QProxyStyle :(


Has there ever been a football player who held the title of "most goals in one season in history" in two different countries?

Question: One of my favourite football players, Eran Zahavi, broke the record for most goals in one season in Israel two years ago.  He's currently well on his way to break the same record in China - the most goals scored in one season in the Chinese Super League is 28 goals, and he has 22 goals with 10 games remaining.
If he ends up breaking the record of the most goals in one season in China, which means he will have this record in two separate countries, will he be the first player to do that in history?
Note that what I'm looking for here is breaking the record in each country, not just being the highest scorer in a particular season. For example, suppose the most goals ever scored in one season in France is 31 and in Germany is 37. If a player comes along and scores 32 goals in France in one season, then he moves to Germany and scores 38 goals in one season, that would count. However, a player who was the highest scorer in one season in France with 30 goals and then scored 38 in Germany would not count as they didn't actually break the record in France. There is no requirement for the two record breaking seasons to be consecutive.
Answer: I can't find any players who strictly meet this criteria, but Cristiano Ronaldo certainly has a case for it. He jointly holds the record for goals scored in a 38-game Premier League season (31 goals in 2007–08), as well as having held the record for the most goals scored in La Liga, with 40 in 2010–11 (albeit only for a solitary year, as Lionel Messi scored 50 the very next season).
I specify a "38-game Premier League season" because in the early to mid 1990s, two players (Andy Cole and Alan Shearer) scored 34 goals in a single season, but they had 42 games to do this in. The Premier League officially acknowledges both of these totals as records, which means that if you found a stats book from 2011 listing the record number of goals scored in any individual season for every top-flight league, Cristiano Ronaldo's name will probably appear twice.
Comment: If he had scored 39 in England, I'd have considered him. I specifically wondered about someone who **broke** (vs **tied**) the record twice.


Ruby on rails routes

Question: Pessoal estou começando em Ruby on Rails e tive um problema com as chamadas nested routes:
 class Maquina < ApplicationRecord
        has_many :verificacaos
        accepts_nested_attributes_for :verificacaos
    end

    class Verificacao < ApplicationRecord
      belongs_to :maquina
    end

      resources :maquinas do
        resources :verificacaos
      end

Foram essas as linhas que eu alterei no código que me gerou a url:maquinas/:maquinas_id/verificacaos
Porém ele não mostra somente a verificação especifica para a maquina do ip requisitado, e sim todas as maquinas independente do computador ao qual ela está relacionada.
Alguém poderia me dar uma luz?
Edit: Contoler Maquina
class MaquinasController < ApplicationController
  before_action :set_maquina, only: [:show, :update, :destroy]

  # GET /maquinas
  def index
    @maquinas = Maquina.all

    render json: @maquinas
  end

  # GET /maquinas/1
  def show
    render json: @maquina
  end

  # POST /maquinas
  def create
    @maquina = Maquina.new(maquina_params)

    if @maquina.save
      render json: @maquina, status: :created, location: @maquina
    else
      render json: @maquina.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /maquinas/1
  def update
    if @maquina.update(maquina_params)
      render json: @maquina
    else
      render json: @maquina.errors, status: :unprocessable_entity
    end
  end

  # DELETE /maquinas/1
  def destroy
    @maquina.destroy
  end

  private
    # Use callbacks to share coMon setup or constraints between actions.
    def set_maquina
      @maquina = Maquina.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def maquina_params
      params.require(:maquina).permit(:marca, :modelo, :numeroPatrimonio, :numeroSerie, :nomeMaquina, :usuarioMaquina, :processador, :memoriaRam, :hd, :sistemaOperacional, :setor, :descricao)
    end
end

Controler Verificação
class VerificacaosController < ApplicationController
  before_action :set_verificacao, only: [:show, :update, :destroy]

  # GET /verificacaos
  def index
    @verificacaos = Verificacao.all

    render json: @verificacaos
  end

  # GET /verificacaos/1
  def show
    render json: @verificacao
  end

  # POST /verificacaos
  def create
    @verificacao = Verificacao.new(verificacao_params)

    if @verificacao.save
      render json: @verificacao, status: :created, location: @verificacao
    else
      render json: @verificacao.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /verificacaos/1
  def update
    if @verificacao.update(verificacao_params)
      render json: @verificacao
    else
      render json: @verificacao.errors, status: :unprocessable_entity
    end
  end

  # DELETE /verificacaos/1
  def destroy
    @verificacao.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_verificacao
      @verificacao = Verificacao.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def verificacao_params
      params.require(:verificacao).permit(:data, :status, :verificadoPor, :maquina_id, :observacao)
    end
end

Comment: Você pode postar o código dos controllers também?
Comment: Eu não alterei os controlers, pelas minhas pesquisas são eles que eu preciso alterar, mas não sei como
Comment: Se qualquer forma estão ai
Comment: Você quer ver uma verificação específica de uma máquina específica, correto?
Comment: Sim, isso mesmo, por exemplo, quando eu digitar maquinas/:maquinas_id/verificacaos tem que aparecer somente as verificações que tiverem a maquina_id igual a que foi colocada na url
Answer: Seu problema está no VerificacaosController. A url maquinas/:maquinas_id/verificacaos é processada pela action index, a qual está retornando tudo:
# GET /verificacaos
def index
    @verificacaos = Verificacao.all

    render json: @verificacaos
end

Você só precisa incluir :maquinas_id na query:
# GET /verificacaos
def index
    @verificacaos = Verificacao.where(maquina_id: params[:maquina_id])

    render json: @verificacaos
end

E a action vai trazer somente os objetos relevantes.
Comment: Cara, eu te amo, muito kkkk

Ruby on rails routes


Composing for mezzo-soprano

Question: I'm composing for a competition that is for a string quartet but also has a requirement for a mezzo-soprano. I have very little experience with singers but I'm aware that the range is A3 - A5.
Are there other constraints I should be aware of? Although breathing is an obvious aspect. Does it make sense for me to try and sing the appropriate part to feel it's doable?
Comment: I rarely see soprano parts go to an A5, so maybe show restraint for the really high notes.
Comment: Trying to sing the part you've written is a good idea, but beware. It's difficult to get a feel for the difficulty of a different voice's part unless you're that voice type. I've had plenty of parts written for me by people who were a different voice type, and invariably they'd be unnecessarily difficult because people didn't realise how difficult certain notes were for my voice type, especially at low dynamics. Hard to write for mezzos if you sing bass II.
Answer: Another thing to consider in your orchestration is the timbre, more specifically that it changes as the part goes towards the extremes. Do you really want the sound of a mezzo-soprano trying to hit an A5 just so that you can fill out your chord? Be aware of the blend you can realistically achieve with the part you've written. The more range you include in the mezzo part, the more difficult it will be for a human singer to produce the tone you desire.
Additionally, you may want to go find a friend who can sing this and ask for their opinion. Even if you yourself are a mezzo-soprano, it's always better to hear others' opinions. The composer may overestimate the abilities of the performers they write for, as they didn't have to "learn" the part, because they wrote it around their own voice (perhaps subconsciously).
Answer: Yes, that's the textbook range, though I'd be wary of the top few notes.  That's not what mezzo-soprano is all about.
Yes, it's an excellent idea to check that the part is singable by you.  Not so much for the range (unless YOU'RE also a mezzo soprano!) but for breathing, tricky jumps etc.   And make sure it's melodic and rewarding to sing!
You'll need to suss out whether this is the sort of competition where cutting-edge 'alternative' stuff is obligatory, or whether you're allowed to write tunes :-)

Composing for mezzo-soprano


What is the idea of "transposing by perfect unison"?

Question: As far as I understand, a "perfect unison" refer to two notes sounding the same pitch. Why both MuseScore and Sibelius 7 (I work with these two programs) offer a feature to transpose the up or down by "perfect unison"?
I tried to transpose a single A placed on the usual staff. When I select "augmented unison", the computer places the # in front of it (if to transpose up) or b (if to transpose down). Hence the augmented unison seems exactly one half tone distance.
However nothing happens when I try to transpose by "perfect unison", that makes sense taking its definition into consideration. But why to have such a "feature" at all? Maybe something would happen when transposing more complex piece with constructs I am not aware?
Comment: You're right, the option doesn't make sense. It's probably there for no specific reason.
Answer: You're right. There's no effect when transposing by a perfect unison. But it does make sense to have the option of transposing by an augmented unison (eg. Ab major to A Major) or a diminished unison (eg. B major to Bb Major). I guess the perfect unison option is simply there because you have perfect, diminished and augmented transpose options for each interval.
Just to be sure, I tried transposing a few passages by a perfect unison using Sibelius 7 (I don't have MuseScore), and yes, the notes are unaffected, but weirdly, the spacing changes…
EDIT: okay, I have spotted one way you can usefully use the transpose by perfect unison function. The transpose function in Sibelius has a "use double sharps/flats" checkbox. You could uncheck this box and transpose by a perfect unison to re-notate the music without double sharps/flats. This is useful; sometimes music is easier to read with more accidentals, but fewer double sharps/flats, even if this is less theoretically "correct". (Eg. G#, G natural, G#, G natural). Having said this, there may be a plug-in for dealing with this anyway.


Distribution of the sum reciprocal of primes $\le 1$

Question: $$\frac{1}{2}+\frac{1}{3}+\frac{1}{7}+\frac{1}{43}+\cdots \le 1 $$
This is an interesting infinite summation. This is very closely resembling my other problem with has to do with the distribution of composites. That other problem is here. The same rules of that other summation apply, but it's good to repeat them :).
Rules of this summation:
1) All terms of the summation must be reciprocal of some prime. For example, $\frac{1}{6}$ could never be a term because 6 is not a prime number.
2) The next term must be the largest reciprocal term that does not allow the entire sum to be $>1$. The next term also must be < the term before it.
3) The sum must also be permanently less than $1$ if you were to stop at a number $\lt \infty$. If you were to stop on term $\infty$, then the sum would amount to exactly $1$ by definition.
Now that you know the rules, we must rewrite the summation in a different way in order to propose my question in a reasonable manner. $$\frac{1}{a}+\frac{1}{b}+\frac{1}{c}+\frac{1}{d}+\cdots\le 1$$ As a mote of clarification, $a, b, c, d$, etc. represent $2, 3, 7, 43$, etc. respectively.
The question:
-Envision $ f(1)=a, f(2)=b, f(3)=c$, and so on. Keep in mind there are an infinite number of terms, thus an infinite number of variables to represent primes. My question is what function, $f(n)$, could hold this property and maintain true no matter what term you are at.
-One who is loving this must remember that $a, b, c, d$, etc. are integers rather than fractions in this case and therefor $f(1) \not= 1/a, f(1) \not= 1/b$, etc.
The reciprocal however is the form in which the numbers have that interesting property.
-What is $f(n)$? (The primary question)
-When answering this question, do the following, please provide some form of evidence or explain your case. If I missed something obvious, please let me know what that is with a website in the comments.
Have a great day! Thanks!
Comment: OEIS has the sequence listed as ["Slowest-growing sequence of primes whose reciprocals sum to 1"](https://oeis.org/A075442).
Comment: I cannot answer this question, but if you are interested, the next few primes are 1811, 654149, 27082315109, 153694141992520880899, and 337110658273917297268061074384231117039. I can keep going, but they are getting very large.
Comment: @MarcusM What a curious title OEIS has for the sequence!  Since the number of digits roughly doubles every term, I think there are much slower-growing sequence with this reciprocal sum (even https://oeis.org/A225669 sort of qualifies since it takes more terms to reach 10-20 digits).  It's certainly the lexicographically first sequence, though.
Comment: That's pretty cool, I never even knew it was on OEIS.
Comment: @AAron: It's always best to check. ;-$)$
Answer: This function can be defined recursively as
$$f(a) = NP\Big{(}\big{(}1-\sum_{k=1}^{a-1}\frac{1}{f(k)}\big{)}^{-1}\Big{)}$$
where $NP(x)$ is the next prime function. In other words, you look for the closest prime higher than the minimal number you need to keep the sum less than one in order to find $f(a)$. This sum can therefore not be expressed explicitly due to the "next prime" function used in the recursion.


Computing integral with contour

Question: I am trying to evaluate the integral $\int_0^{\pi/2}\frac{1}{\sin^2 t+(\sin t)^{-2}}dt$. The first step I took was using symmetry to get
$$\int_{0}^{\pi/2}\frac{1}{\sin^2 t+(\sin t)^{-2}}dt=\frac{1}{4}\int_{0}^{2\pi}\frac{1}{\sin^2t+(\sin t)^{-2}}dt.$$
Then if $z=e^{it}$, then we have $dz=ie^{it}dt=izdt$, and moreover
$$\frac{1}{\sin^2t+(\sin t)^{-2}}=\frac{1}{(\frac{z-z^{-1}}{2i})^2+(\frac{2i}{z-z^{-1}})^2}=\cdots =\frac{-4z^2(z^2-1)^2}{z^8-4z^6+22z^4-4z^2+1}.$$
Hence the integral becomes
$$\frac{1}{4}\oint_{|z|=1}\frac{-4z^2(z^2-1)^2}{z^8-4z^6+22z^4-4z^2+1}\frac{dz}{iz}.$$
My question is, how do we proceed from here? Using the residue theorem requires first computing the roots of $z^8-4z^6+22z^4-4z^2+1$ lying inside the unit circle, but I wasn't able to do that by hand. What is a more efficient way?
Comment: I tried applying the [residue identity for function composition](https://math.stackexchange.com/questions/2830152/residue-identity-for-function-composition-operatornameresf-ha-oper) with

$$
f(z)=\frac1{z^2+z^{-2}}=\frac{z^2}{z^4+1}
$$

and $h(z)=\frac1{2\mathrm i}\left(z-z^{-1}\right)=\sin\left(\frac{\log z}{\mathrm i}\right)$, but I think in view of the simple solution already provided by Mostafa Ayaz it's more trouble than it's worth.
Answer: You need not to decompose the denominator polynomial. Your integral can be written as
$${1\over 4}\oint_{|z|=1}{1\over iz}{({z-z^{-1}\over 2i})^2\over ({z-z^{-1}\over 2i})^4+1}dz$$with singularities lying in $z=0$ and the roots of $({z-z^{-1}\over 2i})^4=-1$ or $${z-z^{-1}\over 2i}={\pm 1\pm i\over \sqrt2}$$I leave to you finding the residue of the function at the singularities.

Computing integral with contour


Retorno Null Print Java

Question: Estou desenvolvendo um exercício em que preciso criar uma classe Ponto e adicionar a um Array de pontos sem que eu use ArrayList, ao testar a 1ª opção que há no menu recebi um retorno de que o array estava Null mesmo que eu já tivesse adicionado um objeto ponto nele.
Este é meu primeiro código em Java e não sei bem a estrutura ainda.
Os arquivos estão todos no mesmo Packages.
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int tam;
        Scanner input = new Scanner(System.in);
        System.out.println("Digite por favor o tamanho da colecao :");
        tam = input.nextInt();
        ListaPonto lista = new ListaPonto();
        lista.listap(tam);
        while(true) {
            int opc;
            System.out.println("\n\n\n\n");
            System.out.println("\n------------------------------");
            System.out.println("\nProjeto Colecao de Elementos");
            System.out.println("\n------------------------------");
            System.out.println("\n0 - Encerrar");
            System.out.println("\n1 - Adicionar um elemento no Final");
            System.out.println("\n2 - Adicionar um elemento em uma posição");
            System.out.println("\n3 - Retornar indice da primeira ocorrencia de um elemento");
            System.out.println("\n4 - Remover um elemento em uma posicao");
            System.out.println("\n5 - Calcular a distantia dos 2 pontos mais distantes");
            System.out.println("\n6 - Colecao de pontos contidos em um Circulo");
            System.out.println("\n\n Informe sua opcao :");
            opc = input.nextInt();

            if(opc == 0) {
                break;
            }
            if(opc == 1) {
                Ponto p = new Ponto();
                int x,y;
                System.out.println("\nDigite o x do Ponto :");
                x = input.nextInt();
                System.out.println("\nDigite o y do Ponto :");
                y = input.nextInt();
                p.pontos(x, y);
                lista.adiciona(p);
                lista.printa();
            }

        }
    }
}

Aqui a Classe Ponto é criada
public class Ponto{
    private int x,y;

    public int pontos(int x, int y) {
        this.x = x;
        this.y = y;
    return x;
    }

}

A Classe da Lista é Criada Aqui.
public class ListaPonto{
    private Ponto pontos[];
    private int validos;
    private int topo;

    public void listap(int N) {
        topo = N;
        this.pontos = new Ponto[N];
        this.validos = 0;
    }

    public void printa() {
        for (int i =0;i<=0;i++) {
            System.out.println(this.pontos[i]);
        }
    }

    public void adiciona(Ponto elem) {
        this.pontos[topo-1] = elem;
    }

}

Comment: Não vi todos os erros, mas uma coisa que vc podia fazer é criar construtores nas classes (por exemplo, na classe `Ponto`, em vez de ter o método `pontos`, crie um construtor que recebe `x` e `y` - o mesmo vale para o método `listap`). Veja mais detalhes [aqui](https://pt.stackoverflow.com/q/73530/112052)
Answer: Quando você inicializa um array de elementos não primitivos em Java, todas as posições são preenchidas com null. Assim, quando você executa este método:
lista.listap(tam);

Você está inicializando seu array pontos. Se neste momento, você o percorresse e printasse o conteúdo de cada posição dele, você teria algo assim:
null
null
null
...

A opção 1 do seu programa diz:
System.out.println("\n1 - Adicionar um elemento no Final");

Quando você executa a linha lista.adiciona(p);, seu programa adiciona no fim do array o ponto criado. Se você printasse novamente esse array agora, você teria algo assim:
null
null
null
seu ponto aqui

Porém, seu método printa() tem um erro:
for (int i =0;i<=0;i++) {

Veja que, da forma que está, você está dizendo que é para o for se encerrar quando i<=0. Ora, se i é inicializado com 0, isso significa que ele vai imprimir apenas o conteúdo da primeira posição do seu array, que, como expliquei antes, tem o conteúdo null, afinal, neste momento você tem apenas a última posição preenchida com o ponto que você criou.
Para que você imprima todas as posições do array, seu for deve ser:
for (int i =0;i<topo;i++) {

ou, melhor ainda:
for (int i =0;i<this.pontos.length;i++) {

Pois isso garante que todas as posições do array serão impressas.
Answer: Eu aconselharia a criar um construtor para Pontos com os parâmetros x e y.
Da seguinte maneira:
public class Ponto {
private int x,y;

public Ponto(int x, int y) {
    this.x = x;
    this.y = y;
}

E ao criar o objeto, espere os valores do console
int x,y;
System.out.println("\nDigite o x do Ponto :");
x = input.nextInt();
System.out.println("\nDigite o y do Ponto :");
y = input.nextInt();
Ponto p = new Ponto(x, y);
lista.adiciona(p);
lista.printa();

Retorno Null Print Java


React Native unlink library from iOS or android only

Question: I had searched throughout SO and just found about react-native unlink only. What i want is unlink a library in specific platform such as android or ios. By running react-native unlink will unlink all native dependencies in both android and ios platform, this is not what i'm looking for.
Thanks
Answer: I had found an answer,
react-native unlink react-native-config --platforms=ios

or:
react-native unlink react-native-config --platforms=android


Microsoft Azure - php

Question: Como fazer com que o Microsoft Azure capture meus erros?

Eu atualmente estou tratando os erros com essa função:
<?php

/**
  Plugin Name: TESTE
  Description: testando log novo
  Version: 1.0
  Author: Vteste
  Author URI: teste

  -------
  LICENSE: This file is subject to the terms and conditions defined in
  file 'license.txt', which is part of Advanced Access Manager source package.
 *
 */

// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    switch ($errno) {
    case E_USER_ERROR:
        $erro = "My ERROR [$errno] $errstr
\n";
        $erro += "  Fatal error on line $errline in file $errfile";
        $erro += ", PHP " . PHP_VERSION . " (" . PHP_OS . ")
\n";
        $erro += "Aborting...
\n";
        echo $erro;
        exit(1);
        break;

    case E_USER_WARNING:
        $erro = "My WARNING [$errno] $errstr\n";
        break;

    case E_USER_NOTICE:
        $erro = "My NOTICE [$errno] $errstr\n";
        break;

    default:
        $erro = "Unknown error type: [$errno] $errstr, linha:$errline, no arquivo $errfile";
            error_log($erro);
        break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling
function scale_by_log($vect, $scale)
{
    if (!is_numeric($scale) || $scale <= 0) {
        trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
    }

    if (!is_array($vect)) {
        trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
        return null;
    }

    $temp = array();
    foreach($vect as $pos => $value) {
        if (!is_numeric($value)) {
            trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
            $value = 0;
        }
        $temp[$pos] = log($scale) * $value;
    }

    return $temp;
}

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

?>

E utilizo o plugin do Application Insights | Microsoft Azure, porém ele não está coletando nenhum tipo de erro, então gostaria de enviar manualmente como poderia fazer?
Answer: Não tenho certeza, mas creio que seja devido ao:
return true;

Dentro do seu handler no set_error_handler tem o return true;, isto faz ao invés de usar o handler interno ele usar somente o teu "handler", então LOG interno do PHP nunca consegue pegar o erro, porque você esta impedindo.
Para tentar resolver remova o return true;, um detalhe a própria Microsoft disponibiliza uma API para usa do Application Insights, se estiver usando composer pode instalar assim:
require: "microsoft/application-insights": "*"

Note que é necessário estar usando PHP 5.4.2+
Após instalar crie uma chave e adicione este código com sua chave:
$telemetryClient = new \ApplicationInsights\Telemetry_Client();
$telemetryClient->getContext()->setInstrumentationKey('DIGITE SUA CHAVE AQUI');
$telemetryClient->trackEvent('name of your event');
$telemetryClient->flush();

Comment: Funciona com multisite ??
Comment: @KaueAlves multi-dominios ou multi-sites?
Comment: multisites do wordpress
Comment: @KaueAlves não sei afirmar, se o multi-site forem aplicações wordpress diferentes creio que terá que configurar um a um, se for a mesma aplicação com múltiplos domínios talvez não seja necessário.

Microsoft Azure - php


equal row heights for QFormLayout

Question: I am using QFormLayout with QLabels in the left column and various widgets in the right column. On the right, there are either labels, check boxes, combos or line edits. Unfortunately each of there controls has different natural height. But I would like to have each row in the form layout to have equal heights determined by the biggest one (I know in which row it is). Is there any simple way to achieve this? I cannot find anything like QFormLayout::setRowHeight().
Comment: Could you use `QGridLayout` instead? This answer is somewhat (it's about width, not height) related https://stackoverflow.com/questions/34644808/set-vertical-alignment-of-qformlayout-qlabel .
Comment: @V.K., try with `layoutVerticalSpacing` or `layoutFieldGrowthPolicy`, sorry I never used them, but big chance they might help!
Answer: One solution, just assign equal size to all widgets at runtime using the following function:
void setEqualRowHeight(QFormLayout *formLayout, int height)
{
    QWidget *w;
    for(int i = 0; i < formLayout->rowCount(); i++) {
        QLayoutItem *item = formLayout->itemAt(i, QFormLayout::FieldRole);
        if (item && (w = item->widget())) {
            w->setFixedHeight(height);
        }
    }
}

Comment: This will probably expand the input-widgets and break the "natural height" they have on the system. I'd rather set the fixedHeight on the labels only of the form layout.
Comment: From what I understood OP wants the layout-rows to have the same height not the widgets to have the same height but maybe I got it wrong.
Comment: @ymoreau Yes, it will break the natural height. Since OP wants to have equal height for all rows, if we set fixed height for the label, it won't fulfill the requirement.
Comment: I tried setting fixed height for the field widgets (not labels) and it works fine so far. For example checkboxes (field role) are not resized. On the other hand, whan I tried setting fixed height on the labels, the checkboxes are aligned to the top of the row instead of the middle... Well, the accepted solution probably in not a silver bullet suitable for all but for my case it works.

equal row heights for QFormLayout


What does "filters per unit" means?

Question: I met the following phrase here:

first hidden layer contains maxout units with three filters per unit

What does it mean exactly? Maxout unit is neuron, which outputs maximum of inputs, right? And what are "filters"?
Answer: According to the Maxout Networks paper, http://arxiv.org/pdf/1302.4389v4.pdf,

In a convolutional network, a maxout feature map can be constructed
  by taking the maximum across k affine feature maps (i.e., pool across channels, in addition spatial locations).

the number of parameters of a maxout layer is $d\times m\times k$, where $d$ is the dimension of the input, $m$ is the number of maxout units, and $k$ is the number of affine feature maps (filters) per unit.
So essentially, compared to ReLU, a maxout unit replaces the non-linearity $max(0,x)$ with $\max\limits_k W_jx+b_j$ via taking the maximum of $k$ sets of different $W$ (filters).

What does "filters per unit" means?


How can i change the background cell color after the user edited some text

Question: Going from the previous question i had asked that related to color text change after edit. Now it has been requested that i should not highlight the edited text but change the background color.
This is what i want now.

Load existing file with the data to the DataGridView
After loading, DataGridView will populate data
The user will edit text from any cell
After editing the text,
Background color of the edited cell will change color to red,
Only for the edited cell,

How can i change the background color of the edited cell in the DataGridView ?
This is what i tried by changing the background color of the cell.
   private void Gridview_Output_CellBeginEdit_1(object sender, DataGridViewCellCancelEventArgs e)
    {
            DataGridViewCell cell = Gridview_Output[e.ColumnIndex, e.RowIndex];
            cell.Tag = cell.Value != null ? cell.Value : "";

            if (cell.OwningColumn.Name == "ValueOut")
                cell.Style.BackColor = Color.Yellow;
    }

global
    List<DataGridViewCell> dgvc_List = new List<DataGridViewCell>();

Save button
    private void btnSave_Click(object sender, EventArgs e)
    {
         dgvc_List.Add(cell);
                foreach (DataGridViewCell d in dgvc_List)
                {
                    d.Style.BackColor = Color.White;
                }
                dgvc_List.Clear();
    }

Comment: You want to call `dgvc_List.Add(cell)` upon the `CellEndEdit` event, directly after `cell.Style.BackColor = Color.Red;` What you have above will not compile...
Comment: am trying to find a way which will help me clear the color when you click save. am trying to follow up with the example you provided me with
Comment: You should probably read up on some basic c# principals if you don't understand. Like the old saying goes, you definitely cant run before you can walk and probably should not try to walk before you can crawl. Have a look at [this](http://www.homeandlearn.co.uk/csharp/csharp.html) for a fairly thorough beginners guide that you may be able to use to help with certain aspects of the language that you do not yet understand... Persistence is the key! Best of luck...
Answer: You might want to use the TextChanged event ( https://msdn.microsoft.com/en-us/library/system.windows.forms.control.textchanged(v=vs.110).aspx ) to detect whenever the user is changing the content of the TextBox (you might want to apply some logic here to avoid to trigger it when loading the data in the control). When the even triggers, you can then change the Background color of the control ( https://msdn.microsoft.com/en-us/library/s2kh9x59(v=vs.110).aspx )
Answer: Add a new event on CellEndEdit instead:
private void Gridview_Output_CellEndEdit_1(object sender, DataGridViewCellCancelEventArgs e)
{
        DataGridViewCell cell = Gridview_Output[e.ColumnIndex, e.RowIndex];
        cell.Tag = cell.Value != null ? cell.Value : "";

        if (cell.OwningColumn.Name == "ValueOut")
            cell.Style.BackColor = Color.Yellow;
}

This is because you invoke the event before the editing is done, instead what you really want is show a different color when the job is done.
Comment: simply add an event on the button click that iterate every cell of the datagrid and set the color to white:
    private void button1_Click(object sender, EventArgs e)
  {
   foreach (DataGridViewRow r in dataGridView1.Rows)
   {
    foreach(DataGridViewCell c in r.Cells)
    {
     c.Style.BackColor = Color.White;
    }
   }
  }
Comment: I think we are already crossing the 'do it for me' line instead of 'help me understand'...
you have a button right? Add An event to that button when an user click it.
Inside that event iterate every cells of the grid and change its color.
just put the code up there into the event. it's pretty straightforward...
Comment: There is something else that require beginEdit other than changing the color if edited? If not you can remove it. Please flag it as answered if this solved your problem.
Comment: @Donbabbeo agree... Add it to the saveButton_Click method.
Comment: i don't understand here. I have save button, so how do you want me to do it. the user will edit from gridcell and click to  edit and then click save button.
Comment: Both @Donbabbeo and I have explained it in fairly simple terms. What error are you getting? Or is it just not working as expected?
Comment: By the way... i don't seee any updated code, it's always the same here.
Comment: after clearing  my mind a bit, i manged to make it work. thanks guys
Answer: Just to further what Donbabbeo has answered...
I take it you only want to change the background ONLY IF the cell value has actually been changed. Using Donbabbeo's answer will change the BackColor regardless every time editing occurs irrespective of whether the value has changed or not.
I suggest you use both the CellBeginEdit and CellEndEdit events together.
To begin with you need to 'remember' the original value of the cell being edited.
string originalValue; // Define a global outside
    private void Gridview_Output_CellBeginEdit_1(object sender, DataGridViewCellCancelEventArgs e)
    {
        originalValue = Gridview_Output[e.ColumnIndex, e.RowIndex].Value.ToString();
    }

And then when you complete the edit you check back against the originalValue, only changing the background color if changes had actually been made
private void Gridview_Output_CellEndEdit(object sender, DataGridViewCellEventArgs e)
   {
       DataGridViewCell cell = Gridview_Output[e.ColumnIndex, e.RowIndex];
       if (cell.Value.ToString() != originalValue)
       {
           cell.Style.BackColor = Color.Red;
       }
   }

If you still want to check that the OwningColumn.Name is a specific value or any other checks for that matter then add a further if statement after you check against the original value.
UPDATE
Changing the cell colors back to their original should be done exactly as Donbabbeo has described in his comment UNLESS you are dealing with a very large DataGridView and then it would be much more efficient to create a generic list of cells to be added to when the change complets & then when saved iterate only through the List<> to revert.
It would be implemented something like this.
First of all the list would need to be declared outside
List<DataGridViewCell> dgvc_List = new List<DataGridViewCell>();

Once the list is declared you would then add specific cells once you were sure that the value was different to the original and that the the BackColor had been changed.
In saying that the following would then be added directly after the color change in the CellEndEdit event.
dgvc_List.Add(cell);

The list will then continue to grow with every confirmed edit until you were ready to do something with it upon the save method, or whatever other method you wanted really, where you would call the following
foreach (DataGridViewCell d in dgvc_List)
     {
         d.Style.BackColor = Color.White; // Or Any Color
     }
dgvc_List.Clear(); // Clears the list ready to go again

Its a little more to code but much more efficient in the long run.
Comment: how can i clear those colors after clicking save button
Comment: Your code throws an error; Object reference not set to an instance of an object.   on this line d.Style.BackColor = Color.White;
Comment: Did you follow the update including the declaration of the `List` ? An object reference exception means that you have not... Or you are picking pieces and trying to use elsewhere without the correct declarations...
Comment: Have you declared the list outside of your method(s)?


Program runs only at a specific pc

Question: I had to write a program that creates credit card numbers. I wrote 3 classes, the main class, from where i can get the type and the length of the card (eg. Visa 15 digits), the luhn formula and one class where i create the card. From the main class i send the type and the length of the card to the last class. So i started the last class like this (its not all the code, only the first lines):
public class Cards extends Program {

private int[] x = new int[length];
private int[] k = new int[length];
private int length;
private String type;

public Cards(int l, String name) {
    length = l;
    type = name;
}

which is clearly wrong (error at the compile) but the thing is that only my pc (where i also wrote these classes) can run it, without compile error and getting the correct results. I know where the problem is and the other 2 classes are correct but i want to know how is it possible to run at my pc without a problem.
Ps: I used acm package, my jdk is 1.8.0_31 and i wrote them on notepad++
Comment: Are you sure you really compile it? You can be running already compiled code...
Comment: Can you share all your code? both mentions of libik can be valid, but therefore we need to see all of your code
Comment: You aren't running the code you've posted, since it doesn't compile.  You are most likely running an earlier version of it, which didn't have any errors.
Comment: You are right the whole i was running an earlier version of it, thank you all very much for your help!!!
Answer: I have the same version of the JDK, and class Card does not compile.  You are probably executing against a previously compiled .class .  Are you sure your code never was something like:
public class Cards extends Program {

    private int[] x;
    private int[] k;
    private int length;
    private String type;

    public Cards(int l, String name) {
        length = l;
        x = new int[length] ;
        k = new int[length] ;
        type = name;
    }
}

I bet it was!  Try again after removing any file Cards.class in your PC.
Comment: You are right the whole i was running an earlier version of it, thank you very much
Answer: In my compiler it gives "Cannot reference a field before it is defined".
You can define them as:
private int length;
private int[] x = new int[length];
private int[] k = new int[length];

However, that code is not clear because length is assigned in the constructor.
Perhaps it is most clear to write:
public class Cards extends Program {
    private int[] x;
    private int[] k;
    private int length;
    private String type;
    public Cards(int l, String name) {
        this.length = l;
        this.x = new int[length];
        this.y = new int[length];
        this.type = name;
    }
}

Program runs only at a specific pc


Utilizar dados do banco de dados em uma opção select (HTML/PHP)

Question: Com quais ferramentas eu posso integrar o meu banco de dados com um html/php, a intenção é criar um campo do tipo
<select>$opção1</select>
<select>$opção2</select>
<select>$opção3</select>
<select>$...</select>

O que eu tenho em mente é puxar* do banco de dados o nome para colocar no select, seria uma aplicação de registrar uma referencia de determinado produto, a aba select iria informar os fornecedores registrados(através de outra aba) no Banco de Dados.
*puxar com um comando de sql select nome_fantasia from fornecedores;
Comment: este valores serão enviados para um banco de dados depois ? se sim, a resposta escolhida como a melhor não irá te atender, mas posso te explicar isso também e responder caso queira
Comment: Sim, a ideia é que o campo "select" trabalhe de forma a preencher o fornecedor do produto, dessa maneira o produto vai pro Banco de Dados sempre com o nome exato do fornecedor.
Comment: irei te explicar através de uma resposta e você verifica se dará certo, mas antes me responda qual o nome dos campos que guardam os nomes dos fornecedores e os códigos ?
Answer: Simples, faça isso e seja feliz:
     <?php $sql  = mysqli_query($conexao, "select nome_fantasia from fornecedores");?>
            <select><?php
              while($resultado = mysqli_fetch_array($sql)){ ?>
                  <option value="<?=  $resultado['id'] ?>"><?php echo $resultado['campo_do_seu_banco']; ?></option>
                  <?php } ?>
            </select>

Comment: Que show! eu tava quebrando a cabeça pra montar isso! Muito obrigado cara!
Comment: Editei pra ficar mais fácil !
Comment: essa resposta marcada como a melhor não ira inserir dado algum no seu banco de dados, irá apenas listar o select trazendo os dados do banco de dados
Answer: Faça um select na tabela e use um foreach para exibir os nome no select
<select>
<?php
foreach($select as $valor){
?>
  <option value="<?php echo $valor['nome']?>"><?php echo $valor['nome'] ?></option>
<?php
}
?>
</select>

Answer: Para exibir registros do banco de dados dentro do seu select, deverá utilizar um bloco PHP para isso. Desta forma, como irei mostrar abaixo, onde o value = 'nome_fantasia' será armazenada dentro da variável nome_fantasia que é o name do seu select e este value irá enviar o nome do fornecedor
<select class="form-control" name="nome_fantasia">
  <option></option>
    <?php

       $result = "SELECT nome_fantasia FROM fornecedores";
       $resultado = mysqli_query($conn, $result);

       while($row = mysqli_fetch_assoc($resultado)) {
         echo '<option value="'.$row['nome_fantasia'].'"> '.$row['nome_fantasia'].' </option>';
       }
    ?>
</select>

Comment: Funcionou perfeitamente! Muito Obrigado!


Depending on answer sent to different email

Question: I need to add a condition. If the $contact_subject is bigger than the number 50000, it should go to one email-address and if it's smaller it should go to another email-address.
if( $contact_name == true )
{
    $sender = $contact_email;
    $receiver = "firstname.lastname@example.com";
    $client_ip = $_SERVER['REMOTE_ADDR'];
    $email_body = "Name: $contact_name \nEmail: $sender \nAccount Number: $contact_subject \nMessage: $contact_message \nIP: $client_ip \nEmail Sent from website http://www.website.com";
    $extra = "From: $sender\r\n" . "Reply-To: $sender \r\n" . "X-Mailer: PHP/" . phpversion();

    if( mail( $receiver, "Email From Website - $subject", $email_body, $extra ) )
    {
        echo "success=yes";
    }
    else
    {
        echo "success=no";
    }
}

Comment: have you tried just using an if....elseif statement?
Comment: I am not really good at this. I will work with the suggestion from Amal.
Comment: Will let you know asap Amal.
Answer: Use a ternary statement to check if $contact_subject is greater than 50000 and set the $receiver email address depending on the condition.
$receiver = ($contact_subject > 50000) ? 'email@example.com' : 'email@example.com';

The same can be accomplished using an if-else block too.
if ($contact_subject > 50000) {
    $receiver = 'firstname.lastname@example.com';
}
else {
    $receiver = 'email@example.com';
}

Answer: Maybe better way is put size in variable number.
-> config.php
    $size_mail = '5000';

-> mail.php
include "config.php";
if( $contact_name == true )
    {

    if($contact_subject > $size_mail)
    {$receiver = 'email@example.com';}else{$receiver == 'firstname.lastname@example.com';}

        $sender = $contact_email;
        $client_ip = $_SERVER['REMOTE_ADDR'];
        $email_body = "Name: $contact_name \nEmail: $sender \nAccount Number: $contact_subject \nMessage: $contact_message \nIP: $client_ip \nEmail Sent from website http://www.website.com";
        $extra = "From: $sender\r\n" . "Reply-To: $sender \r\n" . "X-Mailer: PHP/" . phpversion();

        if( mail( $receiver, "Email From Website - $subject", $email_body, $extra ) )
        {
            echo "success=yes";
        }
        else
        {
            echo "success=no";
        }
    }

Comment: You guys rock! Thank you so much! I will try that. I am not very good at this so I really appreciate the quick response and help!!


The symmetric S7 acting on a set X with 5 elements

Question: I'm trying to prove that $S_{7}$ can't act transitively on a set with $5$ elements.
Now I know that the kernel of an action must be normal and all the normal subgroups of $S_{7}$ are $1$, $A_{7}$ and $S_{7}$ itself, so it must be one of them.
if its $A_{7}$ I can get contradiction
But I can't see why it can't be trivial, I tried to assume transitivity but I can't see where to use it to get contradiction
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: I don't understand your OP, $S_5$ can act transitively on a set of 5 elements, why can't $S_7$?
Comment: I think its because some of the members of X can go to elements outside of X and then the action is not defined. But that what im trying to prove
Answer: Recall that for $n\ge 5$, representations of $S_n$ other than $1$ and $\mathrm{sgn}$ have degree $\ge n-1$ (by e.g., the hook length formula.)
Thus, if $S_n$ acts on a set $X$ of size $k\le n-2$, the associated representation $\mathbb C[X]$ of $S_n$ must be a sum of $1$ and $\mathrm{sgn}$. Thus, the action of $A_n$ on $X$ must be trivial. But $S_n/A_n$ has size $2$, so if $k>2$ then no such nontrivial action can exist.
Answer: If $S_7$ acts transitively on a set with $5$ elements, a point-stabiliser would have index $5$ in $S_7$, but $S_7$ has no subgroup of index $5$.
Comment: But why are there no subgroups of index $5$? That's the hard part.


What happen if I choose the hyperparameters of a classifier based on lowest generalization error?

Question: In this question, the OP asked about a situation that he/she combined training and test datasets into an agumented dataset and then tuned the hyperparameters for best accuracy and then use the training dataset only to train the final model and check its accuracy on test dataset. My situation is somewhat similar to this question but the difference is that I DID NOT combine training and test datasets to form a agumented dataset. Furthermore, my training and test datasets are completely independent and more importantly test dataset is not subset of training dataset. In fact, my test dataset is given by another research group for the same phenomenon as my training dataset. In my situation I used only the training dataset to train the model for each set of the hyperparameters and then measure the accuracy on test dataset. My objective is oriented towards searching the hyperparameters space to have the highest accuracy on test dataset in each iteration of my search. So, to be precise, my model during hyperparameters tuning did not use test dataset for training task, but I stopped the searching of hyperparameters space, when I achieved the highest accuracy on test dataset. So, my question is: Am I overfitting because my final objective is to have the best generalization accuracy? or Do I have some sort of data leakage because of my hyperparameters searching objective is defined based on having the highest generalization accuracy? Any suggestion or thought is appreciated. Here, I created a pseudo-code to introduce my purpose more easily:
<code>DEFINE HYPERPARAMETERS RANGE

DO HYPERPARAMETER TUNING:

  FOR EACH HYPERPARAMETERS IN DEFINED RANGE:

     TRAIN THE CLASSIFIER BY USING ONLY THE TRAINING DATASET

     APPLY THE TRAINED MODEL ON TEST DATASET AND MEASURE THE ACCURACY

     STOP THE SEARCHING IF YOU ACHIEVED THE HIGHEST ACCURACY FOR TEST DATASET
</code>
Comment: If I have understood the rest of your question, then 'I used only the training dataset to tune the hyperparameters', is misleading. You may have used only the training set to calculate the values of the hyperparameters in the model, but if it is constantly measured on the test set, then the test set is being used to tune. Tuning anything is an iterative process, typically consisting of alternately adjusting and measuring. From my understanding you are using the training set to adjust, the test set to measure.
Comment: The edit reads better now, more consistent with the rest of the question.
Comment: @ReneBt Yes, I use training dataset to train the model and test dataset to measure the accuracy. If it is acceptable, I would pull the set of hyperparameters, otherwise still searching for better accuracy on test dataset.
Comment: @ReneBt Thanks, so what's your opinion now? Am I overfitting or have any data leakage?
Answer: Short answer: yes,  you are overfitting.
Your model has a full set of parameters that are typical split into parameters and hyperparameters (but note that this distinction is somewhat arbitrary). You essentially fitted the former to the training data and then conditional on the testing data for you fit the latter to the "test" data.
How much you are overfitting is hard to say (depends in a complicated way e.g. on the size of the "test" data vs. number/influence of hyperparameters), which is why one should not do that and claim/believe/hope that the test set still truly provides an estimate of the generalization error.
What is generally better is to optimize hyperparameters on a validation set (or via cross validation) and then to use a "true" test set to determine how all the final model choice works.
Answer: Terminology use around sets in model building is inconsistent, so I will refer to Wiki on sets and SE Data Science question where 'test set' is specifically a held out set only assessed at the very end. In this syntax then what we are discussing is the 'validation set', used as an intermediate check on the calibration of the model using the training set (and to tune hyperparameters).

Am I overfitting because my final objective is to have the best
  generalization accuracy?

Thanks to the ever present issue of bias and noise overfitting is unavoidable, it is generally a question of whether it is with acceptable limits.
Imagine the ideal; an unbiased dataset where the only errors in the data are completely random and independent between samples (or any other hierarchy within your dataset). Even in this scenario you will still get cross talk between samples due to random overlap in noise. For example Gaussian noise between independent measurements reduces by the square root of the number of measurements taken. This means that any chance coincidences between the two sets will be selected for using the training set even though the validation set was not used to get coefficients for a model. Now, if random noise is low (or sample numbers quadrupled to halve the noise, since noise cancels by square root) in this scenario the overfitting would be minimal, but this is a ideal dataset far removed from any real world.
If your validation set is simply a subset of your full dataset cordoned off from the training phase then the validation set will share the same biases as the training set. This means that the test set will further ingrain these in the model, but then again it would never be able to identify these common biases if used once. In such as case your cannot predict any generalization capability, because you are not generalising your model on independent data.

Do I have some sort of data leakage because of my hyperparameters
  searching objective is defined based on having the highest
  generalization accuracy?

Yes, biases will leak strongly, especially where the validation set is not completely independent of the training set. In such a case biases will not be controlled for and will give a falsely optimistic performance estimation. Independent random noise will leak but can be minimised by using large sample numbers.
There is no such thing as a blank-cheque generalisation licence for models, you do not prove boundless generalisability. Strictly speaking a model can only be considered validated for generalised use in a situation/population for which an independent data collection has been carried out. Furthermore, the utility is only validated for the limits of the independent set. E.g. a model built using East Asian data will not be able to demonstrate generalisation outside of East Asia. Before knowing if it is relevant to North America it needs validation on North American data. You can replace East Asia/North America with any combo relevant to your model (Male/Female, working age/retired, poor/rich cats/dogs etc). This is because different limits may have different underlying data generating processes (control variables, covariance structures, biases etc) that fall outside the calibrated range, i.e. you are extrapolating the model beyond its expected limits.
Comment: Thanks for your answer. I have to say my test dataset is completely independent from my training dataset. In fact, I could say even the test dataset is given by another research group but it is for the same phenomenon as my training dataset. So, in summary: 1. My test data is independent from my training data, 2. It's not like training a model on East Asia data and expect to generalize it for North America, it's exactly like training a model on East Asia data, that is extracted by me, and generalize on East Asia data extracted by another research group. So, now what's your opinion then?
Comment: The independence of the data helps bolster the chance that fewer biases will leak across as much as if they were simple subsets of one data collection. However, since it is being used to direct choices that influence the settings available to the model, there will be leakages from the test set to the model as described above. Without a further set for a one look confirmation you can't get a useful estimate of how much influence it has.
Answer: Over-fitting is not the problem here, the problem is that the estimate of generalisation performance will be optimistically biased as the test set has been used to tune some aspect of the model (in this case the hyper-parameters).  Whether you will have encountered over-fitting in model selection depends on how many hyper-parameters you have to tune, the sizes of the training and test sets and the sensitivity of your hyper-parameter tuning criterion to over-fitting.  Note that over-fitting in model selection can result in a model that over-fits the data or under-fits it.
I wrote a paper to clarify a few of these issues:
G. C. Cawley and N. L. C. Talbot, Over-fitting in model selection and subsequent selection bias in performance evaluation, Journal of Machine Learning Research, 2010. Research, vol. 11, pp. 2079-2107, July 2010. (www).
Note that there often isn't really a statistical distinction between parameters and hyper-parameters (just one set of parameters for which there is a computationally efficient procedure for finding the optimal values, given the values of a second set, which we call hyper-parameters - see my answer on a related question here).  So the problems with tuning parameters or hyper-parameters on the test data are actually very similar.
Comment: So why the down vote?


Prove $\frac{X^p-1}{X-1}$ for $p$ prime is irreducible in $\mathbb{Q}[X]$

Question: I've been solving problems from my Galois Theory course, and at some point I sated that, given $p$ prime,
$$\frac{X^p-1}{X-1} = X^{p-1}+X^{p-2}+\cdots+X+1$$
is irreducible in $\mathbb{Q}[X]$, because I felt I saw that in my course classes, but I'm not sure how can I prove or if it's even true.
Is it really irreducible in $\mathbb{Q}[X]$ for any $p$ prime? If that's the case, how can I prove it? Any help will be appreciated, thanks in advance.
Comment: This is not an answer (just simple observation) for $p≤5$, the polynomial is irreducible over $\mathbb Q$. This mean the special case is irreducible. So, if for any $p$ the polynomial is reducible over $\mathbb Q$, this should have been true for $p≤5$ as well. But this is a contradiction..It's just the first thing I think about..
Answer: Applying the linear substitution $X=Y+1$ to $f(X)=\frac{X^p-1}{X-1}$ we obtain $$f(X)=Y^{p-1}+{{p}\choose{1}}Y^{p-2}+\dots +{{p}\choose{p-2}}Y+{{p}\choose{p-1}}.$$
By Eisenstein's criterion, the latter is irreducible in $\mathbb{Q}[X]$.


inserting record mysql

Question: I have a method which insert a record into a table as shown below:
public static function AddCategory($categoryName)
    {
        $sql = 'INSERT INTO category(name)
                VALUES(' . $category_name .')';
        $parameters = array('category_name' => $categoryName);
        return DB::Execute($sql,$parameters);
    }

Can anyone tell me if the SQL syntax is correct? Im not being able to insert any record..I can't find my mistake.
Thanks
Answer: public static function AddCategory($categoryName) {
    $sql = 'INSERT INTO category (name)
            VALUES (:category_name)';
    $parameters = array('category_name' => $categoryName);
    return DB::Execute($sql,$parameters);
}

Answer: From my brief observation this line is redundant:
 $parameters = array('category_name' => $categoryName);

You have already specified the inserted value inside query itself. You need only to execute it now.
Answer: I don't exactly understand what you want to do, a valid SQL INSERT sintax is:
INSERT INTO table1 VALUES (value1, value2, ...)
so i suppose your code should be changed into something like:
public static function AddCategory($categoryName)
    {
        //I don't know the real name of the TABLE you want to update, so you have to replace CATEGORIES_TABLE with your table name
        $sql = 'INSERT INTO CATEGORIES_TABLE VALUES(' . $categoryName .')';
        return DB::Execute($sql);
    }

I don't know what DB::Execute does, I suppose it executes a query.
FYI a good way to test this is to add the following line before exectuing the query:
echo "
" . $sql . "
";

Then you take the result printed by PHP and run it on MySQL query browser, it will tell you more accurate details about why the query fails.

inserting record mysql


Create UIPopOver without including Tableview in ios

Question: I want to create two PopOvers when at the time button clicked and textField clicked in the same UIView (not ViewController). In those popovers I need to load separate array values. Is there any way to create them and added to UIView?
I already added one tableview for base UIView, so without using tableviews, how can I create UIpopOvers and load the arrays in those popOvers? How to handle the selected rows?
Answer: This link can help you to create a popover menu.
Or you can take an UIImageView having shape of popover menu and table view in that, it will be  easy to load arrays and to handle selected rows.
I did the same using second method.
Happy Coding!


How to diagonalize a matrix when it has more eigenvectors than eigenvalues?

Question: I'm trying to solve this problem:
Give an example of a matrix A with the following three properties:

A has eigenvalues −1 and 2.
The eigenvalue −1 has eigenvector (1,2,3).
The eigenvalue 2 has eigenvectors (1,1,0) and (0,1,1).

I tried solving it using
 $$A= PDP^{-1}$$
But D is 2x2 and P is 3x3 so multiplication is not possible. How do we deal with cases like this when a matrix has more eigenvectors than eigenvalues?
Comment: How did you deduce that $A$ is a $2×2$ matrix? It can sure have repeated eigenvalues.
Answer: Each eigenvalue appears once in $D$ for each eigenvector it has in your collection of eigenvectors. So in this case, $D$ has $2$ twice along the diagonal. A few requirements, though:

The collection of eigenvectors for any given eigenvalue must be linearly independent
There must still be a full set of eigenvectors, which is to say there must be $n$ of them for an $n\times n$ matrix

As long as these are fulfilled, the are no issues.
Comment: That makes sense. Thank you!
Answer: Since you have three linearly independent eigenvectors the diagonalization is possible. The matrix $P$ whose columns are the eigenvectors serves as the engine in the process of $$P^{-1}AP=D$$
The matrix $A$
is found by solving the equations $$AV=\lambda V$$ for given eigenvalues and eigenvectors.
My calculation resulted in $$A=\begin {bmatrix}1/2&3/2&-3/2\\-3&5&-3\\-9/2&9/2&-5/2\end{bmatrix}$$


How Can i control the way the tabels in the admin panel build?

Question: How Can i control the way the tabels in the admin panel build?
i want to make the system more comfortable for the people how will be doing all the content edit in my site.
Like change the way this build -

Matan
Answer: If you just want to style the D7 administrative theme (called "seven") differently, you can create a sub-theme of that theme and then customize. Docs are here: https://drupal.org/node/225125
Once you have a sub-theme, you can add you own css, templates, etc to change the way things look.
Because of the inheritance you get when sub-theming, you only have to add what you need to the new theme. For example, you could just have an .info file and custom css file.


DLL file load failed For Cx_oracle

Question: I'm using Python 3.1.2. I've downloaded cx_Oracle (Windows x86 Installer (Oracle 10g, Python 3.1)). I'm using Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64-bit.
I'm trying to access a remote Oracle server. I haven't installed any Oracle client. However, I use SQLTools 1.5.0, which I manually copy-pasted from some place.
I came to know cx_Oracle needs a DLL file from an Oracle client to access a remote database, so I copied all the DLL files from the folder of SQLTools to a location. I added the location where I kept the ora.dll into the system's environment variable (PATH and ORACLE_HOME). But it doesn't seem to work. I get the same error:

ImportError: DLL load failed: The specified module could not be found.

I'm missing something. Will this manual work do the job or do I have to install an Oracle client?
Comment: just having the same problem, seems you do need a local oracle client installation, see http://stackoverflow.com/questions/1711408/help-installing-cx-oracle
Comment: Why are you copying .DLL files around?  Why aren't you running the proper installers?
Comment: Because I don't have the rights to install in my computer. Will the proper installer do the job??
Answer: The Oracle client isn't an installer, but a series of zip packages. Download the appropriate Instant Client from this here (http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html), unzip them, stick them on your C drive or anywhere you prefer, and add it to your LD_LIBRARY_PATH and ORACLE_HOME env vars.

DLL file load failed For Cx_oracle


Is every conformal diffeomorphism isotop (or homotop) to an isometry?

Question: Assume that $M$ is  a  compact simply  connected Riemannian manifold and  $f$ is a  conformal  diffeomeorphism of  $M$. Is it true  to  say that  $f$ is  homotopic (or  isotopic) to  an  isometry of  $M$?
What would  be the  answer  if  we drop the  simply  connected assumption?
Answer: I don't think that this can be true in the form you state it. The point is that you can replace the given metric on $M$ by any conformal rescaling without changing the the conformal diffeomorphisms. However, a generic conformal rescaling of a given metric on $M$ should not admit any isometries. So you would end up with the statement that any conformal diffeomorphism is homotopic to the identity.
Comment: If you are just looking for an explicit manifold, you can take an even dimensional sphere $S^{2n}$. Now take a smooth function $f:S^{2n}\to\mathbb R$ and define $g:=e^fg_0$, where $g_0$ is the round metric. Then any conformal transformation for $g_0$ is a conformal transformation for $g$. So in particular, the antipodal map is conformal and not homotopic to the identity. If $f$ is sufficiently generic, then $g$ will not have any isometries.
Comment: This is a completely different quesiton, since it compares diffeomorphisms to conformal diffeomorphisms rather than conformal diffeomorphisms to isometries.  I don't known the answer, but generic conformal classes don't have conformal diffeomorphisms apart from the identity.
Comment: Thank you for  your answer. What is  an  explicit example  of  a simply  connected   Riemannian  manifold $M$ with trivial isometry but $M$ possess a  conformal  diffeomorphism not homotopic to identity?
Comment: What  would be the answer if  we change the  question as follows: Is every orientation preserving diffeomorphism  homotopic to  a  conformal diffeomorphism.
Answer: It is known that if the group of conformal transformation of a compact manifold is compact, then it is conjugate to a group of isometries, and if it is not compact, then the manifolds is the sphere with its standard conformal structure (Lelong-Ferrand Obata).
Assume that the manifold is not conformal to the sphere, then any conformal map is an isometry of another metric conformal to the first one. But perhaps the manifod has no isometry at all ; for instance it is easy to construct a metric on the 2-sphere with no isometry, but this metric has a lot of conformal maps.
In the case the manifold is (conformal to) the sphere, the group of conformal transformations is the Möbius group which contains the groups of isometries as a retract, so every conformal transformation is isotopic to an isometry.
Comment: Take a metric $g$ on the sphere without isometries (the boundary of a potatoe does the job). This metric is conformal to the standard one $g_0$, let $F$ be the  conformal  transformation $g\to g_0$, and  $C$ is any conformal map of the standard sphere.  Then $F^{-1}\circ C \circ F$  is a conformal transformation of $g$. If $C$ is of degree $-1$, yo have your example.
Comment: thank you for your  answer. What is  that metric  on $S^2$ and  what  is  a  conformal  diffeomorphism (of course of  degree $-1$) which is not  homotop  to the  identity?


Including Web Fonts With Moovweb

Question: I am trying to include Google Fonts in my Moovweb site via @import url(http://fonts.googleapis.com/css?family=Oswald:400,300,700);  and then including the tag 'Oswald' in font-family.  I have done this before with static sites, but for some reason it is not working for me.  I am not sure if I am placing the code in the right file?  Seems like a simple fix, if someone could provide some guidance it would be greatly appreciated.
Comment: To answer my own question, I added insert_top("link", rel: "stylesheet", href:"http://fonts.googleapis.com/css?family=Oswald") to the html.ts file and then included the font in font-family of _base.scss. If this is not best practice please advise.  Thanks again.
Comment: Hey Danny, just FYI it's encouraged to answer your own question as you would any normal stackoverflow post (there's an "Answer Your Own Question" box you should have). See http://stackoverflow.com/help/self-answer
Answer: Why are you using @import ? Can you not create the link tag on head of your file?
<code><link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
</code>
Is there any message on the console?

Including Web Fonts With Moovweb


Como declarar e usar métodos que estão na mesma classe

Question: Boa tarde. Gostaria de saber como é feito a declaracao e a utilizacao de métodos dentro da mesma classe. Por exemplo, em uma classe há 2 métodos, a qual 1 método utiliza o outro.
Por exemplo:
class ClasseEMetodo:
    def retorna_valor:
        return '10'

    def imprimi_valor:
        print('O valor é {0}' retorna_valor())

# chamada
var = ClasseEMetodo
var.imprimi_valor()

O erro mostrado é:
    def retorna_valor:
                     ^
SyntaxError: invalid syntax

Comment: Basicamente https://pt.stackoverflow.com/questions/176543/por-que-temos-que-utilizar-o-atributo-self-como-argumento-nos-m%C3%A9todos , e no teu caso tens mais uns erros de sintaxe à mistura: https://repl.it/repls/StarryIndianredOs
Answer: class ClasseEMetodo:
    @classmethod
    def retorna_valor(cls):
        return '10'

    @classmethod
    def imprimi_valor(cls):
        print('O valor é {0}'.format(cls.retorna_valor()))

# chamada
var = ClasseEMetodo
var.imprimi_valor()  # O valor é 10

Comment: O que é o (cls)?
Comment: `cls` -- `ClasseEMetodo`. `print(cls)  # `, `print(ClasseEMetodo)  # `


How to pick the vectors with specific number of elements?


When debugging unittest in visual studio the debugsession just quits

Question: I've had this occur to me daily now. I am debugging my libraries using unittests. My libraries are all code projects inside a single solution.
So I'm stepping through the code and all of a sudden it just continues as if I would've pressed F5, which I didn't.
Is this a bug or is there something I'm missing here? Anyone else experiencing this problem?
I'm using the Microsoft.VisualStudio.QualityTools.UnitTestFramework 4.0 with Visual Studio 2010. My libraries are all written in .Net 3.5.
Comment: Does it happen when using keyboard shortcuts?  There was a bug where hitting a key would cause a toolbar button to be "clicked".  WAG, and it only ever happened to me when typing in the WF designer...
Comment: Yes, it happens when I press F10 to go to the next step.
Answer: This is a bug that was present in VS2008 SP1.  There was a post-SP hotfix that solved it.  Unfortunately, it doesn't look like they checked the fixed back into the trunk, the bugs came back in VS2010.  This is not uncommon for hotfixes.
Well, no quick fix or well documented workaround I'm afraid.  You could post to connect.microsoft.com to remind them about it.  Hopefully it will be covered by SP1, you might want to consider moving back to VS2008 while you wait for that.


Show that vectors are linearly independent vectors for each value of a

Question: "Show that $(a \ \ 3)$ and $(2 \ \ \ 1-a)$ are linearly independent vectors for each value of a"
This means that given scalars $C1,C2$ their scalar sum should equal $0$:
$aC1 + 2C2 = 0$
$3C1 + C2-aC2 = 0$
$\Rightarrow 6C1 - aC1 + a^2C1 = 0.$
Don't know what I need to do now or if this is wrong already.
Comment: Yes, it's fine. Now factor that last result. If $C_1 \ne 0$, then what must be true? Finally, assuming the base field is $\mathbb{R}$, what can you conclude?
Comment: Regarding $a$ as an unknown constant, you have two unknowns, $C_1$ and $C_2,$ and two equations. Solve for $C_1$ and $C_2.$ Your turn.
Comment: Ah which means that  $(6 - a + a^2) = 0$, but that has no real solution?
Comment: Right -- check the discriminant.
Comment: Which is negative so it has two complex answers, what do I do with this fact?
Comment: Then for real $a$, $(6 - a + a^2) \ne 0$. But you know the product
$$C_1(6 - a + a^2) = 0$$
If a product of two quantities is zero, but one of the quantities is not equal to zero, then ...
Comment: Then  $C_1$ is obviously 0? I still don't understand how that is proof :/

Edit: So because both  $C_1 $ and  $C_2 $ should not both be zero, there  will be no solution which means that they are linearly independent for any a?
Comment: You are trying to prove that $C_1$ and $C_2$ must _both_ be zero. You've shown $C_1 = 0$. Plug that back into the first equation.
Answer: Your approach is workable. As for the comment where you got $\Rightarrow$ from one solves the first equation for $C_2 = -aC_1/2$ and inserts that in the second equation. What you're basically doing here is a proof by contradiction - you assume that there is a (non-trivial) linear combination of the vectors that's $0$.
The requirement is also $C_1$ and $C_2$ should not both be zero. You know that if one is zero the other must be zero for the sum to be zero. So you basically know that this requires $C_1\ne 0$. So you can divide both sides with $C_1$ and get the equation:
$$\left(a-{1\over2}\right)^2 + {23\over4} = \left(a-{1\over2}\right)^2 - {1\over4} + 6 = a^2 - a + 6 = 0$$
Which isn't possible with real $a$ since $(a-1/2)^2\ge 0$ and $23/4>0$ so the LHS (left hand side) is certainly greater than zero and not equal to zero. Now as we see that the equation is certainly false for all $a$ we have a contradiction an we can conclude that our assumption that theres a (non-trivial) linear combination is false.
That is whatever value of $a$ we have no (non-trivial) linear combination of the vectors that's the null vector.
Comment: What is LHS? So this means the equation can't be 0 for any real a, so what do I do with this fact?
Comment: LHS=Left Hand Side
Comment: The equation is a consequence of the assumption that $C_1$ and $C_2$ are constants to form a linear combination. This puts an requirement on $a$ that is impossible to fulfill. This means that there can't be such a linear combination. The equation is an equation for which values of $a$ the vectors become linearly dependent, without any solution it will be linearly independent for all $a$.


Finding the length of the shortest ladder

Question:
A wall 8 feet high is 1 foot from a house. Find the length $L$ of the
  shortest ladder over the wall to the house. Draw a triangle with
  height $y$, base $1 + x$, and hypotenuse $L$.

The shortest ladder is placed straight up close to the wall. It has length $8+8=16$ for going up and down. Does this even need calculus? Or have I misunderstood the problem?
Comment: @learnmore. Not quite. You need $L^2 = {(1+x)^2(x^2+64)\over x^2}$
Comment: This probably isn't the OP's fault, but I can think of at least three different scenarios given the poor wording of the question.
Comment: You've misunderstood. I think the ladder has to be a single line. Otherwise you could do it with length 9 - straight up the wall and then horizontal to the house. You don't have to reach the house at ground level.
Comment: I think you need to consider $L^2=1+x)^2+8^2$ and find maxima of that
Comment: $L^2=(1+x)^2+y^2$ and $y:(1+x)=8:x$
Comment: @MattG88 and $y=8(x+1)/x$
Comment: @ScottBurns Yes ;-)
Answer:
The triangles $ABC$ and $AB'C'$ satisfy the relation
$$
\frac{y}{1 + x} = \frac{8}{x}
$$
So that
$$
y = \frac{8}{x}(1 +x) \tag{1}
$$
The length of the ladder (red line) follows from
$$
L^2 = (1 + x)^2 + y^2 \stackrel{(1)}{=} (1 + x)^2 + \frac{64}{x^2}(1 + x)^2 = (1 + x)^2\frac{x^2 + 64}{x^2}
$$
Call $f(x) = L^2$, and note that minimizing $f(x)$ is equivalent to minimize $L$, therefore we want to find the minimum of
$$
f(x) = (1 + x)^2\frac{x^2 + 64}{x^2}
$$
Which can be done by solving the problem
$$
\frac{df}{dx} = 2\frac{-64 - 64 x + x^3 + x^4}{x^3} = 0
$$
whose solution is $x = 4$. It is easy to see that for this value $f$ has a minimum since
$$
\left.\frac{d^2f}{dx^2}\right|_{x = 4} = \frac{15}{2} > 0
$$
The length of the ladder is then
$$
L = \sqrt{f(4)} = 5\sqrt{5}\;{\rm ft}
$$
Comment: I prefer the square root form. It is easier to solve, and its derivative, though seemingly difficult,  can easily be obtained by using the product rule and the power rule.
Answer: If the distance of the bottom of the ladder from the wall is $x$, then the distance from the house is $x+1$ and the height at which the ladder hits the house is $8\frac{1+x}{x}$. So the length of the ladder must be:
$$L=\sqrt{(1+x)^2 +8^2\frac{(1+x)^2}{x^2}}=\frac{1+x}{x}\sqrt{x^2+8^2}$$
Wolfram alpha says the derivative of this is:
$$\frac{x^3-64}{x^2\sqrt{x^2+64}}$$
Which means the minimum must be at $x=4$ and $L=5\sqrt{5}$.


people use thank you instead accepting answer

Question: I have notice that there is some people who uses thank you instead of accepting an answer
https://magento.stackexchange.com/users/45390/er-sarvesh-v-tiwari?tab=questions
This guys has 38 question and not a single answer is accepted
I have recently give one answer to this user
How do I" Pass variable between .phtml files?
He uses thank you instead of accepting my answer.
What should we do with this type of situation, and it is also not good thing for MagentoSE
I think once they got solution they need to accept someones answer or Else they have to put their own answers
Comment: *I am your father* :D
Comment: thanks you :) posting this question :D
Comment: I'm just starting to answer questions on here and am also noticing that marking an answer accepted seems to confuse people :)
Answer: One thing is clear. You cannot force people to accept answers if they don't want to.
But you can encourage them (but avoid nagging) by leaving a comment under the question or under the answer that should be accepted telling the OP to mark the answer as accepted.
That't the best you can do about it.
Comment: Yes I have done the same But not get the reply from that man and even he is not accepting anyones answers , its strange thing that I have notice
Comment: ok. I will send him a message, but that doesn't mean it will get the problem solved.
Comment: Ok, thank you  I appreciate your quick response
Comment: That's their choice to either accept or give only thank you.
Marius
Answer: It would be nice from stackexchange to send a reminder to those users like Amazon or eBay does?

:-)


Excel VBA: How to get input from user and compare exact match in column D?

Question: Excel VBA: How to get input from user and compare exact match in column D if a match found highlight that found match  automatically in column D? Is it possible by using Excel 2013?

Get input from the user  if a exact match found in column D
highlight that value in column D (value must be type Variant)
If no match found an alert msg(Not Found)
Wants to clear the input text box automatically for next user input

please help this will very helpful for me....
Comment: Pure code-writing requests are off-topic on Stack Overflow -- we expect
questions here to relate to *specific* programming problems -- but we
will happily help you write it yourself! Tell us
[what you've tried](http://stackoverflow.com/help/how-to-ask), and where you are stuck.
This will also help us answer your question better.
Comment: What have you done so far...
Comment: I'm new for programming that's why i'm seeking help from talented programming  peoples like  gizlmeier. Help me if u can don't criticize JFS
Answer: By exact match you are talking about case sensitive matching, aren't you? If so this should do it:
<code>Function findValue()

Dim Value As Variant
Dim Sheetname As String

Value = InputBox("Enter Value:", "Input")

Sheetname = "ENTER SHEETNAME HERE"

'Sheets(Sheetname).Columns("D:D").Select
Dim Cell As Variant

'Search in Column D | MatchCase True = case sensitive
Set Cell = Sheets(Sheetname).Columns("D:D").Find(What:=Value, After:=Sheets(Sheetname).Range("D1"), LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=True, SearchFormat:=False)

If Not Cell Is Nothing Then

    'Value is found, Highlight Cell
    Sheets(Sheetname).Range(Cell.Address).Interior.ColorIndex = 4
Else

    'Value Not found
    MsgBox "Not Found"
End If
End Function
</code>
Otherwise you have to change the MatchCase option to False
Comment: gizlmeier Thanks For your Help And I'm Happy to inform you that i created an vba app in my own with your code as reference... :-)
Comment: Thanks for your great help buddy.. and i got a run-time error type mismatch in line 13.. pls help to solve it  ... my sheet name is sheet1 cell address is full D column
Comment: This is weird, the code works fine for me. Could you give any more info of where exactly the code fails?
Comment: No you used it wrong, the Sheetname variable is for the name of your Worksheet, default Worksheet name is Sheet1 for Example

And the line inside the If (Sheets(Sheetname).Range(Cell.Address).Interior.ColorIndex = 4) Should stay as it is, you may only change the ColorIndex
Comment: Oh what are the things i want to change in that code to make it work??? i'm very new for excel but its requires for my new job so pls help to solve it gizlmeier...
Comment: You could just tell me your Worksheet name and how the found cell should be highlighted and I modify the Code for you