Why does Visual Studio use xchg ax,ax

Question: I was looking through the disassmbly of my program (because it crashed), and noticed lots of
xchg    ax, ax

I googled it and found out it's essentially a nop, but why does visual studio do an xchg instead of a noop?
The application is a C# .NET3.5 64-bit application, compiled by visual studio
Comment: are the bytes associated with these instructions the same? nop should be hex 90. is xchg ax,ax a 2 byte instruction?
Comment: This turned out to be a question with a bit more nuance than I originally thought (or remembered anyway).
Comment: hey can you tell me how to look at assembly code like yours. i'd like to see how a simple prgoram is converted to assembly. thanks
Answer: On x86 the NOP instruction is XCHG AX, AX
The 2 mnemonic instructions assemble to the same binary op-code. (Actually, I suppose an assembler could use any xchg of a register with itself, but AX or EAX is what's typically used for the nop as far as I know).
xchg ax, ax has the properties of changing no register values and changing no flags (hey - it's a no op!).

Edit (in response to a comment by Anon.):
Oh right - now I remember there are several encodings for the xchg instruction.  Some take a mod/r/m set of bits (like many Intel x86 architecture instructions) that specify a source and destination.  Those encodings take more than one byte.  There's also a special encoding that uses a single byte and exchanges a general purpose register with (E)AX.  If the specified register is also (E)AX then you have a single-byte NOP instruction.  you can also specify that (E)AX be exchanged with itself using the larger variant of the xchg instruction.
I'm guessing that MSVC uses the multiple byte version of xchg with (E)AX as the source and destination when it wants to chew up more than one byte for no operation - it takes the same number of cycles as the single byte xchg, but uses more space.  In the disassembly you won't see the multiple byte xchg decoded as a NOP, even if the result is the same.
Specifically xchg eax, eax or nop could be encoded as opcodes 0x90 or 0x87 0xc0 depending on whether you want it to use up 1 or 2 bytes. The Visual Studio disassembler (and probably others) will decode the opcode 0x90 as the NOP instruction and will decode opcode 0x87 0xc0 as xchg eax, eax.
It's been a while since I've done detailed assembly language work, so chances are I'm wrong on at least one count here...
Comment: x86 has a lot of "shortcuts" for specific registers - `0x90` is " `XCHG` register with `(E)AX` ".
Comment: That would be the disassembler being smart (or dumb, depending on what you wanted it to do).  Do you see both decodes using the same disassembler?  That might be something interesting to look at.
Comment: `XCHG` only operates on `(E)AX`.
Comment: My guess is that the disassembler has access to meta-data that tells it what the original instruction was, but it's a guess.
Comment: Reminds me of the NOP on 360 and 370 machines: "BCR 0,0". BCR is a conditional branch to the address in a register. The first 0 is the condition code mask with all conditionsl masked out, so it BCR 0,0 was "unconditionally, don't branch". The second zero was for register zero; when used in addressing, register zero was always replaced with the value "zero". So the NOP was "unconditionally, don't branch to address 0".
Comment: Also, is `xchg ax, ax` does nothing, why does `xchg bx, bx` map to something else (0x87 0xdb)? Shouldn't it also do nothing? Mighty strange if you ask me.
Comment: @Lasse: Anon is right about this - I've updated the answer to cover the single byte/multiple byte encoding details of `xchg`.
Comment: The multple byte nop could be used to align things in the pipeline could it not?  I seem to remember some mention of this in one of Michael Abrash's optimization articles.  Ack, I guess I get the question necro badge...  I didn't notice the age.
Comment: I can't source it, but I believe that modern Intel x86 processors do actually have a no-register NOP so as to avoid the (wasteful?) overhead incurred from touching the registers unlike the old ones which were originally just symbols.
Answer: xchg ax,ax and nop are actually the same instruction, they map to the same opcode (0x90 iirc). That's fine, xchg ax,ax is a No-Op. Why should one waste extra opcode encodings with instructions that don't do anything?
Questionable is why you see both mnemonics printed. I guess it's just a flaw in your disassembly, there is no binary difference.
Comment: The question of whether to waste opcode encodings on do-nothing instructions raises some interesting issues, especially in architectures which are specified to trap invalid instructions.  On the one hand, if a significant portion of the opcode space is used by functionally-identical instructions, forbidding the use of all but one such encoding would make the others available for future operations.  On the other hand, doing so could make some dynamic-code-generation scenarios more difficult, and if invalid opcodes are supposed to be trapped, require extra hardware to trap them.
Comment: @supercat: That's a bit different than just declining to define *yet another* opcode that does nothing, isn't it?
Comment: @SamB: Suppose a processor that uses 16-bit instructions defines 256 opcodes to mean "add an 8-bit immediate operand to r0" and another 256 to mean "subtract an 8-bit immediate operand from r0".  The instructions which add zero and subtract zero may be functionally equivalent, but outlawing one of them might complicate code that expects to dynamically modify an "add N to r0" instruction that's used within a tight loop so as to avoid the need to dedicate a register to the addend (or have to load it within the loop). If there were only 255 "add N to r0" instructions...
Comment: ...code which might want to change the value of N to or from zero might have to special-case that behavior, rather than simply being able to store the desired N within 8 bits of the opcode and ignoring the rest.
Comment: @supercat: That's hardly the same as deciding not to invent a whole new encoding just for NOP, though
Answer: Actually, xchg ax,ax is just how MS disassembles "66 90". 66 is the operand size override, so it supposedly operates on ax instead of eax. However, the CPU still executes it as a nop. The 66 prefix is used here to make the instruction two bytes in size, usually for alignment purposes.
Comment: @VioletGiraffe I can't say without seeing your code. For example, often some nops are inserted to align a loop start for faster execution. If you wan to know the answer for your specific case, ask a new question and add the code.
Comment: there are also many other NOPs with different sizes and the compiler can choose the one that fits best http://stackoverflow.com/a/12564044/995714
Comment: Any idea why MSVC emits NOPs in the optimized release build? Does x86_64 require alignment for some specific instructions? The instruction following the `xchg ax, ax` in my code is a simple `movzx`, surely it has no special alignment requirements?
Answer: MSVC puts NOPs in the compiled code for debug builds, generally. This allows Edit & Continue to work.
Answer: I don't know if it has something to do with the question but many Windows functions begin with MOV EDI, EDI. That's also a 2 byte NOP. Two bytes NOP's are useful to hotpatch code, because you can safely replace it with a short JMP.
Reference: http://blogs.msdn.com/b/oldnewthing/archive/2011/09/21/10214405.aspx
Answer: The real question here is; why did the disassembler choose to display it as xchg ax,ax and not nop?
I suspect that this is from 32-bit or 64-bit code and (given that the disassembler displayed xchg ax,ax and not xchg eax,eax) that there's an operand size override prefix intended to make the nop slightly larger (to achieve a certain amount of padding with fewer instructions); and the existence of prefixes has confused the disassembler resulting in xchg ax,ax (rather than nop or o16 nop).

Why does Visual Studio use xchg ax,ax


Non-diatonic chord?

Question: I've done some looking to no avail, so I'm hoping one of you will know the answer to my question. If I'm in a minor key and I play a i, iv, v progression, but later on I change ONLY the i to a major, how is that chord identified? For example, in A minor, if I suddenly played an A major, but still had a D and E minor following.
I don't know what to call it, other than a non-diatonic chord, but something tells me there's probably a name for this type of chord in this situation, as well as other non-diatonic chords. I haven't really studied post-tonal theory, so I wouldn't know where to begin. If someone could point me in the right direction, I'd appreciate it.
Answer: Well, first of all, "chromatic chord" is probably a better term than "non-diatonic". When a composition ends with a major I in an otherwise minor piece, it's called a "Picardy third" or "tierce de picardie". But in the middle of a piece it would generally just be called "modal borrowing". You could also call it a secondary dominant, ie V/iv. The use of a different mode or secondary dominant like this in an otherwise basic tonal progression isn't particularly the purview of post-tonal theory, but in neo-Riemannian theory the move from a minor chord to major with the same root or vice-versa is labelled "P", which stands for parallel.
EDIT TO ADD:
Whether you call it a modal borrowing (just labelled I) or a secondary dominant of iv (labelled V/iv) is to some extent just six-of-one, half-a-dozen the other. It depends on how you hear it or want it to function. If you mostly just hear it as an occasional alteration of the i chord then I'd reflect that by calling it modal borrowing, but if you hear it as making the drive to iv stronger then I'd call it a secondary dominant. Both will probably be somewhat true.
Comment: I think it may be useful if you add suggestions of which modes the chord could be borrowed from and potentially a few other situations where similar things might happen, such as a bIII chord in a major key, or something along those lines.  I think this would help solidify the OP's understanding of the subject more than just label the chord that he is using.  Just a suggestion, I already up voted your answer. I would have answered but you seem to have covered everything I would have mentioned.
Comment: @Basstickler Fair points. In common practice theory of course, modal borrowing always just means the parallel major/minor. There are already a lot of answers on here about modal borrowing in general, but it's a good suggestion. I'll try to sneak some time later to update the answer further.
Comment: I do find that convention to be largely true but you can definitely borrow from other modes even though less common in most settings.  I generally try to format answers to provide everything in one place, which is why I suggest mentioning it.
Answer: That would be called the parallel major chord.  Likewise, in A major, the A-minor chord (or scale) would be called the parallel minor.
In the key of A minor, BTW, the relative major would be C major.
As mentioned in other replies to your question, it also could be thought of as a secondary dominant chord, and in this case written as V/iv.  Although it would be more convincing that way as a dominant-seventh chord (V7/iv), so in the key of A minor this new chord would have the notes A, C#, E, G, and would commonly lead to iv (D minor).  But this really depends a lot on voice leading and cadence!
Answer: A secondary dominant, I think, eh? A is going to act like the dominant of d. It would be like A-d = V-i in d minor, d-e = iv-v in a minor, with d as the pivot chord between the two key centres.
V/iv is the usual way of numbering it.
Comment: it would still be an A of some sort in the key of A of some sort. So it would still be a tonic. Can a tonic be a dominant at the same time?
Comment: Yes. As a matter of fact, this gets into a bit of a grey area: it can be the sign of a transient modulation within a prevailing A tonality; it can also just take on a brief colouristic dominant function within the A tonality (as in the example Matt gave). Multiplicity and ambiguity of function is actually what makes large scale form possible in tonal music. You need to destabilise a tonality in order to modulate from it convincingly (that is, there needs to be some sort of tonal justification in functional tonality). Ambiguity of harmonic function achieves that.
Comment: that means that the next part of the composition will be in D minor.At that point, Em would pretty well be redundant.
Comment: That's why I said colouristic function in Matt's example. Still, think about it: A-d-e... Is it a passage in A minor that is giving some prominence to iv? (And it is doing that - the root movement and leading tone voice leading are very strong.) Or is it a passage in d minor that is starting to move away from d minor? In isolation, without what comes before and after, that would be hard to tell. As part of an unstable passage, it will continue the instability; embedded in purest A minor, it's going to be a little bit of a surprise.
Comment: I agree — it's impossible to analyze without the context, but I think it's hard to imagine an example in a-minor where an A-major chord followed by d-minor doesn't sound like `V/iv`.
Answer: Depending on the context, it could either be considered a secondary dominant or a borrowed chord.
If the I is preceding a iv chord, it is most likely meant to sound as a secondary dominant; that is to say that this chord sounds like the dominant (V) in the key of iv.  For instance, in the case of A minor, A major sounds like V in D minor, so 'A d E a' would be analyzed as V/iv iv V i.
Alternatively, if the chord is not acting as a secondary dominant, it would be considered a borrowed chord.  For instance, some songs in minor keys end with a raised third.  In this case, your chord would be analyzied as I, borrowed from the parallel major.  For instance, in the case of A minor, 'a d E A' would be analyzed as i iv V I.
Comment: as in 'tierce de Picardie'.(Last para).

Non-diatonic chord?


Finding respective Taylor series of function

Question: I need your help with finding the Taylor sequence of $ f(x) =\sin(x) $ at $x_0 = \pi/4 $.
I'm having problem with using the summation notation as the signs are a bit tricky
I got that:
$ T_f(x) = \frac{\sqrt2}{2} + \frac{\sqrt2}{2}x - \frac{\frac{\sqrt2}{2}x^2}{2!}
 - \frac{\frac{\sqrt2}{2}x^3}{3!}  $
Because of the signs switching like this, I can't figure out how can I write the general summation form (i.e. with Sigma notation).
Thank you
Comment: Don't forget that it's $\left( x - \frac{\pi}{4} \right)^k$.  I would say write it as the sum of two different series that both alternate.
Comment: I understand what you say but not sure which series I should use...
Comment: Make all the odd terms one series and all the even terms another series. They will both alternate $(-1)^n$. Then the series for $\sin(x)$ will be the sum of them.
Answer: Hint
Making the problem more general: what is the Taylor expansion of $\sin(x)$ around $x=a$ ?
Let $x=y+a$ and use $$\sin(y+a)=\sin(a)\cos(y)+\cos(a) \sin(y)$$ Use the well known Taylor series of $\sin(y)$ and $\cos(y)$ around $y=0$ and when finished, replace $y$ by $(x-a)$.
Comment: That would create a series expansion for the sine, but it wouldn't be *the* Taylor series around $x_0$, wouldn't it?
Comment: No, since the series will be in terms of $y$ which is $x-a$.
Comment: Oh, I see. You're right. Then this is indeed a nice solution.
Answer: The general formula for the Taylor Series of a function $f(x)$ around $x_0$ is $$f(x)=\sum\limits_{n=0}^{\infty}\frac{f^{(n)}(x_0)}{n!}(x-x_0)^n$$
Recall $\sin(\frac{\pi}{4})=\cos(\frac{\pi}{4})=\frac{1}{\sqrt2}$ to obtain $$\sin(x)=\sum\limits_{n=0}^{\infty}\frac{(-1)^{\lfloor\frac{n}{2}\rfloor}\frac{1}{\sqrt{2}}}{n!}(x-\frac{\pi}{4})^n$$
Answer: Notice that
$$\sin'(x)=\cos(x)=\sin\left(x+\frac\pi2\right),\\
\sin''(x)=-\sin(x)=\sin\left(x+2\frac\pi2\right),\\
\sin'''(x)=-\cos(x)=\sin\left(x+3\frac\pi2\right),\\\cdots$$
and you can write
$$\sin\left(x\right)=\sum_{k=0}^\infty\frac{\sin\left(\dfrac\pi4+k\dfrac\pi2\right)}{k!}\left(x-\dfrac\pi4\right)^k.$$


Como retornar tamanho de vetor com sizeof()?

Question: Este é o código que  estou usando, mas o retorno da função tamVet  não é o tamanho do vetor, e sim o tamanho do ponteiro sobre ele mesmo.
#include <stdio.h>

int tamVet(int *vet){
    int tam;
    tam = sizeof(vet) / sizeof(vet[0]);
    return tam; //Está retornando 1 invés de 10, o número de elementos de vetor[10]
}

int main(){
    int vetor[10];
    printf("%i", tamVetor(vetor));
    return 0;
}

Comment: "Como retornar tamanho de vetor" eu acho uma pergunta interessante. Mas no seu caso, pq faz questão que seja com `sizeof()`?
Comment: Desconheço outra forma de pegar tamanho de um vetor
Answer: Em C, assim que você passa um array para uma função o array "decai" para um ponteiro para seu primeiro elemento. O comprimento do vetor é esquecido e a única maneira de passá-lo pra função é usando um argumento separado. Por exemplo, o main recebe um argumento argc além do vetor argv.
No seu caso, se a única coisa que você quiser fazer é criar algo pra ter que digitar menos acho que dá pra resolver usando macros ao invés de funções.
#define TAMVET(vet) (sizeof(vet)/sizeof((vet)[0]))

Comment: Entendi. Não conhecia esta forma hugomg, obrigado
Comment: Tome *bastante* cuidado com macros. É extremamente fácil dar um tiro no pé com eles.
Comment: Certo, estou estudando sobre eles agora :)


How to get values of dynamic textareas in vue js?

Question: I am creating text fields inside the v-for loop Now confusion is how I can get values of all these inputs those are not fixed number input so I can set their variables in data()
How i am rendering inputs
  <ion-list>
        <ion-item v-for="(worker, index) in this.workers" :key="index">
          <ion-label text-wrap>
            {{ worker.name }}
          </ion-label>
           <ion-textarea placeholder="Enter Detail..."></ion-textarea>
        </ion-item>
      </ion-list>

        <ion-button
          shape="round"
          expand="full"
          @click="submit"
          style="--background: #272727;text-transform: capitalize;font-size: 16px;color: #ffc946;"
        >Submit</ion-button>

In submit() method i want to fetch values of all these textareas
Answer:
In the template part you shouldn't use this. Actually, Vue should output at least a "warning" for that, if not an "error"
Try to think in terms of dataset & -structure. You don't want to "get the data from an input field" - you output an input field based on the data you have. This might sound like a "zen koan", but it's easier to grasp Vue (and other reactive frameworks) with this approach.

Here's a small to show:

Vue.component("InputField", {
  props: ['id', 'value'],
  computed: {
    fieldValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit("update:value", val)
      }
    },
  },
  template: `

    {{ id }}
    <input
      type="text"
      v-model="fieldValue"
    />

  `
})
new Vue({
  el: "#app",
  data() {
    return {
      formFields: [],
    }
  },
  methods: {
    addField() {
      this.formFields.push({
        id: this.formFields.length + Date.now(),
        value: null,
      })
    },
  },
  template: `

    <button
      @click="addField"
    >
      ADD FIELD +
    </button>
    {{ formFields }}

    <input-field
      v-for="field in formFields"
      :key="field.id"
      :id="field.id"
      :value.sync="field.value"
    />

  `
})

Answer: Here we can get the input value using the v-model directive and debounce this value after 250 milliseconds in the button
<ion-list>
        <ion-item v-for="(worker, index) in this.workers" :key="index">
          <ion-label text-wrap>
            {{ worker.name }}
          </ion-label>
           <ion-textarea placeholder="Enter Detail..." v-model="input"></ion-textarea>
        </ion-item>
      </ion-list>

        <ion-button
          shape="round"
          expand="full"
          @click="submit"
          style="--background: #272727;text-transform: capitalize;font-size: 16px;color: #ffc946;"
        >{{buttonText}}</ion-button>

Script file/tag:
export default{
data:{
input: "",
buttonText: "Submit xyz"
},
watch: {
   input: _debounce(function(){
   this.buttonText = this.input !== "" ? "Submit" + this.input : "Submit";
  }, 250)
 },
}


How to close a QDialog at click outside and close at click a sub-widget?

Question: I have a little problem. I'm trying close a QDialog when I press a QPushButton(child) or at click outside of the QDialog.
I dont want close with connect in the function of the button. I want close when the QDialog detect a child clicked.
Sry my english.
thanks a lot.
Dialog.py
# coding=utf-8
from PyQt4.QtCore import Qt
from PyQt4.QtGui import *

class SimpleDialog(QDialog):

    def __init__(self, title=None):
        QDialog.__init__(self)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.Tool)
        self.setMinimumWidth(280)

        self.__inWidget = []
        self.__textColor = "#212121"

        font = QFont()
        font.setFamily("Roboto Medium")
        font.setPixelSize(20)

        self.__title = QLabel()
        self.__title.setFont(font)
        self.__title.setWordWrap(True)
        self.__title.hide()
        if title:
            self.setTitle(title)

        self.__vLayout = QVBoxLayout()

        textLayout = QVBoxLayout()
        textLayout.setAlignment(Qt.AlignTop)
        textLayout.addWidget(self.__title)

        contentLayout = QVBoxLayout()
        contentLayout.addLayout(textLayout)
        contentLayout.addLayout(self.__vLayout)

        widget = QWidget()
        widget.setLayout(contentLayout)

        main = QVBoxLayout()
        main.addWidget(widget)

        backBoard = QHBoxLayout()
        backBoard.addLayout(main)
        self.setLayout(backBoard)

    def focusOutEvent(self, *args, **kwargs):
        self.close()

    def addItem(self, simpleDialogItem):
        """ SimpleDialog.addItem(SimpleDialogItem)
        Agrega un item al SimpleDialog
        """
        if type(simpleDialogItem) == SimpleDialogItem:
            self.__vLayout.addWidget(simpleDialogItem)
            self.__inWidget.append(simpleDialogItem)
        else:
            raise TypeError("Se espera un SimpleDialogItem y se recibio: " + type(simpleDialogItem))

    def setTitle(self, title):
        """ SimpleDialog.setTitle(str)
        Establece el titulo del SimpleDialog
        """
        self.__title.setText(title)
        self.__title.show()

class SimpleDialogItem(QPushButton):
    def __init__(self, icon=None, text=None):
        """ SimpleDialogItem(icon=path, text=str)
        Item utilizado en SimpleDialog
        """
        QPushButton.__init__(self)

        self.__text = QLabel()
        self.__text.setWordWrap(True)

        self.__layout = QHBoxLayout()
        self.__layout.addWidget(self.__text)
        self.setFixedHeight(48)

        self.setLayout(self.__layout)
        if text:
            self.setText(text)

    def setText(self, text):
        """ SimpleDialogItem.setText(str)
        Establece el texto del widget
        """
        self.__text.setText(text)

test.py
import sys

from PyQt4.QtGui import QApplication
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QPushButton, QDialog

from Dialog import SimpleDialog, SimpleDialogItem

class Main(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        b = QPushButton("button")
        b.released.connect(self.hola)

        l = QHBoxLayout()
        l.addWidget(b)

        self.addView(l)

    def hola(self):
        t = "Three line wrapped text goes here making it wrap to next line and continues longer to be here "
        tt = "You'll lose all photos and media."
        ttt = "You'll lose all photos and media."
        sd = SimpleDialog(title="Are you sure?")
        self.item = SimpleDialogItem(text=t, icon="slide_1.jpg")
        self.item.released.connect(self.chao)
        item2 = SimpleDialogItem(text=tt)
        item3 = SimpleDialogItem(text=ttt)
        sd.addItem(self.item)
        sd.addItem(item2)
        sd.addItem(item3)
        sd.exec_()

    def chao(self):
        print "Hola mundo!"

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Main()
    window.activateWindow()
    window.show()

    sys.exit(app.exec_())

This code, no detect focusOut in SimpleDialog :( Any solution?
Comment: If you speak Spanish better post it on http://es.stackoverflow.com/
Comment: You could place only the most important part of your code.
Comment: I try user Qt.Popup how windowFlat but draw a shadow in the window.
Comment: what's MainLayout??
Comment: The MainLayout is a QWidget modified :)
In the test I use a SimpleDialog and add 3 SimpleDialogItem, I want close the SimpleDialog when I press on Item added.
I ask my question in "ES" forum too, but here I can find more entries.
Answer: I want to show you the solution that I found to my problem.
First, how do I close my widget SimpleDialogal click away from it?
I made a small modification at the end of the widget, which allows me to expand this one and manage its entire area.
main = QVBoxLayout()
main.addWidget(...contenido...)

self.fullWidget = QWidget()
self.fullWidget.setLayout(main)
self.fullWidget.setStyleSheet("background-color: RGB(0,0,0,30)")

l = QHBoxLayout()
l.addWidget(self.fullWidget)

self.showFullScreen()
self.setLayout(l)

So, this way I can write the mouseReleaseEvent to detect the top area and when the click is closed.
def mouseReleaseEvent(self, QEvent):
    if QApplication.widgetAt(QEvent.pos()) == self.fullWidget:
        self.close()

Now as a solution to the problem of closing SimpleDialog when pressing the SimpleDialogItem is about writing the mouseReleaseEvent method to with QApplication find the parent and close it
def mouseReleaseEvent(self, *args, **kwargs):
    for widget in QApplication.topLevelWidgets():
        if type(widget) == SimpleDialog:
            widget.close()


How to remove image script if it has no image?

Question: I created a block using views.
The fields has image, title and body.
While the article has no image, it still render out the image script and it make a space before the title.
How do it make the image script disappear if there is no article in its.
Answer: Go to Image field configuration:
Click on No results behavior section.
You will get the option to hide.


Probit model with error term

Question: I'm writing a probit model but I don't know if the error term is written correctly.
I wrote my model like this:
$$\Pr(Y_i=1|X_i)=Φ(x'_i\beta) + ν_i$$
where $v_i$ is the error term. Is this correct?
Answer: Hello Nell and welcome to Cross Validated!
This is not exactly correct.
The model is given by the assumption,
$$\Pr[Y=1|X]=\Phi(X^T\beta)$$
where $\Phi$ is the standard normal CDF.
So in this equation, we do not have an error term because we assume the probabilities are specified like this.
The way this is typically motivated is with a latent variable model,
$$Y^*=X^T\beta + \epsilon$$
where $\epsilon\sim N(0,1)$ is the error term. $Y^*$ is viewed as some auxiliary random variable that we do not observe but for which the binary $Y$ indicates some cutoff. Usually that cutoff will be $0$. So,
$$\Pr[Y=1|X]=\Pr[Y^*>0]=\Pr[X^T\beta+\epsilon>0]=\Pr[\epsilon < X^T\beta]$$
Then using the fact that $\epsilon\sim N(0,1)$ we have,
$$=\Phi(X^T\beta)$$
From this point, we can just use maximum likelihood to estimate this model because for any single observation we essentially consider the estimate of the probability a Bernoulli-p parameter and use the $Y_i$ to tell us if we are estimating $\Pr[Y=1|X]$ or $\Pr[Y=0|X]$.
I encourage you to check out the Wikipedia page on the Probit model so you can read through some more details.

Probit model with error term


cURL request (with Stripe API) slowing down page load times - optimal way to make the request?

Question: I'm making a call at the beginning of each page of my site to Stripe (a payment/subscription service) using its API in PHP. I need to check if at any point the subscription has failed/changed so they lose access to the current page.
The problem is that it seems to be slowing down my pages a lot, causing noticeable issues with JavaScript that's hiding/showing elements. What's the best way to handle this? If I AJAX after the page is loaded then a user could disable JS in their browser and retain access. Is it unusual for a cURL to be noticeably slow?
Answer: There can be various reasons behind why pages are loading slowly and/or the API response time is high. In your use case, it does make sense to retrieve the subscription object beforehand. An alternative approach would be to store subscription status in your DB so that you don't have to make a network request to look it up every time. You can use customer.subscription.updated webhook [0] to keep a track of subscriptions statuses.
To verify if Stripe is the one responding to your GET requests slowly, you can profile your request by logging timestamps before/after the GET to retrieve a Subscription completes. If it is not that high, then your latency might lie elsewhere in your code. Otherwise I'd reach out to Stripe Support with specifics such as the request IDs for those GET requests you made to Stripe's API [1].
[0] https://stripe.com/docs/api/events/types#event_types-customer.subscription.updated
[1] https://dashboard.stripe.com/test/logs
Comment: Thanks for your answer, I'll look into using the web hook


AuthInfoRequired cups overwrites

Question: My problem is basically identical to the following:

http://bbs.archlinux.org/viewtopic.php?id=61826

Put simply, I have a machine in ubuntu trying to connect to another ubuntu machine via a network in order to use the printer attached.  There is no problem printing until I restart the guest machine. Immediately it overwrites the printers.conf file (under /etc/cups/printers.conf).
 It always adds the same line:

AuthInfoRequired username,password

I stop cups and change it to **#**AuthInfoRequired username,password to comment out the command. Start cups. Works great 'til the next shutdown. Then it gets overwritten again.
Googling indicates it may be GTK problem and not CUPS, but I have found no permanent solution to date.
Any suggestions appreciated ....
Answer: You can do it another way too.
Just put "none" in the end of the AuthInfoRequired. It expects something like that:
AuthInfoRequired none
Answer: I've added user and password to the smb share, for example, like this:

smb://joe:not24get@winstation/printer

and it stopped adding this line to printers.conf
If your windows station doesn't require login, just put dummy data:

smb://user:@winstation/printer

AuthInfoRequired cups overwrites


Cisco switch: is it possible to add a user, which would be able to modify a single specific port?

Question: Is it ever possible to delegate control over a single switch's port to an end user? Here's the situation: let's say a company offers colocation service. Each client's server is connected so a port on a switch. If an user wants to create some rules for this port (for example disable access from specific IP addresses), he has to contact tech support.
Are there any ways of delegating user's port (and only this port!) to the user?
Comment: I don't know Cisco well enough to say aye or nay, but typically the co-lo provider offers such functionality in their customer portal or API and then pushes a validated config to the switch, rather than give customers direct access to their management network and too much opportunity to screw up. Or they use the opportunity to sell additional services in the form of a firewall appliance...
Answer: Absolutely. In the TACACS configuration, you can restrict the commands you allow, but you would do better to move that logic into a web application, rather than give your customers direct access into the switches. Simply put, you can create very granular access control using TACACS, but it is very easy to screw-up, and keeping the user-> device -> port -> commands mappings correct in TACACS is harder than keeping it correct in a database-driven application.


PHPStorm Type hinting array of different types

Question: Is it possible in PHPStorm to type hint an array with different object types, ie:
<code>public function getThings()
{
    return array (new Thing(), new OtherThing(), new SomethingElse());
}
</code>
Even declaring them separately before building the array doesn't seem to work.
Comment: PhpStorm does not support type hinting of individual array elements (especially with numeric keys). Those tickets that exist right now are all about incoming data (describe structure of parameter of an array type).  Possible suggestion: `list($a, $b, $c) = $object->getThings();` and then typehint individual variables.
Comment: I'm talking about PHPStorm (an IDE) @ʰᵈˑ
Comment: Yes. "PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, **arrays (since PHP 5.1)**" http://php.net/manual/en/language.oop5.typehinting.php - Unless I totally misread your question.
Comment: Ah ok, [that edit](http://stackoverflow.com/revisions/29165580/2) resolved my confusion with the question. My bad.
Comment: If this objects implement one interface it is bossile. Add phpdoc comment to the method. Phpstorm suggest object methods when you iterate over array of this objects.
Answer: you can use phpdocs in order for phpstorm to accept an array of multiple types like so:
<code>/**
* @return Thing[] | OtherThing[] | SomethingElse[]
*
*/
public function getThings()
{
    return array (new Thing(), new OtherThing(), new SomethingElse());
}
</code>
This technique will make phpstorm think that the array could contain any of those objects and so it will give you type hinting for all three.
Alternatively you can make all of the objects extend another object or implement an interface and type hint that once object or interface like so:
<code>/**
* @return ExtensionClass[]
*
*/
public function getThings()
{
    return array (new Thing(), new OtherThing(), new SomethingElse());
}
</code>
This will give you type hints for only what the classes extend or implement from the parent class or interface.
I hope this helped!
Comment: You can write `@return (Thing|OtherThing|SomethingElse)[]`. Instead of saying there are 3 possible returns types, you say that the only return type is an array, but that the array values can be of these different types. It's a subtle difference.
Answer: This is described in the PHPDoc standards
https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#713-param
<code>/**
 * Initializes this class with the given options.
 *
 * @param array $options {
 *     @var bool   $required Whether this element is required
 *     @var string $label    The display name for this element
 * }
 */
public function __construct(array $options = array())
{
    <...>
}
</code>
Comment: Currently (Sept 2019) that link is not helpful because the list of tags has been removed in that PSR and hasn't been converted to a new PSR yet. However, that is expected to happen at some point in the future.
Comment: This is a good answer to [a different question](https://stackoverflow.com/questions/15414103/best-way-to-document-array-options-in-phpdoc), but not the one asked here ;)
Answer: In PHP, I've seen a very nice way of doing this:
<code>@return array<Thing,OtherThing,SomethingElse>
</code>
IDEs like PHPStorm and VSCode understand this syntax pretty well. Hope this helps.
Comment: It doesn't work from what I can see. This notation defines a single type of collection or key type and item type. More than two arguments do nothing.


Can you piggyback a data response to an Ajax partial rendering

Question: I'm using ajax to update a partial, but i would like to get some data back from the server at the same time.
<code>$('<%=escape_javascript  @my_params.to_json%>');
$("#partial").html('<%= escape_javascript(render partial: "view/partial" )%>');
</code>
gives me the response with both data and partial rendering in it, but it breaks the Ajax render, so the partial is not rendered.
Using Rails 4, ROR.  no errors in the browser or Rails
if i refresh the page i get the result i wanted.
I know this must be easier than i'm making it.
Answer: Assuming that you are using js.erb format for rendering ajax page.
Inside the view partial, write the code

 run your js code here or assign to global js variable

Comment: okay, i tried
$("#magic_box").html('<%= escape_javascript(render partial: "magicacts/magic_box" )%>');
areply= <%=escape_javascript(@my_params.to_json) %>;
Comment: doing something simpler i added areply=3;  I get a successful response, and see the data in the response, but haven't been able to reference it.
Answer: I'll leave this here for edification, but my friends told me that they would disavow me if i abused a cookie this way.  So i switched my implementation, can't afford to lose any friends.  They told me to focus on making the turn around time for the ajax call fast.  I still needed to know when the object had completed rendering so i simply added a hidden element in the partial and i set its size to zero and wait until the partial rendering changes the height from zero.  It was pretty funny to see the interactions with two tabs open to the web page, even though i was planning to use the session ID avoid crosstalk.
Okay, I decided that for my purposes the best way was to put the data in a cookie and just detect when the cookie changed.  This allowed me to change the cookie at the end of the send_data command and both get the data for the image position relative to the other image as well as detect when the send_data completed so i could slide the image into place (over the animated wait image).
it looks like this on the server
<code>   send_data(image.to_blob { self.format = 'png' },
          type: 'image/png',
          disposition: 'inline')
cookies[:duck_data] = { :value => $cookie_data.to_json}
</code>
and this on the client side
<code>wait_for_paint=->
  if $.cookie('duck_data') == 'keep waiting'
    setTimeout (->wait_for_paint()),  250
   else
    my_data= $.parseJSON($.cookie('duck_data'))
    do_ajax_response(my_data)
</code>


Mnemonic for which of $\vee$ and $\wedge$ means OR and which means AND

Question: I can never remember which is which. What's a good mnemonic?
(In the 15 minutes so far this question has existed, I've seen one answer be edited and one comment be deleted for mixing them up, which I guess comes to show how easy it is to do that.)
Comment: Well $\wedge$ already looks like the beginning of a letter A for And
Comment: If you already know $\cup$ is union and $\cap$ is intersection, then $\vee$ is in the same direction as $\cup$ since $x \in A \cup B$ is equivalent to $x \in A \vee x \in B$, and $\wedge$ is in the same direction as $\cap$ since $x \in A \cap B$ is equivalent to $x \in A \wedge x \in B$.
Comment: It goes to show you that sometimes English, for all its shortcomings, is often the clearest way to express something.
Comment: Same question for $\Delta$ and $\nabla$.
Comment: $\lor$ resembles $\cup,$ the first letter of $\cup$nion.... $(x\in A \lor x\in B)\iff (x\in A\cup B)$
Answer: I just remember that $\wedge$ looks like an A for And.
Comment: good one..............
Answer: $\vee$ and $\wedge$ correspond to $\cup$ and $\cap$, respectively, so if you can remember which is union and which is intersection, it may help you remember which is OR and which is AND, because they look similar.  The union symbol looks like a U so that may help, too.
Comment: You could also take the $\lor$ to be like a bucket, which fills itself up with everything on its left side and its right side, similar to a union operation you're talking about..
Answer: the 'or' is smiling cause it's easier to satisfy.
Comment: Briliant..............
Comment: I can only accept one answer, but I think this one is the best suggestion for $\vee$. A nice thing about it is that it suggests a corresponding mnemonic for $\wedge$: it's a frown because it's picky.
Comment: I like how this one and Bram28's don't depend on the language used.
Answer: $\vee$ resembles the letter v, which is the first letter of "vel", the Latin word for "or".
Comment: Has "vee", the latex symbol for it, to do with "vel"?
Comment: Or with velcro, which sticks together?
Answer: I see the $\lor$ as a physical structure that precariously balances on a point, but will easily tip to one side or the other.
Comment: Also, $\wedge$ is a structure standing firm on its left leg **and** it's right leg.  This is an amusing answer. +1
Answer: $\wedge$ looks like A for and, and $\vee$ looks like r for or. Totally subjective.
Comment: You must write your r's pretty weird. ;P
Comment: @Bye_World I mean, if you decrease the first derivative of the left part, and decrease the second derivative of the right part, $\vee$ starts to look like an r. :)
Comment: Fair enough. +1 ;)
Answer: Actually the latex-commands for these symbols are a good mnemonic.
Pronouncing $\vee$ sounds like "wedge", so you type it in, and it gives $\wedge$, the other one. You only need to remember that the wrong one was AND.
Comment: How does pronouncing $\vee$ sound like "wedge"?
Comment: IPA for the English pronunciation of "V" is [vi:]. IPA for the English pronunciation of "wedge" is [wɛdʒ],  I copied these from Wiktionary but these agree with my experience as native English speaker (US).  Typically in English "v" and "w" match with IPA. (Further confusion can arise because although I know little German or Latin, I think "w" in German is pronounced as "v" in English, and "v" in Latin is pronounced as "w" in English.)
Comment: @JonasMeyer The letter $V$ (for $\vee$) is pronounced as "w" in the beginning of the word wedge.
Comment: In what language/dialect?  I'm confused.
Comment: @JonasMeyer In English. How do you pronounce the letter $V$ with the first sound? How do you pronounce $w$ in the beginning of "wedge"? For me this is the same, but you are right, I am not native English, so I could be wrong (also with "w").


Naive Bayes calculation

Question: I was following along with an example given here in which we are trying to classify emails as spam ($S \in \{0, 1\}$) based on the occurrence of the words "buy" ($B \in \{0, 1\}$) and "cheap" ($C \in \{0, 1\}$). From the example, we know the following:
$$
\begin{align}
P(S=1) &= 0.25\\
P(B=1) &= 0.25\\
P(C=1) &= 0.25\\
P(B=1|S=1) &= 0.8\\
P(B=1|S=0) &= 0.067\\
P(C=1|S=1) &= 0.6\\
P(C=1|S=0) &= 0.133
\end{align}
$$
Furthermore, from Bayes rule, we can obtain:
$$
\begin{align}
P(S=1|B=1) = \frac{P(B=1|S=1)P(S=1)}{P(B=1)} = \frac{(0.8)(0.25)}{0.25} = 0.8\\
P(S=1|C=1) = \frac{P(C=1|S=1)P(S=1)}{P(C=1)} = \frac{(0.6)(0.25)}{0.25} = 0.6
\end{align}
$$
Using a naive Bayes classifier, we have that $P(B, C | S) = P(B|S)P(C|S)$. Thus, we find that:
$$
\begin{align}
P(S | B,C) &= \frac{P(B, C| S) P(S)}{P(B, C)}\\
&= \frac{P(B|S)P(C|S)P(S)}{P(B)P(C)} \mbox{  (by assumption)} \tag{1}
\end{align}
$$
We can rewrite this last line as $\frac{P(S|B)P(S|C)}{P(S)}$ by using Bayes rule:
$$
\begin{align}
\frac{P(B|S)P(C|S)P(S)}{P(B)P(C)} &= \frac{P(B|S)P(S)}{P(B)}\frac{P(C|S)P(S)}{P(C)}\frac{1}{P(S)} \tag{2a}\\
&= \frac{P(S|B)P(S|C)}{P(S)} \tag{2b}
\end{align}
$$
Upon substituting, we get:
$$
\begin{align}
P(S=1|B=1,C=1) &= \frac{P(S=1|B=1)P(S=1|C=1)}{P(S=1)}\\
&= \frac{(0.8)(0.6)}{0.25}\\
&= 1.92
\end{align}
$$
which clearly doesn't make sense since probabilities must be between 0 and 1. On the other hand, we can also write:
$$
\begin{align}
P(S=1|B=1,C=1) &= \frac{P(B=1|S=1)P(C=1|S=1)P(S=1)}{P(B=1)P(C=1)} \tag{3}\\
&= \frac{P(B=1|S=1)P(C=1|S=1)P(S=1)}{\sum_{S \in \{0,1\}}P(B=1|S)P(C=1|S)P(S)}\\
&= \frac{(0.8)(0.6)(0.25)}{(0.067)(0.133)(0.75) + (0.8)(0.6)(0.25)}\\
&= 0.947
\end{align}
$$
Why does the second formula work out while the first does not?
Comment: Tim, I was looking at the @Henry's deleted comment late last night and thought the mistake had been caught, but it had not. I have edited the question and expanded out how I "rewrote the last line." I now realize the mistake is, as Henry pointed out in his comment above, in my assumption of independence. I was going off the equation given [here](https://youtu.be/Q8l0Vip5YUw?t=1126) at 18:45, which seems to state that the independence among features is unconditional, when, in fact, it is class-conditional. I will answer my own question to share with other readers.
Comment: Another issue is $P(B)P(C)=\dfrac{1}{16}\not=\dfrac{19}{150}=P(B,C)$.  Conditional independence does not imply unconditional independence
Comment: How exactly did you "rewrite the last line"?
Answer: You can check each of your calculations with this table
<code>S   B   C   Probability
1   1   1   0.12
1   1   0   0.08
1   0   1   0.03
1   0   0   0.02
0   1   1   0.006666667
0   1   0   0.043333333
0   0   1   0.093333333
0   0   0   0.606666667
</code>
This will give you $P(S=1 \mid B=1,C=1) =\dfrac{P(S=1,B=1,C=1)}{P(B=1,C=1)}= \dfrac{0.12}{0.12+0.006666667}\approx 0.9473684$ which is indeed what you found with your second method
This illustrates that $P(B=1,C=1)= 0.12+0.006666667 = 0.126666667$ while $P(B=1)\,P(C=1) = 0.25 \times 0.25= 0.0625$, demonstrating the lack of marginal independence
Comment: Thanks, @Henry. I posted a follow-up question to this one [here](https://stats.stackexchange.com/q/445184/24612) and was wondering if you could take a look at it when you get a chance.
Answer: The assumption made in equation (1) is incorrect. Naive Bayes makes the assumption that the features are conditionally independent, given the class. This is different from marginal independence, which is what I assumed in the denominator of equation (1). Hence, equation (1) should read:
$$
\begin{align}
P(S | B,C) &= \frac{P(B, C| S) P(S)}{P(B, C)}\\
&= \frac{P(B|S)P(C|S)P(S)}{P(B, C)} \mbox{  (by assumption)} \tag{1}
\end{align}
$$
Since the denominator cannot be broken down into the product of two marginal distributions, this is the furthest that this equation can be simplified. Hence, equations (2a) and (2b) are incorrect, which is what led to the incorrect answer 1.92.
Finally, the denominator of equation (3) is also incorrect. Equation (3) should read:
\begin{align}
P(S=1|B=1,C=1) &= \frac{P(B=1|S=1)P(C=1|S=1)P(S=1)}{P(B=1, C=1)} \tag{3}
\end{align}
The equations that follow equation (3) are correct, however, since they don't actually make use of the (false) marginal independence of $B$ and $C$ and instead marginalize out $S$ from the joint distribution of $B$, $C$, and $S$.

Naive Bayes calculation


How is this "United States of Reddit" graph created?

Question: Below is a graph from p. 202 of Christian Rudder's Dataclysm, though it was made by James Dowdell. It illustrates the relationships betweens various top 200 subreddits, which are areas of interest on reddit.com where users can submit links, comments, and votes. These are similar to tags on this site. The size of the subreddit regions represent their popularity. The subreddits are grouped by cross-commenting, and the darker tint represents the percentage of people that stay within that subreddit and don't post to others.
Is this just a standard Voronoi partitioning, with some coloring for insularity, or is it something more involved?
How might one go about making one of these?
Comment: I don't know, but my guess is that it's a *Voronoi cartogram*--one adjusts the point centers (not shown) until each of the Voronoi region areas is proportional to a predetermined value.
Answer: First, I am James Dowdell, so I'm rather uniquely qualified to answer (created an account to answer, can confirm identity if anybody is worried).
The simple answer is indeed what others have surmised: this is a http://en.wikipedia.org/wiki/Voronoi_diagram .  We used the same concept on page 194, where the voronoi sites there are the latitude longitude pairs listed by craigslist.org .
Unfortunately, this knowledge itself isn't actually very useful.  With the Craigslist graph, it's clear what values to use for the sites.  But what magic trick did Dataclysm use to assign x/y coordinates in this graph?
The answer to that is far more involved than most people would expect, and I can't say I recommend redoing what we did.  I bet somebody else here could recommend an approach that gets more or less the same result and is far simpler.
The truth is:
Christian and I went back and forth for over 3 months creating graphs for this chapter, that we could never make work.  But, the results of one approach often fed into the next.

The most critical thing unfortunately involves a technique and some image assets I'm not at liberty to explore or share in any meaningful way, because we may still yet use them somehow.  What I'll say is that we took a complicated http://en.wikipedia.org/wiki/Graph_theory#Graph that we compiled with permission from Reddit's data, involving userids and subreddits, and we played around with this graph and various derivatives of it inside http://gephi.github.io/ (I'm particularly a fan of "OpenOrd" these days).  In fact we got a magnificent image - would have been the highlight of the book if it had been published - but while it would have worked fine on a website it didn't print well in a book - not enough room or resolution.  Christian was originally considering setting it as a fold out in the book, but it just wasn't cost effective for Crown.
However, at this point we had an image that had x/y coordinates for the subreddits and they were at least relatively arranged properly in x/y space. We were also in a hurry because the publish deadline was approaching.  I'm a programmer first and a data guy second, so to accomodate the extremely tight boundaries of the page in the book and the time left on the clock, my instinct was to write a program in Box2D which simulated the boundaries of the page as walls, put an extremely shrunk version of the graph inside, and simulated growing those nodes (not natural for Box2D by the way, it expects rigid bodies that don't change) until everything was flush against the walls and each other.  Nodes grew at a rate proportional to the size of the subreddit they represented, which meant that final sizes would also be proportional in the same way.  I unfortunately don't have a screenshot of the actual run that produced the graph in the book, but the run for an unpublished related graph I attach here: screenshot of box2d program while running
The result of that didn't look very nice at all, but it did give me something very valuable: the voronoi sites.  I took the centroids of the resulting box2d polygons, put them through a standard process, and that's what was used for the graph in the book.  Text labels were applied by hand in photoshop I believe.

Incidentally, the cell coloring was related to a statistic we had developed to form the graph back in (A)
Comment: Welcome to the site. This is close to how I might have tried to do it. Use whatever graph layout to assign xy coordinates to the nodes. (It may be possible in some force based layouts to make the cells approximately the size you want based on specifying edge weights and mass, but I doubt they will be exact.) After creating the voronoi areas of the original graph layout, then I would use a cartogram tool, like [Scapetoad](http://scapetoad.choros.ch/), to make the ending areas proportional to the statistic of interest. This ends up being pretty similar to the program you suggest in box2d.
Answer: It looks more like a word cloud problem with a Voronoi polygon appearance. You need to use the word frequency to decide the location (high frequency means center). As long as the location of the words determined, drawing the Voronoi polygon should not be a big deal.


Designing a dynamic panel

Question: I am new to C# and I want to design a GUI for a image processing application in c#.  I have a very basic rudimentary layout designed as shown below
Here, the image plane is fixed and it will show a live stream video. I have designed all the buttons frame and the side panel. But I do not know how to dynamically change the side panel for each button I click. For example, If I click button1_1, I want some things in the side panel and for button1_2, some other things in it. How do I go about doing it.
EDIT:
Thanks for the answers. I see tab controls is an option. But I want a new panel evertime a click a button. which can further open forms. Is it possible?
Comment: Do you have your heart set on WinForms, or would you consider WPF?
Comment: I heard WPF needs more time. I want to do it winforms since it has a simpler learning curve for other programmers after me who are maintaining my code. since we use different languages in our company.
Comment: You're right, WPF is generally considered to have a steeper learning curve.  On the other hand, it has better data binding and allows for better separation between presentation and application logic.  If you go to the effort of creating a test suite for your application, future maintainers will probably be much more grateful for that than for using WinForms.  Just a thought.
Answer: OK, let's see. It's easy to do with "TabControl" or array of "Panel"s.
1.Do it with TabControl.
You can design GUI in TabControl in multiple subTabs(if you don't know how please ask.). Then you change it in button click event, to make subTab you wanna show(which means make it visiable and not visiable for other subTabs.)
2.Do it with array of panel.
You can use panel[] panels. In button click event, you hide other panels and show the one you want.
Hope answer helps you!
<code>    private void button1_Click(object sender, EventArgs e)
    {
        tabControl1.SelectedIndex = 0;
        tabControl1.TabPages[0].Text = "First";
    }

    private void button2_Click(object sender, EventArgs e)
    {
        tabControl1.SelectedIndex = 1;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        tabControl1.SelectedIndex = 2;
    }
</code>
Comment: Can you provide some tutorials or sources for tabcontrol and array of panels.. Thanks.:)
Comment: Sorry for bading looking.private void button1_Click(object sender, EventArgs e)
{
 tabControl1.SelectedIndex = 0;
}
private void button2_Click(object sender, EventArgs e)
{
 tabControl1.SelectedIndex = 1;
}

private void button3_Click(object sender, EventArgs e)
{
 tabControl1.SelectedIndex = 2;
}
Comment: I edit in my answer, hope you can understand, it just change the SelectedIndex of the tabcontrol.
Comment: Thanks. I implementented it. But I want to display some dynamic heading for each tab. Anyway I can do that?
Comment: @shivoham Yes. tabControl1.TabPages[index].Text="Title";
Comment: Thanks. I did that before. But the title is not getting displayed. Am I missing something here.?
Comment: @shivoham It works fine in my VS..Can you show your parts of code so I can see if something you missed.I made a example in my answer.
Comment: I am using this code to make the tabes invisible. so I am not getting any headings.  tabControl1.Region = new Region(tabControl1.DisplayRectangle);
Answer: you may want to add split container in your form.
Create UserControl for each buttons.
Code for the button click event
<code>//Button1Click Event
    private void button1_Click(object sender, EventArgs e)
    {
        UserControl1 m_UserControl = new UserControl1();
        splitContainer1.Panel2.Controls.Clear();
        splitContainer1.Panel2.Controls.Add(m_UserControl);
    }
    //Button2Click Event
    private void button2_Click(object sender, EventArgs e)
    {
        UserControl2 m_Usercontrol2 = new UserControl2();
        splitContainer1.Panel2.Controls.Clear();
        splitContainer1.Panel2.Controls.Add(m_Usercontrol2);
    }
</code>
you can do this if you want to change what usercontrol display in a panel at run time.
Correct me if i misunderstood your question.
Answer: In WinForms, you could use a tab control and just change the selected tabs index when a button is pressed. More specifically, when its click event is fired. Here is a good tutorial on using the TabControl and here is a tutorial on wiring up click events.
EDIT:
This is a better tutorial.
Since you can't hide the tabs of a tabcontrol without using WPF, you may need to use something else, if you don't like the way they look. A good workaround if you only have a couple of buttons and thus views, would be to use panels. When button one is clicked show panel one and hide panel two, etc. Here would be the code:
<code>private void button1_Click(object sender, EventArgs e)
    {
        pane2.visible = false;
        pane1.visible = true;
    }

private void button2_Click(object sender, EventArgs e)
    {
        pane1.visible = false;
        pane2.visible = true;
    }
</code>
Hope this helps you!

Designing a dynamic panel


connection between $\limsup[a_n, b_n]$ and $[\limsup a_n, \limsup b_n]$

Question: If $\{a_n\}$ and $\{b_n\}$ are sequences of real numbers, what is the connection between $\limsup[a_n, b_n]$ and $[\limsup a_n, \limsup b_n]$?
Is $\limsup[a_n, b_n] = [\limsup a_n, \limsup b_n]$?
I would appreciate a proof or an example (if it exists) that it is not always true.
Thank you.
Answer: In general, $\emptyset\subseteq\limsup\limits_{n\to\infty}[a_n,b_n]\subseteq\left[\liminf\limits_{n\to\infty} a_n,\limsup\limits_{n\to\infty} b_n\right]$.
For $a_n=2^{-n-1}$ and $b_n=2^{-n}$, both sequences converge and the $\limsup$ of the intervals is empty (though this does not happen when $\lim_na_n<\lim_nb_n$). For $a_n=\cos (\pi n)$ and $b_n=1+\cos(\pi n)$, neither of the sequences converges and the other equality holds.
The sequences $a_n=\cos(\pi n)+2^{-n-1}$, $b_n=\cos(\pi n)+2^{-n}$ are an instance when $\emptyset =\limsup\limits_{n\to\infty} [a_n,b_n]\subsetneqq \left(\liminf\limits_{n\to\infty}a_n, \limsup\limits_{n\to\infty} b_n\right)$.


Is my custom twig form error free and secure?

Question: Basically I am displaying a template that is showcasing some data read from the database. The user is allowed to check the table row and click "remove" to delete those from the database. In order to do that I wrote a custom form around a table. Is this form valid? Am I missing anything? I am only asking because I kind of did this on my own and am not sure if I am making any mistakes.
Thanks
<form action="{{ path('main_referral_capture_manage_physicians') }}" method="post">

      Select
      Referring Physician
      NPI Number
      Practice
      Location
      Phone
      Fax
      Email Address

      {% for physician in physicians %}

      <input name="chkphysician[]" type="checkbox" value="{{physician.id}}" />
      {{ physician.physicianFirstName }} {{ physician.physicianLastName }}
      {{ physician.physicianNpi }}
      {{ physician.physicianPracticeName }}
      {{ physician.physicianLocationName }}
      {{ physician.physicianPhone }}
      {{ physician.physicianFax }}
      {{ physician.physicianEmail }}

    {% endfor %}

<input type="submit" value="Remove" />
</form>

Comment: From an OO perspective, I see a bit of redundancy in your naming. You already know your on the physician object, so why prepend your property names with physician, i.e. physicianEmail, physicianNpi, etc?
Comment: good point. I will fix that.
Comment: You are going to make processing your data more difficult than it needs to be by way of how your naming your checkbox. I would just call it "physicianIds", or simply "ids". Then in your controller, the Request will contain an array of ids the user wants to delete (if 1 or more checkboxes are checked).
Answer: I see no inherent issues with your twig form. To validate your twig forms, you can run the lint command:
php app/console twig:lint @SomeBundleName


Difficulty in reading Introduction to Set Theory by Hrbacek

Question: Background: I was reading Karel Hrbacek's Introduction to Set Theory and need help with understanding this snippet:

What I don't understand/need to clarify:

In order to be allowed to use the notion $\{x| P(x)\}$ I need to prove that: $\exists A:\forall x:\big(P(x)\implies x\in A\big)\implies \{x\in A|P(x)\}\textit{ exists and it's unique}$, right?
I've noticed that sometimes it's not mandatory to prove the existence and uniqueness of an object to define it. For instance: When defined what $A\subseteq B$ mean for two given sets $A$ and $B$. So, when is it mandatory to prove the existence and uniqueness of an object in order to define it?

Update:

Why is it even mandatory to prove the existence and uniqueness of an object to define it?
Comment: If I say, "let $x$ be the natural number that is only divisible by 1 and itself", would you say I've defined what $x$ is? Or "let $x$ be the real number whose square is negative."
Comment: [Axiom of specification](https://en.wikipedia.org/wiki/Axiom_schema_of_specification)
Comment: When you discuss the notation $A \subseteq B$, you're not defining a new object at all. You're just introducing shorthand. So I'm not sure how this is analogous.
Comment: @MarkSaving What about my second question?
Answer:
You are quite correct. The famous example is the set $\{x \mid x \not\in x\}$ that stars in Russell's paradox. You can't use that notation to describe a set (in ZF set theory), because you can't prove the existence of a set $A$, such that $x \not\in x \Rightarrow x \in A$.
Defining a relation between objects does not require you to construct an object that represents that relation. The set of all pairs of sets $(A, B)$ such that $A \subseteq B$ isn't a set in ZF set theory, but that doesn't invalidate the definition of the subset relation. I would describe introduction of new relations as definitional.
This is about extending a theory $T$ by adding a new constant symbol $c$ that satisfies an axiom $P(c)$ for some formula $P$ (or maybe, mutatis mutandis, a new function symbol $f$). Such an extension is consistent if $\exists x\lnot P(x)$ cannot be proved in $T$. Such an extension is conservative if adding the axiom $P(c)$ to $T$ doesn't introduce any theorems that do not involve $c$ and were not already theorems of $T$. Such an extension is definitional (my terminology) if $T$ proves $\exists!x(P(x))$. Definitional extensions are conservative and conservative extensions are consistent.

If an extension is not consistent (i.e., if $P(x)$ leads to a contradiction, then the resulting theory is trivial (everything is true). Apart from that, it is a judgment call whether you require extensions to be conservative or definitional. The usual presentations of ZF set theory comprises a sequence of extensions to the theory of a binary relation $\in$ that are either definitional or not conservative.
Comment: How could I learn more about what your answered in question 3?
Comment: @Replik The key concept you want is "extension by definitions."
Comment: So you're saying a class $\{x: \varphi(x)\}$ is a set if $\exists A: \varphi(x) \implies x\in A$ If so, What book can I find more about this fact on?
Comment: @Replik: that's a way of phrasing the axiom of separation or comprehension and is covered in any standard textbook on ZF set theory
Answer: We have really great and important questions here. First, let's see what exactly Hrbacek and Jech are saying in their (really good) book.
As you may know, the Axioma Schema of Comprehension states that

Let $P(x)$ be a property of $x$. For any set $A$ there is a set $B$ such that $x \in B$ if and only if $x \in A$ and $P(x)$.

Informally, this axiom says that, given any set $A$, we can always "seperate" those elements of $A$ that satisfy the property $P(x)$ and collect them to form a new set $B$. So far, so good.
As the authors points out, this set ($B$) is uniquely determined, meaning, any other set $C$ in these conditions will be equal to $B$. Now, we are completely certain that a set in these conditions exists and is unique. Therefore, we can assign them some terminology or notation.
Since this set is uniquely determined, any time we use the notation $\{x \in B \mid P(x)\}$ we all know what set we are talking about (because it is unique, and therefore this notation is not ambiguous).
For the last part of the text from the book, are you familiar with classes? Although it is not an object of the standard universe of sets, some theories regard this as a proper object. Informally, a class is a collection of objects that fails in being a set by being too large. Take for example the class of all sets. Sometimes, we denote this "collection" by $\{x \mid x = x\}$. But we don't want, with this notation, to say that this collection is a set. In fact, one can prove using the ZF axioms that there is no such set.
You may now ask, why did they allow this later notation for sets? Well, they are not wrong, since they advertise that the use of this, let's call it an abuse of notation, must only occur when we are sure that there is a set consisting of those elements. For example, let $A$ and $B$ be any sets. We know that $\{x \mid x \in A \vee x \in B\}$ is a set. One may argue that something is missing, namely when we first write $x$ (as one sees in the axiom schema of comprehension). Although, one can prove that there is a set $X$ such that $x \in X$ if and only if $x \in A$ or $x \in B$, so that use of notation is legit.
Now, for the questions 1-3.

I believe I already answer this above. When we are defining a new object, we must ensure that the object exists (so when we are talking about it we are actually talking about something that exists) and that is unique (in this way, when we talk about it, we all know what we are talking about, and there is no risk of confusion or ambiguity).

Although no one proves the existence of such relation, be aware that $A \subseteq B$ is a shorthand notation for the formula $\forall x (x \in A \Rightarrow x \in B)$. On the other hand, considering $\subseteq$ as a binary relation one can prove that this relation exists (it is proving that some set exists, since a binary relation is a set itself). I believe that the reasons that no one do this is that the proof itself is not hard, it follows directly by applying and manipulating some ZF axioms (note that if we were to do such proves all the time, we wouldn't go anywhere) and, finally, it is such an intuitive result that one would have no big trouble in accepting it.

For this, read again what I wrote in 1.

Remark. For the second point, I don't want to encourage you or anybody to accept results without a proof or, at least, without asking why. This question of yours is really essential, because it is good for a mathematician to have these doubts and to think of these issues. What I meant is that, with time, and with practise we come to accept this results, because deeply we now that a proof is possible and we would be able to do it (with more or less effort).
I hope this helps you with your study.
Second Remark. On the page $9$, the Axiom Schema of Comprehension is introduced. This axiom tells us that, given a certain set, let's say $A$, we can collect those elements of $A$ which satisfy some property and collect them to form a new set. On the next page, there is a Lemma which guarantees that this new set is unique. Therefore, given a set $A$, there is a unique set whose elements are those of $A$ which satisfy the property, let's say $P(x)$. This set, which is uniquely determined, is denoted by $\{x \in A \colon P(x)\}$. In this notation, we first specify where the elements of these sets come from (we write $x \in A$, which means that its elements come from the set $A$), and then we specify the property that they satisfy (we then write $P(x)$).
Later, on page $11$, the author talks indirectly about classes. A class is a collection of elements that satisfy some property $Q$ and we denote classes by $\{x \colon Q(x)\}$. Not every class is a set, but every set is a class. A class is, so to speak, a collection of elements. And intuitively we know that a set is also a collection of some elements. Although, not every class is a set. For example, we may have the class of all sets, which is denoted by $\{x \colon x = x\}$. Since every set is equal to itself, then every set belong to this class. But there is no such set. Hence, when we write $x \in \{x \colon x = x\}$ we are actually just saying that $x$ is a set.
Although, sometimes we find the notation $\{x \colon Q(x)\}$ for sets. For example, $\mathbb{R}^2 = \{(x,y) \colon x,y \in \mathbb{R}\}$. In order to use this notation, we have to make sure that this is well-defined. [Later, in your study of ZF theory, you will understand why $\mathbb{R}^2$ is a set.] This actually means that we can gather all those object of the form $(x,y)$ to form a new set. And this set that we form is unique (that's why that author says that it doesn't depend on the set $A$, and for any set $A'$ constructed in a similar way will be the same as $A$). Hence, this set is uniquely determined and we can associate a notation for them (which is $\{x \colon P(x)\}$). To sum up, if we can collect objects that satisfy a property $P(x)$ in order to creat an actual set, then this set is unique.
Comment: Just to make sure, what I am exactly to prove is $\exists A:\forall x:\big(P(x)\implies x\in A\big)\implies \{x\in A|P(x)\}\textit{ exists and it's unique}$ ?
Comment: @Replik you are asking about the method to prove the existence and uniqueness, right?
Comment: No, I am acquainted with the method. I'm endeavouring to grasp what it is I need to prove. I am newbie so...
Comment: Note that in the formula that you wrote you are saying that if it exists then it is unique, and that is not true in general.
Comment: What you should prove is that if we have to sets in those conditions, then they must be equal
Comment: Note that it is quite different from the formula you wrote. Right?
Comment: What about this snippet: _IF there is a set $A$ such that for all $x, P(x)$ implies $x\in A$ then $\{x\in A| P(x)\}$ exists,_ Shouldn't I prove that?
Comment: May you write in a formula exactly what the authors are encouraging the reader to prove, please?
Comment: $(\forall x (P(x) \rightarrow x \in A)) \wedge (\forall x (P(x) \rightarrow x \in A')) \rightarrow A = A'$
Comment: That's one way to state the uniqueness of an object in order to assign a notation to it
Comment: So, the part saying: "If there is a set $A$ such that for all $x, P(x)$ implies $x\in A$ then $\{x\in A|P(x)\}$ exists" is supposed to be assummed (like an axiom), shouldn't I prove it?
Comment: What are other ways to state the uniqueness of an object?
Comment: You are not probing that $\{x \in A \mid P(x)\}$ exists because that's just a notation for a given set. And this given set, its existence is assured by the Comprehension Schema, the uniqueness you must prove it
Comment: Check this https://proofwiki.org/wiki/Definition:Existential_Quantifier/Unique
Comment: So once I've proved $A=A'$ by consequence $\{x\in A:\varphi(x)\}=\{x\in A':\varphi(x)\}$ meaning that the set $\{x\in A:\varphi(x)\}$ is unique and, therefore, I can introduce a notation for it?
Comment: @Replik exactly! If you don't prove the uniqueness, one may wonder what set that notation would stand for. But by proving the uniqueness there is no doubt about what set that notation would stand for
Comment: But earlier in the book we've proven the set that the set $B$ in the axiom schema of comprehension: $\forall A:\exists B:\forall x:\Big(x\in B\iff x\in A\wedge \varphi(x)\Big)$ is unique and the notation $\{x\in A:\varphi(x)\}$ was introduced so we the author gives notation to the notation now?
Comment: But isn't it redundant to prove again the uniqueness of the set when we knew it is already?
Comment: At page $9$ (I hope we are consulting the same edition) the author introduced the notation $\{x \in A \colon P(x)\}$. Why? The Axiom states that this set exists (so we are actually defining something that exists) and the Lemma before the Definition guarantees that this set is unique (hence we can give it a name and a notation, in this way every time we use that notation we know what set we are talking about).
Comment: In the page $11$ The author talks indirectly about the notion of a class. For example, there exists the class of all sets, but there is no set of all sets. The class of all sets would then be written as $\{x \colon x = x\}$ (the "collection" of the sets which are equal to themselves [all sorts satisfies this property]).
Comment: I get that but for this new notation we are to prove AGAIN the uniquess we proved at page 9, why?
Comment: But, you can prove that there is no set of all sets. So $\{x \colon x = x\}$ is not a set. Sometimes, we can gather some objects that satisfy a property together and collect them to form a set, by which we mean that we have a set $A$ whose elements are those that satisfy that property. In this later page, the author explains that this is set is also unique, meaning that any other set of this elements is equal to $A$.
Comment: Note that the uniqueness of page $9$ is diferente from the uniqueness of page $11$. The difference is just technical and is just a justification for that use of nation. Note that $\{x \in A \colon P(x)\}$ comes from the axiom but $\{x \colon P(x)\}$ does not come from the axiom.
Comment: For example, in English, how would you read $\{x \colon P(x)\}$ and $\{x \in A \colon P(x)\}$?
Comment: So whenever we introduced notation for a notation we should prove a different existence than the one proven before (in case it's not just shorthand)?
Comment: @Replik I'm now understanding your doubt. Allow me to edit my answer. I will add a second Remark at the end with a more detail explanation of this issues.
Comment: I have edited my answer. See this https://en.wikipedia.org/wiki/Class_(set_theory) for more on classes. It may give you a more clear picture of what is a class in ZF theory.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/133575/discussion-between-replik-and-antoine-dibiasky).


How to calculate the characteristic exponents

Question: I'm trying to solve the following question:
Q: Let $Q(t)>0$ be a $C^1$ period function on $\mathbb R$, show that the solution of equation $x''(t)-Q(t)x=0$ is not bounded.
I tried to solve it by the Floquet theory. The above equation corresponds to a $2\times2$ period matrix $A(t)=(0, 1, Q(t),0)$(I don't know how to type matrix ,here 0 and 1 forms the first row, -Q(t) and 0 forms the second row). Then Floquet's theorem tells us that if the characteristic exponents has non-zero real part then the solution of the original equation is unbounded. Is there a good method to calculate the  characteristic exponents? Or there are different method for my original question ?
Comment: As $Q$ is not periodic, how do you intend to apply Floquet theory? You could start your exploration with the WKB approximation.
Comment: Thanks for you correction and advice.  I missed an $x$ and Q is periodic. Then will Floquet theory works?
Comment: Yes, but you get a faster result using $00$ and $x'(t_1)>0$, then due to the convexity of the solution for $t>t_1$ the solution grows faster than the tangent.
Comment: Thanks, but how to use comparision theorems to second order equations? As far as I know, it tells about one order equation.
Comment: The Sturm-Picone comparison theorem for oscillating solutions in the "elliptical" case has also a companion or corollary for the "hyperbolic" case, in that any solution can have at most one root. Also, unrelated, note that $x''-x=0$ has forwards bounded solutions $x=ce^{-t}$, so you need some really global argument for the claim.
Answer: On solution segments where $x(t)$ is positive (negative), one has by the DE $x''(t)>0$ ($<0$), so the curve is convex (concave).
This has immediately the consequence that any non-trivial $x(t)$ can have at most one root, as any arc between two consecutive roots becomes impossible.
If $x(t_*)=0$ with $x'(t_*)>0$, then by convexity the solution for $t>t_*$ has to be above the tangent at $t_*$ locally on some small segment, meaning the solution stays positive there, which prolongs this property globally for all $t>t_*$.
As non-zero constant solutions are impossible, for any positive solution one can find a point with a non-horizontal tangent which forces the solution to $\infty$ in one direction.
For solutions with negative values, note that with $x(t)$ also $-x(t)$ is a solution.


Configure the server & DNS like: Accept all domains that use our spesific nameservers

Question: First, I will describe the problem: I have a domain portfolio website. Every domain have a forsale page like this:
www.myportfoliosite.com/thedomainforsale.com

I want to park my domains but I need only a simple redirection to our for sale page. I think this solution has two steps:

Configure your server (cent-os, Apache 2.2 and WHM/cPanel) and/or DNS to accept all domains that use our specific nameservers.
Redirect all domains to their for sale page.

I think I can solve the step 2 using .htaccess. Now, I want to solve step 1 via this question. So,
Is it possible to configure the server or set up a DNS to accept all domains that use our specific parking nameservers like park1.myportfoliosite.com and park2.myprotfoliosite.com.
Note: Our current domain and nameservers work normally. So, I can create new nameservers or I can create a new cPanel account and use my another domain myportfoliosite.NET to create a specific configuration.
Answer: Normally, a name server is authoritative for certain domains and can allow recursion for the rest. That's the normal behavior of a name server. With BIND, this is done using hint type zone (see Caching Name Servers):
zone "." {
        type hint;
        file "/etc/bind/db.root";
};

If you simply don't need to use this server recursively on any client, and are willing to disobey the normal practices, it would be possible to make your name server answer authoritatively on every query by making it as a Master (Primary) Name Server for root .:
zone "." {
        type master;
        file "/etc/bind/db.root.authoritative";
};

And creating a fake root zone (/etc/bind/db.root.authoritative) e.g.:
$ORIGIN .
@    IN   SOA  ns1.example.com. hostmaster.example.com. 2017103002 1800 900 604800 86400
@    IN   NS   ns1.example.com.
@    IN   NS   ns2.example.com.

@    IN   A    203.0.113.10
*    IN   A    203.0.113.10

Where:

example.com could be the domain of your portfolio site
ns1.example.com and ns2.example.com are the actual name servers, configured at registar
203.0.113.10 is the IP of your webserver

Because of the *. your name server will now answer authoritatively to every query; it will answer 203.0.113.10 for every.subdomain.example.net. A you ever have.
As you are already breaking the rules, you don't necessarily need to configure zone transfers between your name servers for this . zone, but you can simply configure both servers as masters.
Comment: Thank you very much for your detailed answer. Everything is clear however I may need a freelancer to apply your solution. :)
Comment: This is helpful, to implement this should we have bind dns server installed, apprectiate any links for such is provided.


Drawing text in .NET with native look & feel

Question: I'm using .NET1 and I want to draw text as native. Is it possible by configuring graphics?
I need to render the text as the System.Windows.Forms.Label does when the FlatStyle is set to System.
I have configured the SmoothingMode and the AntiAliasGridFit, but unfortunately the result is not the same:

I'm using the same font in both cases (Segoe UI 9pt).
Any ideas?
Comment: How are you rendering the text? In .Net1.1 I'm assuming you're using Graphics.DrawString? Maybe you should look at calling the native "DrawTextEx" function if DrawString is not producing the desired formatting.
Comment: This was solved 4 major releases of .NET ago.  Kinda pointless to teach that old dog new tricks.
Comment: @Hans Maybe he has a specific target platform requirement? In an ideal world we'd all be using the latest and greatest of everything. Given, 1.1 is ancient, but so is IE6 and sadly that's still a required target platform in a lot of real-world cases.
Answer: Have you tried using the TextRenderer class instead of the Graphics.DrawString routine? It was introduced into the framework precisely because there is a discrepancy between the default rendering of Windows Forms and .NET's GDI+ wrapper.
The MSDN says:

The TextRenderer class provides a set of static methods that can be used for measuring and drawing text on a Windows Form control.
Comment: I believe the "TextRenderer" class is only available in 2.0 and greater versions of the framework. He's explicitly stating .Net 1.1.
Comment: @Brandon: ouch, didn't see. But to be blunt, that is an unreasonable requirement and I would *strongly* advise an immediate platform switch, *before* doing any other work.
Comment: Well, I hate developing in .NET 1.1 but it's a requeriment for me. We need to support an integration with Visual Studio 2003 that is incompatible with .NET 2.0 or higher.


How to change size of prices without disrupting the menu?

Question: I've been trying to get the size of the prices to change, but whenever I do it goes on top of the dotted line instead of staying above it.

//hide all the pages and display the home page
$('.page').hide();
$($('.page')[0]).show();
$($('.page-button')[0]).addClass('selected');

//this block of code switches the pages. it works no matter how many pages or page buttons there are, making it easy to add and remove pages
$('.page-button').on('click', function() {
  $(this).addClass('selected');
  $('.page').hide();
  $($('.page')[parseInt($(this).attr('data-page_num')) - 1]).show(); //displays the page based on the value of data-page_num
  window.scrollTo(0, 0); //scroll to the  top of the page
});
body {
  background: #e6e6e6;
  font-family: "Open Sans", Sans Serif;
  font-weight: 300;
  color: #febd44;
  margin: 0px;
}

ul,
li {
  list-style-type: none;
}

ul li {
  display: inline-block;
  box-sizing: border-box;
  text-align: left;
}

.main-button {
  display: inline-block;
  width: 79px;
  padding: 10px;
  box-sizing: border-box;
  text-align: center;
  font-size: 16px;
}

.main-button:hover {
  background: rgba(255, 255, 255, 0.1);
  transition: 0.7s;
  cursor: pointer;
}

h3 {
  text-align: center;
  font-size: 44px;
}

.container {
  box-sizing: border-box;
  margin: auto;
  max-width: 70%;
  padding: 20px;
}

.button {
  background: rgb(0, 163, 222);
  display: inline-block;
  width: 130px;
  margin: 10px;
  padding: 10px;
  text-align: center;
  text-decoration: none;
}

.button:hover {
  background: rgb(0, 105, 242);
  transition: 0.25s;
  color: white;
  cursor: pointer;
}

a {
  color: #febd44;
  text-decoration: none;
}

a:hover {
  color: white;
  transition: 0.5s;
}

.content1 {
  background: rgba(255, 255, 255, 0.15);
}

.content2 {
  background: rgba(255, 255, 255, 0.1);
}

.li {
  clear: both;
  margin: 0;
  padding: 0 0 1.8em 0;
  position: relative;
  border-bottom: dotted 2px #999;
}

strong {
  padding: 0 10px 0 0;
  font-weight: normal;
  position: absolute;
  bottom: -.3em;
  left: 0;
}

em {
  padding: 0 0 0 5px;
  font: 28px "Times New Roman", Sans-serif;
}

sup {
  font-size: 15px;
  margin-left: 3px;
}

.price {
  position: relative;
  top: .9em;
  float: right;
}

Silver Spoon

Home

Menu

Menu

Now introducing edible food.

Silver Spoon has a high-quality menu with affordable prices. Find out more on the menu page.

Bakery

Cheese Danish

250

Chocolate Chip Cookies

150

Glazed Donuts

200

Everything Bagels

200

Plain Bagels

150

Hot Breakfast

Egg Sandwich

350

Chicken Sausage Sandwich

450

Egg Bites

400

Egg Wraps

400

Old-Fashioned Oatmeal

350

Sandwiches

Chicken Caprese

450

Chicken Sandwich

400

Hamburger

250

Ham & Swiss Panini

300

Deserts

Cookies

150

Cake

350

Ice Cream

199

I tried to mess with the padding and margin, but it didn't change anything for me.
I just want to change the size of the prices while staying above the dotted lines
Answer: Just set the hight of .li explicitly, and also the size of .price em (that's the font size of the price).

//hide all the pages and display the home page
$('.page').hide();
$($('.page')[0]).show();
$($('.page-button')[0]).addClass('selected');

//this block of code switches the pages. it works no matter how many pages or page buttons there are, making it easy to add and remove pages
$('.page-button').on('click', function() {
  $(this).addClass('selected');
  $('.page').hide();
  $($('.page')[parseInt($(this).attr('data-page_num')) - 1]).show(); //displays the page based on the value of data-page_num
  window.scrollTo(0, 0); //scroll to the  top of the page
});
body {
  background: #e6e6e6;
  font-family: "Open Sans", Sans Serif;
  font-weight: 300;
  color: #febd44;
  margin: 0px;
}

ul,
li {
  list-style-type: none;
}

ul li {
  display: inline-block;
  box-sizing: border-box;
  text-align: left;
}

.main-button {
  display: inline-block;
  width: 79px;
  padding: 10px;
  box-sizing: border-box;
  text-align: center;
  font-size: 16px;
}

.main-button:hover {
  background: rgba(255, 255, 255, 0.1);
  transition: 0.7s;
  cursor: pointer;
}

h3 {
  text-align: center;
  font-size: 44px;
}

.container {
  box-sizing: border-box;
  margin: auto;
  max-width: 70%;
  padding: 20px;
}

.button {
  background: rgb(0, 163, 222);
  display: inline-block;
  width: 130px;
  margin: 10px;
  padding: 10px;
  text-align: center;
  text-decoration: none;
}

.button:hover {
  background: rgb(0, 105, 242);
  transition: 0.25s;
  color: white;
  cursor: pointer;
}

a {
  color: #febd44;
  text-decoration: none;
}

a:hover {
  color: white;
  transition: 0.5s;
}

.content1 {
  background: rgba(255, 255, 255, 0.15);
}

.content2 {
  background: rgba(255, 255, 255, 0.1);
}

.li {
  clear: both;
  margin: 0;
  padding: 0 0 1.8em 0;
  position: relative;
  border-bottom: dotted 2px #999;
  /* set the height of the li explicitly */
  height: 20px;
}

strong {
  padding: 0 10px 0 0;
  font-weight: normal;
  position: absolute;
  bottom: -.3em;
  left: 0;
}

em {
  padding: 0 0 0 5px;
  font: 28px "Times New Roman", Sans-serif;
}

sup {
  font-size: 15px;
  margin-left: 3px;
}

.price {
  position: relative;
  float: right;
}

/* set the size of .price em */

.price em {
  font-size: 50px;
}

/* set the size of .price sup */

.price sup {
  font-size: 30px;
}

Silver Spoon

Home

Menu

Menu

Now introducing edible food.

Silver Spoon has a high-quality menu with affordable prices. Find out more on the menu page.

Bakery

Cheese Danish

250

Chocolate Chip Cookies

150

Glazed Donuts

200

Everything Bagels

200

Plain Bagels

150

Hot Breakfast

Egg Sandwich

350

Chicken Sausage Sandwich

450

Egg Bites

400

Egg Wraps

400

Old-Fashioned Oatmeal

350

Sandwiches

Chicken Caprese

450

Chicken Sandwich

400

Hamburger

250

Ham & Swiss Panini

300

Deserts

Cookies

150

Cake

350

Ice Cream

199

But I think it would be much better to use flexbox for this, and then you can set the font-size to whatever value you want, and don't have to worry about not displaying right:

body {
  background: pink;
}

.menu-list {
  list-style-type: disc;
  margin-block-start: 0;
  margin-block-end: 0;
  margin-inline-start: 0;
  margin-inline-end: 0;
  padding-inline-start: 0;
}

.menu-list .li {
  margin: auto;
  background: white;
  display: flex;
  width: 80%;
  /* 'justify-content: space-between;' does the trick of
  separating the two items in the li */
  justify-content: space-between;
  border-bottom: 1px dotted red;
}

.menu-list .li .title,
.menu-list .li .price {
  display: flex;
}

.menu-list .li .title {
  font-size: 18px;
  align-self: flex-end;
}

.menu-list .li .price {
  font-size: 30px;
}

Food 1350

Food 2550

Food 3400


Use node title as page title in views full node page display

Question: I'm using views to link a menu-item to the last node added of a certain content-type.
To accomplish this, I've set up a view to display a 1 full node sorted by post date.
this all works just fine, but now I want to use the node title as page title () instead of the view page title. I also don't want the node title to link to the node again.
Does anyone know how I can do this?
Thx in advance.
Answer: I finally managed to pull this off by writing a small module using following code:
<code>function MYMODULE_preprocess_views_view(&$vars) {
  // Get my view
  if ($vars['view']->name == 'MY_VIEW_NAME') {
    //get the title of the node shown in the view
    $nid = $vars['view']->result[0]->nid;
    $node = node_load($nid);
    $my_title = $node->title;

    /* Code to dynamically set title here...
       Override view's title since drupal_set_title() is not working.*/
    $vars['view']->build_info['title'] = $my_title;
  }
}
</code>
This module changes te views page title and uses the nodes title as page title instead.
Now you can remove the linked nodetitle in the node--YOURTYPE.tpl.php
Comment: @Alex Will do so, but is says that I have to wait 1 more day.
Answer: This is a great way if you want to address all displays of a view, but what if you want this only for one specific display?
I found an answer to this on http://dropbucket.org/node/194.
<code>// first implement hook_preprocess_views_view() which is called for each view.
function HOOK_preprocess_views_view(&$variables) {
  if (isset($variables['view']->name)) {
    $function = 'HOOK_preprocess_views_view__'.$variables['view']->name;
    if (function_exists($function)) {
     $function($variables);
    }
  }
}

function HOOK_preprocess_views_view__MY_VIEW_NAME(&$variables) {
  //alter here that specific view
  if($variables['display_id'] == 'page_1') {
  // here it will alter specific display of that view.
    //get the title of the node shown in the view
    $nid = $variables['view']->result[0]->nid;
    $node = node_load($nid);
    $my_title = $node->title;

    /* Code to dynamically set title here...
       Override view's title since drupal_set_title() is not working.*/
    $variables['view']->build_info['title'] = $my_title;
  }
}
</code>
Now only the page_1 display of a view gets it's title from the node. All other displays just get the title defined in the display.
Comment: thx for your addition


For HashMap, is it more efficient to use compute() or put()

Question: I have tried looking around for a while but I can't find a concrete answer and still am having some trouble understanding exactly what the compute method for HashMap does.
The way I understand it at the moment is that compute will allow you to manipulate the value but not set it to a new value (like where the garbage collector will have to get rid of the old object) while put will just get rid of the old object and set it (like going x = new Something).
If my understanding of this is wrong, please tell me, but regardless, is the compute method more efficient in general? Should I use this over put whenever possible or is it only used in certain situations?
Answer: Use put if you want to set a new value unconditionally. Use compute if you want to compute a new value based on the existing value in the map. You have the option of either changing it to a new value or removing it from the map.
The documentation for compute states that:

The default implementation is equivalent to performing the following steps for this map:
V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null) {
    map.put(key, newValue);
} else if (oldValue != null || map.containsKey(key)) {
    map.remove(key);
}
return newValue;

It's more complicated than a simple put:

It calls get to retrieve the current value.
It calls the supplied remapping function to convert it to a new value.
It either calls put to overwrite the old value or remove to remove it depending on whether the new value is null or not.

Since ultimately it ends up calling put, compute has more steps and is slower. If put meets your needs—you don't care what's in the map, you just want to set a key to a value—use put.
Comment: IMO, compute is not slower.  Neither theoretically, nor implementation wise. In fact the main reason it is promoted and used is because it can do the key lookup once vs. twice as happens in get and put.  I have explained this in https://stackoverflow.com/a/76495979/298742
Comment: The question asks about compute and put, not get and put. I agree that calling compute is better than separate calls to get and put.
Answer: TL;DR
Yes, it is more efficient to use compute, instead of get() and put().
Longer version
By using a combination of compute, computeIfPresent computeIfAbsent etc, you can do EXACTLY the same things using compute method as you can do with get and put. (In fact prior to JDK 8, there was no compute and lambda, but we were all able to "get by" without any large gaping holes in our coding lives, although admittedly, the things got better with lambda.)
But the main advantages of using compute method is:

It is more readable (depends on who is doing the reading, of course)
It is atomic - between get and put, things could have changed if you write get and put yourself.
It can be and is generally more efficient.  This is evident from the fact that if you see the source code of HashMap.compute method, you will see
that it calls the hash function only once.   The get and put will call
hash function once each, since the underlying data structure knows
of those calls as separate calls.  In compute, it knows that the put
call is "coming", so it can save the hash.  Similarly in other implementations, once the key has been "located", it will be reused, rather than being looked up again.  The main algorithmic cost of this operation is in the lookup, so doing it once is better than doing it twice.

So, between 2 and 3, there are good reasons to use compute.
Comment: Note that the question is about compute vs. put, not compute vs. get + put.
Answer: As @John Kugelman explained above, put() is more efficient than compute().
Apart from explanation, Below are few observations from my side:
There are 2 cases where we can compare set() and compute()

If key is present in hash map
If key is not present in hash map

set(key,value): If key is not present in hash map, the key with value is added to the hash map and set() method returns "none".
set(key,value): If key is present in hash map, the new value will be replaced in place of old value and set() returns "old value".
compute(key,BiFunction biFunction): If key is not present in hash map, the key with value is added to to the hash map and compute() method retuns "new value".
compute(key, BiFunction biFunction): If key is present in hash map, the new value will be replaced in place of old value and compute() returns "new value"
    Map<String,Integer> ss = new HashMap<>(Map.of("A",10,"B",20));
    System.out.println(ss.put("C",30)); // none
    System.out.println(ss); // {A=10, B=20, C=30}

    System.out.println(ss.put("A",11)); // 10
    System.out.println(ss); // {A=11, B=20, C=30}

    System.out.println(ss.compute("D",(x,y)->40)); // 40
    System.out.println(ss); // {D=40, A=11, B=20, C=30}

    System.out.println(ss.compute("B",(x,y)->y+10)); // 30
    System.out.println(ss); // {A=11, B=30, C=30, D=40}

Internally compute() uses set(). The noticeable difference is the method's return types when key is present and not present in hash map

In terms of efficiency, set() is more efficient than compute().