Logistic regression with rare events, all events have large residuals and are influential points

Question: I am running a logistic regression model where the outcome is relatively rare (250 out of 5000). My main interest is to see if there are differences between age groups, sex, educational levels, income levels...with regards to the outcome and i am running a model with just the main effects. It appears that since the model has so few "positive" outcomes, these are not fitted well by the model. This becomes apparent since all the standardized residuals for these cases are between 2-3.1 and that all these are seen as influential points based on Cook's distance (see graph), based on the common rule of thumb 4/N(=0.0008). This is not surprising since the highest predicted probability from the model is p=0.28 for one of the "positive" outcomes.
My question is if such a model is trustworthy. I am only interested in the obtained odds ratios, not how well the model can discriminate between positive/negative outcomes. I have used the Le Cessie-van Houwelingen-Copas-Hosmer global goodness of fit test to evaluate the model which gives a p-value of p-value=0.3, so from that prespective looks good but on the other hand this is expected since the vast majority of the sample is well predicted. I have also tried Firth's logistic regression to correct for bias and both regressions give almost identical results. I have finally checked what happens if i remove the 10 more influential points from the model which resulted in almost identical estimated coefficients as the model with all data.
My question is if one can use a model like this for inference, for example to identify differences between age groups and being able to rely on these estimates.
I should also add that the model has 6 categorical predictors which leads to 20 model parameters. One variable is binary, 2 variables have four levels, 2 variables have 5 levels and one has 6 levels. No separation problems were observed and no multicollinearity based on VIF.
Comment: How many predictors are in your model? Please include in your count the number of levels (beyond the first) of each categorical predictor. Please provide that information by editing the question, as comments are easy to overlook and sometimes get lost.
Answer: Those measures are not the preferred ones for assessing lack of fit in binary logistic regression, when compared to directed tests of linearity or additivity.   Your effective sample size is about 500 and this sample size does not support consideration and estimation of very many parameters.  With a relatively small sample size expect individual observations to be influential, but don't necessarily make adjustments because of that.  And as @EdM mentioned the Efron-Gong optimism bootstrap can quantify overfitting/model reliability.  Details about these issues are in RMS.
Comment: Thank you professor Harrell for your reply, i really appreciate your work.
Answer: Most of the information in a logistic regression comes from the cases in the lower-prevalence category. Thus the "rule of thumb" for avoiding overfitting in a logistic regression is to have 10-20 lower-prevalence cases per model parameter evaluated. Under that "rule of thumb" you are on the low end of the range, but OK. That's unlike ordinary least squares, where the corresponding rule of thumb is for the total number of cases.
I'm not familiar with your "rule of thumb" about 4/N for Cook's distance. If that comes from ordinary least squares, it's possible that in the logistic-regression context the N should be the number of cases in the lower-prevalence category rather than the total number of cases. That would give you a "rule of thumb" for excess influence of 0.016, with all of your cases less than half that level.
Instead of relying on rules of thumb and diagnostic plots, let the data tell you how reliable your modeing process is. Repeat your modeling process on multiple bootstrapped samples of the data, examine the variance of your coefficient estimates among the multiple models (for inference), and evaluate how well the models work on the full data set. Under the bootstrap principle, that's a good way to estimate how well your model would work if applied to a new data sample.
Comment: Thank you very much for your reply. You are right, this rule of thumb comes from linear regression and is most likely wrong in a logistic regression context. I wasn't aware of the use of bootstrap for model validation, i will follow your suggestion and try it out.


Point a domain to google cloud

Question: I have setup Google Cloud Debian Instance and has this IP: "18.104.22.168".
I setup Google DNS as:

Domain name server for 11tips.com at the registar looks like this:

Virtual host conf in the server looks like this:
<VirtualHost *:80>
  ServerAdmin firstname.lastname@example.com
  ServerName 11tips.com
  ServerAlias www.11tips.com
  DocumentRoot /var/www/html
  ....
</VirtualHost>

And last, /etc/hosts looks like this:
127.0.0.1       localhost 11tips.com www.11tips.com
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters
10.128.0.4 lamp-1-vm.c.codefight-cms.internal lamp-1-vm  # Added by Google

Now when I go to 11tips.com, it doesn't load a site. What am I missing here. I am not good with servers, so hopefully someone can help me point my domain to Google Cloud.
Thank you.
Answer: My first thought was that you might need to create a glue record at the registrar for the NS, but you have them defined as googledomain.com servers.
https://wiki.gandi.net/en/glossary/glue-record
The DNS Tools check says something about your SOA record:
http://www.dnsstuff.com/tools#dnsReport|type=domain&&value=11tips.com

Like the registrar page says, your nameservers need to resolve your domain:  if they don't, something is misconfiguring on the hosting side (I haven't tried using Google Cloud hosting DNS)
Answer: Found the issue. I was creating / deleting dns few times as I didn't know what I was doing.
When I entered NS record to my domain, google dns was:
ns-cloud-c1.googledomains.com
But as I deleted and created again, c1 changed to d1 and I didn't notice that.
ns-cloud-d1.googledomains.com
Once I fixed that, site started loading.

Point a domain to google cloud


I can't find a comfortable place to sing when playing guitar

Question: My vocal range is between G2 and E4, but I cant find a place on the guitar to sing comfortable. If anyone could suggest a good place to try and sing it would be great!
Comment: I actually struggled with this problem for years - sliding the capo around and never being satisfied. My solution ended up being to tune the entire guitar down a minor-third and now everything fits so much more comfortably.
Comment: @jjmusicnotes - you're almost implying that you sing everything in the same key, which happens to be a m3 lower than others. How can that be? I'm sure you play different songs in different keys, so what difference will down-tuning make. Play song xyz in C? Too high for you? So play it in A instead ! Same end product - with the subtle changes of chord voicings.
Comment: @Tim - my particular problem was that with a standard-tuned guitar, in lower capo positions, my voice would be in the same tessitura as then guitar when singing in a comfortable octave, but I didn't have the range to sing entire songs with proper vocal production up the octave - I was vocally fatigued, sounded strained, and it didn't fit my voice. In order to find a good vocal placement, I'd have to put the capo up to at least 5th fret before I could sing in a comfortable tessitura, but then I don't have a big, resonant guitar sound.
Comment: @Tim - for me, shifting the entire guitar down works because now I can capo around in the lower positions, get a full guitar resonance; I can sing in the top  half of my range with nice production / resonance, and I'm not fighting tessitura with the guitar. Tuning the guitar down a m3 doesn't imply playing in the same key any more than a standard-tuned guitar implies playing everything in the same key.
Comment: @jjmusicnotes - not being funny, but I've never considered the guitar to have a tessitura. That's normally reserved for certain (not all) songs. I fukly understand the guitar will sound richer when tuned lowe, although capod at fret three, I reckon it'll sound the same as a standard guitar? Please enlighten me!
Comment: @Tim - any instrument can have a tessitura; tessitura is simply where the majority of notes are in a given melody / piece. Tessitura is different than range, as it constitutes an average. Re: capo, yes you're right, that would sound quite similar. However, I also do a lot with open strings, as well as tuning low. Sometimes I tune down to C# and sometimes I drop it all the way to B. Dropping it a whole P4 really shifts the guitar's tessitura and helpsmy vocal fatigue. If you've never tried it, you should!
Comment: @jjmusicnotes - not wishing to labour the point, but you seem to agree that where the majority of (higher or lower) notes are in a piece is its tessitura. It's where they are in *the piece* rather than where they are on what's playing them - although generally speaking, tessitura is related to voice. Yes. it's very different from *range*, which is exactly what any *instrument* will have.
Answer: One of the reasons different songs are in different keys is due to the range of each song - its highest and lowest notes. Two songs could both be in the same key, but their highest and lowest notes needn't be the same. Or, two songs could have the same highest or lowest note, but each be in a different key.
So, with a vocal range of over two octaves, which isn't bad, you're going to have to find a suitable key for each and every different song. Yes, there will be songs that have a small range, and these are easier to accommodate. That's because moving them up or down by a couple of tones will still keep them within your vocal range. There will also be songs which might take you too high, so you change to a lower key in order to keep the high notes happy, but that then takes you down too low. Maybe those songs are just not for you.
If you can't already, get so you can play in any key. Then you'll be able to try out a song, realise it's too high/low, and adjust accordingly. You should fing just about every song will have its 'best' key for your voice, but you alone need to find it. That's what good singer/guitarists do.
Answer: Are you actually transposing the guitar chords, or trying to sing 'high octave' or 'low octave' to the same chords?   I'm afraid the right place for your voice is almost always going to be somewhere in-between!     If the song is a Blues in F - F7, F7, Bb7, F7, C7, Bb7, F7 - maybe for YOU it will have to be a Blues in C - C7, C7, F7, C7, G7, F7, C7.     Get those transposing chops working!


Pegar um atributo de outra classe e colocar como parâmetro em um construtor

Question: Estou com uma duvida tremenda na qual não consigo achar um solução!
Estou tentando fazer que um construtor consiga pegar um atributo de uma classe e faça ele como parâmetro como mostra o código a seguir:
public class Comprador {

    private String nome;
    private int idade;
    private EnderecoResidencial endereco;

    public Comprador(String nome, int idade, EnderecoResidencial endereco) {
        this.nome = nome;
        this.idade = idade;
        this.endereco = endereco;
    }

    public Comprador(String nome, int idade) {
        this.setNome(nome);
        this.setIdade(idade);
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getIdade() {
        return idade;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }

    public EnderecoResidencial getEndereco() {
        return endereco;
    }

    public void setEndereco(EnderecoResidencial endereco) {
        this.endereco = endereco;
    }

    public void imprime() {

        System.out.println("Nome: " + getNome());
        System.out.println("Idade: " + getIdade());
        System.out.println("Endereço: " + getEndereco());

    }

}

public class EnderecoResidencial {

    private String enderecoCompleto;

    public EnderecoResidencial(String endereco) {
        this.enderecoCompleto = endereco;
    }

    public String getEnderecoCompleto() {
        return enderecoCompleto;
    }

    public void setEnderecoCompleto(String enderecoCompleto) {
        this.enderecoCompleto = enderecoCompleto;
    }

    public void imprime() {
        System.out.println("O endereço completo é: " + getEnderecoCompleto());

    }

O problema é que ao fazer isso no main está gerando o erro: (The constructor Comprador(String, int, String) is  undefined.) Somente no construtor no qual eu quero pegar o endereço.
public class Teste {

    public static void main(String[] args) {

        EnderecoResidencial enderecoresidencial = new EnderecoResidencial("Rua Pauliceia");
        enderecoresidencial.imprime();

        Comprador comprador1 = new Comprador("Ari", 22, ""); //(The constructor Comprador(String, int, String) is  undefined.)
        comprador1.imprime();

        Comprador comprador2 = new Comprador("Ana", 18);
        comprador2.imprime();

        System.out.println(comprador1.getEndereco());

        System.out.println(enderecoresidencial.getEnderecoCompleto());
    }

}

No que estou errado nesse código? O parâmetro do endereço no construtor está errado?
Answer: Tá dando erro porque você está mandando uma string como parâmetro ao invés do objeto. Tente:
Comprador comprador1 = new Comprador("Ari", 22, enderecoresidencial);


How and where is the $variables variable used in templates etc. generated in Drupal?

Question: How and where is the $variables variables that is used in templates and theme functions generated in Drupal?
Is there documentation anywhere that defines $variables?
Comment: Do you mean it depends on what key-value pairs of $variables I'm interested in? So, for example, where is $variables created that is passed into theme_item_list (https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_item_list/7)?
Comment: It really depends on which variables you're interested in. It's a bit too vague for a question.
Comment: The `$variables` for `theme_item_list` will have originated from the function that calls `theme('item_list', $variables);`. Which variables are accepted will have been declared in `hook_theme()`. Also have a look at [`theme()`](https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7)
Answer: The $variables associated array that are passed into functions such as MYTHEME_item_list($variables) are initialized by the caller of that function.
Comment: I think OP is talking about the `$variables` array that gets passed to theme functions/templates.
Comment: I have revoked my downvote :-)
Comment: Thanks. So essentially, the contents of $variables will be set by modules and passed to theme functions/templates to be rendered into HTML?
Answer: You can use associated array $variables that are taken from template.php or yourmodule.module so that, you can pass that variables to page of your theme.
 $imageOutputinner = "You can have  images variable here";
$vars['innerImages'] = $imageOutputinner;
//you can print this variables to page of  theme as
print_r($innerImages);


Dell PowerEdge T710, add a new hard disk, how to?

Question: I have a virtual machine which needs more space. This VM runs and a PowerEdge T710 with Vmware EXSI 4.  I would like to add this disk in the simplest was possible.
I already got a normal desktop hard disk (SATA, 1TB, not Dell branded).
I have no rack for it to plug it inside any of the front bays.
I found an available SATA cable and power. Can I just add the disk by plugging these and using the empty 5"1/4 slot available under the CD drive (with a 5"1/4 - 3½" bay adapter)?
Even if this way it seems that I bypass the RAID controller that owns the front bay with racks.
edit : i suppose the existing RAID is composed of 1 TB drive, BTW this is ok for lack of redundancy, i accept if for now. My difficulties are : can i plug it this (loosy) way ? will it be seen by the firmware/BIOS and VMWare and also how to setup and install the drive so that BIOS + VMWare recognize it and add it as a new ressource (what are the particular steps to follow?)
Answer: I have no Vmware EXSI 4 experience, but from a hardware point of view:
1) Yes, you can add the drive that way. It will not be part of any existing RAID arrays. It will not have redundancy. But the PowerEdge will be able to access it and if the drivers of ESX4 allow it you can also use it as a direct usable disk (passthough) from the VM.
I repeat: No redundancy. If the drive fails you just lost all data on it.
2) If you are using hardware RAID with SAS drives then you can not add it to the existing array.
3) Do contract Dell for a proper 5 1/4  - 3½" bay adapter. Or check Ebay. Lose drives in a server are not recommended. :)
Could you check which drives are already in the server. Type, speed, interface. Then add that to the post. (Just in case the HW RAID consists of 1TB SATA drives)
Comment: ok for the "if drive fail" i had to accept that for now, my main troubles is that from my trial, i can not see the disk added as a manageable/usage "ressource", actually i do not know what are the steps after plugging the power and sata wires... (real beginner)
Comment: For that you will have to search in the vmware manual. I can tell you for windows, GNU/Linux, BSD, ... but as stated not for ESX4. No experience with that.


I am struggling with fingerboard muscle memory on the violin. Are there exercises, besides scales, that can help me?

Question: I'm an adult learning violin for 5 months now. No tape or any markings on the fingerboard.
I can't seem to gain muscle memory when it comes to placing fingers.
I have an idea of where they should go, but I am always really off; like a full semitone off a lot of the time.
I practice scales a lot (I only know first position so I only practice 1 octave G, D, A major scales)
I feel like there is something I am missing when it comes to learning how to develop muscle memory.
How do I my make fingers land in correct position on violin?
Are there exercises, besides scales, that can help me?
Comment: Classic example of someone who would benefit from a teacher.
Comment: @Tim I knew someone would comment this. But, I'm not sure what a teacher could do to make me place my fingers in the correct position besides telling me to practice; which is obvious advice. Seriously, how would a teacher make my fingers land correctly?
Comment: @AlJebr - For starters, I can definitely imagine your teacher forcibly moving your hand into the proper position (one of my piano teachers later in my childhood did this to me, too).
Comment: This is one thing experienced teachers must be doing all the time! If we all knew how, we wouldn't need them! We don't, so why not give it a go? Even a coupke of lessons would put you in the right direction. There is of course the obvious 'practise lots', and use ears lots, and stop looking so much.
Answer: A semitone out is a lot. If you are practicing scales with intonation and finger placement specifically in mind and still regularly being a semitone out then my first suggestion would be to put those tapes back on. If you never had them on in the first place that might be a contributing factor.
The second thing I would point out is that practice, to be of value, needs to be mindful. By that I mean that before you start your practice you have to have a plan. You know what you are going to try and do and how you are going to do it. While you are practicing your brain is fully engaged. You are paying attention to what you are doing and correcting and adjusting as you go.
The third thing I would point out is that improvement is gradual. It is not, unless you are lucky, an overnight thing. It happens slowly over time with much mindful practice. Good intonation should always be at the back of your mind but you should not stop everything else. Repertoire and etudes should still be part of your daily routine.
One addition to your scales would be to switch on a tuner while you play and adjust your finger positions with the aid of the tuner. Unless you have already mastered another instrument it is very likely that your ear will require training just as much as your fingers.
Finally, by insisting to try and learn without the help and guidance of a teacher you are metaphorically tying one hand behind your back. If you paid money for your instrument then it will be very much worth your while to pay money for instruction.


The field trace is surjective over the fixed field

Question: This problem it's from Stewart Galois Theory book. I want to solve it only using the theorems used on the book. Or at least simple tools.

Let $K$ be a field of characteristic $0$. And let $L/K$ be a finite and normal extension (thus in this case Galois extension , since is also separable). For any $a\in L$ define $T(a)= \sum_{\sigma\in G} \sigma (a)$ Where $G = Gal (L,K)$. Prove that $T(a)\in K $ and that $T$ is a surjective map $L\to K$.

Well it's clear that $T(a)\in K$ since is fixed by all the element of the galois group, and then it's just to consider the Galois theorem.  But how I can prove that it's surjective?
I realized that $T$ is also a linear transformation, maybe I can use the dimension theorem is some way. But I don't know how to compare the dimension of the kernel, with the dimension of $L$ over $K$. Or maybe that it's not a good way to solve the problem.
Comment: For any $x\in K$, $T(x/|G|)=x$.
Answer: Hint: What is the trace of an element of $K$?
Addendum: Also it is crucial here that the characteristic of your field is $0$ as Makoto points out below. Otherwise the proof has to use slightly more sophisticated machinery.
Comment: By the way, what if $char(K) = p > 0$ and $L/K$ is separable and $(L:K)$ is divisible by $p$?
Comment: Use linear independence of characters then to show that the trace map is surjective. But, that is not what the question is asking so ... Nevertheless I put in a comment to warn the OP that the approach will not work in the situation you mention.
Comment: I think that I did it, but I'm not sure. Look this. Since $ T:E\to F$ is a F-linear transformation, then $Im T \le F $ is a F-subspace of F. Since $ dim_F F =1 $ the image has dimension 1 or 0. But it's not zero , since the characteristic is not zero. Then por example 1 is not in the kernel. And Then $ dim_F Im T = 1$ and since it's also contained in F , then $Im T = F $
Comment: Yes, your solution is great. You should post it as an answer and accept it (posting answers to your own questions is encouraged on this site). Btw, I hope you are using characteristic $0$ (you said not $0$ in your comment above) to show that the trace of $1$ is not zero, or something like that.


Does intuitionist logic deny diagonal argument?

Question: Let us for example give an example of diagonal proof of uncountability of the set of real numbers $\mathbb{R}$.
Would intuitionists accept this, or deny this? If they deny this argument, why would they?
Comment: There is some subtlety in the meaning of "the set of real numbers". The diagonal argument can be used (in intuitionistic logic) to show that the set of functions $\mathbb{N} \to \{ 0, 1 \}$ is uncountable, for instance.
Comment: I just guess there's no evidence of use of **Axiom of Choice** and **principle of excluded middle** here !
Comment: @Fardad Pouran: the axiom of choice is not a problem intuitionistically. It's included in Bishop's system for constructive mathematics, for example.
Comment: @CarlMummert I didn't know. Thank You
Answer: The general methods of the diagonal argument are fine intuitionistically.
Also, because $\lnot P$ is equivalent to $P \to \bot$, it is fine to prove $\lnot P$ by assuming $P$ and deriving a contradiction. So there is no problem with proving "the reals are not countable" by assuming "the reals are countable" and deriving a contradiction.
The main thing to worry about is whether any classical logic slipped into the intermediate steps of the proof. This is particularly relevant to real numbers because of the way real numbers are handled in intuitionistic logic.
Nevertheless, at least one version of proof that the real numbers are not countable (by a variation of the nested interval diagonal method due to Cantor) is intuitionistically valid.


css transition: choose different speed for hover out

Question: Is it possible to choose a different timing/speed for transition in css so when mouse hover over a div it expands with different speed than the speed it retracts back to its original width not hover state.
I have tried declaring different transition speeds in :hoer and normal state styling, however, only normal state style seems to apply.
http://jsfiddle.net/tpf8mv51/3/
Problems:
1st) it goes with same speed it expanded with.
2nd) zindex takes effect after animation is completed for reasons i don't gte.
3rd) other images get affected even though they shouldn't, by affected i mean they 99% of time disappear till animation is done.
* {
    margin: 0;
    padding: 0;
}
body {
    overflow: hidden;
}
.main {
    font-size: 0;
    height: 100%;
    width: 100%;
    display: none;
    z-index: -1;
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
}
.main img {
    -webkit-user-select: none;
    width: 25%;
    -webkit-transition: transform .5s;
    transform-origin: left;
    z-index: 0;
    vertical-align: top;
}
.main img:hover {
    transform: scale(1.3, 1);
    z-index: 1;
}

Answer: Don't fret. try this (quick IN, slow OUT):
.main img {
  width: 25%;
  height: 100%;
  transition: width 2s ease;
}
.main img:hover {
  width: 50%;
  transition: width .5s ease;
}

Your Fiddle as I can see it only has one transition. If you're only changing the width, tell it to change the width, which has full browser support, rather than calling transform with all the attendant prefixes.
Comment: originally i was doing that, but only 2s transition was applying..let me check again.
Answer: CSS doesn't distinguish between mouseover and mouseout, but this thread seems like it may have the answer to your question:
MouseOver and MouseOut In CSS
Edit: I just realized you said you have tried this. Javascript may be your only option.
Comment: There is no reason for javascript
Answer: Update your css with the below (add transition)
.main img {
    -webkit-user-select: none;
    width: 25%;
    -webkit-transition: transform .5s;
    transform-origin: left;
    z-index: 0;
    vertical-align: top;
    transition:all 1s;
}
.main img:hover {
    transform: scale(1.3, 1);
    z-index: 1;
    transition:all 1s;
}

Comment: i did and i am still having few same problems: 1. During transition of animation all other images disappear, until it's finished. 2. zindex only applies after the animation has finished so in meanwhile element order prevail. 3. expand out and in still have the same speed/timing.
Comment: The `transition` rule at the last line of the first ruleset overrides `-webkit-transition`, and therefore your solution doesn't work.


JQuery Mobile  not expanding in full browser

Question: Using a basic
 and
 within asp.net project with input controls, can't figure out why
 will not expand to full browser width? The
 will expand with wider
 content.

                <asp:Label ID="Label1" runat="server" Text='<%# Eval("FDID")%>' Font-Bold="True" Font-Size="Medium"></asp:Label>
                : Selections

1st Week:
                <asp:TextBox ID="CHOICE1TextBox" runat="server" Text='1st Week' ReadOnly="True"></asp:TextBox>

                <asp:HiddenField ID="CHOICE1HiddenField" runat="server" Value='<%# Bind("CHOICE1")%>' />

2nd Week:
                <asp:TextBox ID="CHOICE2TextBox" runat="server" Text='' ReadOnly="True"></asp:TextBox>

                <asp:HiddenField ID="CHOICE2HiddenField" runat="server" Value='<%# Bind("CHOICE2")%>' />

...

                <asp:Button ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update"
                    Text="Update Selections" ToolTip="Click to change your selections..."></asp:Button>
                <asp:Button ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
                    Text="Cancel"></asp:Button>

Screen Shots:
Comment: What is the paretn element of the UL? What is its rendered HTML?
Answer: Try with  data-inset="false" on

Comment: then you have some issue with css, play a bit in firebug with css
Comment: can you give page content HTML, you have to much padding there
Comment: See other post with HTML output: http://stackoverflow.com/questions/25645334/jquery-mobile-non-adjustable-width   this is using standard jquery mobile 1.4.3
Answer: ok the problem was in the <FormView> of the .net section of my page, see: asp.net formview generates table at fixed width 259px
it's seems the default width of 259px is auto generated in the form based on content size.


Why I can't translate image in the view by QGraphicsView.translate

Question: I want implement an image view by PyQT5 using QGraphicsView. And I don't want scoll bars; and  I want to pan the image freely. That means I can pan the image outsize the viewport. So I make the scene with big range. Below is my code. I found that I can't translate the image by calling self.translate. I can't figure out why, please help:
from PyQt5.QtCore import Qt, QPoint, QPointF, QRectF, QSizeF, QRect
from PyQt5.QtGui import QImage, QPixmap, QTransform, QPainter, QCursor, QMouseEvent
from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene, QGraphicsPixmapItem, QScrollBar
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
import math
from PyQt5 import QtGui

class ImageViewer(QGraphicsView):
    def __init__(self, parent=None):
        super(ImageViewer, self).__init__(parent)
        self.setScene(QGraphicsScene(self))
        self.setSceneRect(-10000, -10000, 30000, 30000)
        self.setStyleSheet("background-color: black;")
        self.setDragMode(QGraphicsView.ScrollHandDrag)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.pixel_item = QGraphicsPixmapItem()
        self.scene().addItem(self.pixel_item)
        self._last_pos = None

    def wheelEvent(self, event: QtGui.QWheelEvent) -> None:
        pass

    def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:
        self._last_pos = event.pos()

    def mouseMoveEvent(self, event: QtGui.QMouseEvent) -> None:
        if self._last_pos is not None and event.buttons() & Qt.LeftButton:
            diff = event.pos() - self._last_pos
            print('translate: ', diff.x(), diff.y())
            self.translate(diff.x(), diff.y())

    def mouseReleaseEvent(self, event: QtGui.QMouseEvent) -> None:
        self._last_pos = None

    def loadImage(self, imagePath):
        pixmap = QPixmap(imagePath)
        self.pixel_item.setPixmap(pixmap)
        self.pixel_item.update()
        self.centerOn(self.pixel_item)
        # self.setSceneRect(item.boundingRect())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = QMainWindow()
    window.setContentsMargins(0, 0, 0, 0)
    print("window size", window.size())
    image_viewer = ImageViewer(window)

    image_viewer.loadImage('4649---1.jpg')
    print('setting widge')
    window.setCentralWidget(image_viewer)
    # window.setGeometry(100, 100, 800, 400)
    window.show()
    sys.exit(app.exec_())

And My goal is to implement a image viewer class that I can pan and zoom the image freely without scene limit. And I can call translate of scale method to adjust the image without mouse event to simultanously pan and zoom multiple ImageView to compare them.
Answer: The main reason of your problem is explained in the documentation:

QGraphicsView keeps the center of the view fixed during a transformation. Because of the scene alignment (setAligment()), translating the view will have no visual impact.

The translate() function is used for complex transformations and does not affect the visual area of the scene.
The reality is that, if you use a large enough scene rect (as you are doing), you should not implement mouse events at all, since using the ScrollHandDrag will be sufficient: remove all mouse event handlers and it will work as expected.
As an alternative, you could control the view box by translating the view's sceneRect instead, but since the translation is incremental, you must always update the _last_pos to the new event pos, and the original scene rect must be as small as possible: the fact that the scroll bars are hidden does not mean that their behavior is ignored, so if you make the window smaller than the actual scene contents, they would actually control the viewport scrolling; making the view's scene rect extremely small will override their behavior completely.
Finally, in order to properly center the item within the "small" scene rect, you have to set its position to the negative center of its bounding rect.
class ImageViewer(QGraphicsView):
    def __init__(self, parent=None):
        super(ImageViewer, self).__init__(parent)
        self.setScene(QGraphicsScene(self))
        self.setSceneRect(0, 0, 1, 1)
        # ...

    # ...

    def mouseMoveEvent(self, event: QtGui.QMouseEvent) -> None:
        if self._last_pos is not None and event.buttons() & Qt.LeftButton:
            diff = event.pos() - self._last_pos
            self.setSceneRect(self.sceneRect().translated(-diff))
            self._last_pos = event.pos()

    # ...

    def loadImage(self, imagePath):
        pixmap = QPixmap(imagePath)
        self.pixel_item.setPixmap(pixmap)
        self.pixel_item.setPos(-self.pixel_item.boundingRect().center())


foreach step 5 steps forward in an array

Question: How can I step forward 5 steps when using foreach to output an arrays value? So In this the put will be 1, 5
<code>$array = ("1","2","3","4","5","6","7","8","9");
foreach ($array as &$value) {
    echo $value; //Where do I tell it to move 5 paces forward?
    echo "<br/ >";
}
</code>
If a foreach loop cannot be used, I'm willing to use something else. I don't think "while" or "for" can be used here?
Comment: 2 ways. Add a counter and use it as index. Add +5 after each iteration. Or use modulous operator.
Comment: Should it *always* move forward 5 places?
Comment: If you move forward 5 steps wouldn't the output be 1,6?
Answer: <code>$array = array("1","2","3","4","5","6","7","8","9");
for($i=0; $i<count($array); $i+=5) {
    echo $array[$i];
    echo "<br/ >";
}
</code>
Comment: This did the job (with a few amendments to the arrays starting value and beginning i at 1). Thanks a lot for this.
Answer: I would use a while loop. Just set an index outside of the loop, and add 5 to it on each iteration of the loop. When the index is larger than the length of the list, terminate the loop.
A more compact way to express these instructions is a for loop:
<code>for ($i=0; $i<count($array); $i = $i+5)
</code>
Answer: If it is not numerically indexed
<code>$count = -1;
foreach ($array as &$value) {
  $count++;
  if ($count%4 != 0) continue;
  echo "$value".PHP_EOL;
}
</code>


New DbContext puts old data into database

Question: I'm testing business logic (in sqlserver db) using auto-generated DbContext and MSTest framework. DbContext maps only part of entities and is used mainly in web api odata controllers. The testing pattern is:
<code>protected U2Db Db; //auto-generated DbContext
protected DbContextTransaction CurrentTransaction;

[TestInitialize]
public void BeforeEveryTest(){
    Db = new U2Db();
    CurrentTransaction =
       Db.Database.BeginTransaction(IsolationLevel.ReadCommitted);
}

[TestMethod]
public void Method1() {
    var o = new Order() {Tag="Method1"};
    Db.Orders.Add(o);
    Db.TrySave(); //custom extension. wraps SaveChanges and reports errors if exist

    //checks inner db tables, service broker queues etc.
    ....
}
[TestMethod]
public void Method2() {

    var o = new Order() {Tag="Method2"};
    Db.Orders.Add(o);
    Db.TrySave(); //wraps SaveChanges and reports errors if exist

    ....
}
[TestCleanup]
public void AfterEveryTest() {
    if (Db == null) return;
    try
    {
        if (CurrentTransaction != null)
        {
            CurrentTransaction.Rollback();
            CurrentTransaction.Dispose();
        }
    }
    catch (Exception e) { };

    Db.Dispose();
}
</code>
If I run any test manually, it works as expected. If I start running a batch of tests (sequentially, single-threaded), some of them fail. What i see in Server Profiler is that transactions work as expected, but in failing tests database gets records which were used in previously run tests, which makes me feel like DbContext is not actually a 'new' instance. What I'm doing wrong?
Answer: Tests in general should be stateless to avoid these kind of errors. Don't use a field for your DBContext, but instantiate a separate variable in each test like this:
<code>[TestMethod]
public void Method1() {
    var db = new U2Db();
    var o = new Order() {Tag="Method1"};
    db.Orders.Add(o);
    db.TrySave(); //custom extension. wraps SaveChanges and reports errors if exist

    //checks inner db tables, service broker queues etc.
    ....
}
</code>


Route to the view received by Node.js request

Question: Controller code:
bina: function(req, res) {
  var request = require('request');

  request({
    url: 'http://localhost:3000/bina/',
    method: 'GET',
  }, function(err, res, body) {
    if (err) {
      console.log(err);
    } else {
      var data = JSON.parse(res.body);
      console.log(data);
      res.render(data)
    }
  })
}

The data that comes with the request does not see any functions like res.view or res.render.
Error output:
res.render(data)
           ^
TypeError: res.render is not a function

Note:
I can see the data via console.log(data) via web service. I use Sail.js.
Answer: Here's what you are doing wrong:
You are using same variable (res) name twice. And at the res.render it taking the one which is in the nearest scope. I have renamed the res => to response and now it should work.
bina: function(req, res) {
    var request = require('request');

    request({
        url: 'http://localhost:3000/bina/',
        method: 'GET',

    }, function (err, response, body) { // Changed the variable name
            if (err) {

                console.log(err);

            }
            else {
                var data = JSON.parse(response.body);
                console.log(data);
                res.render(data)

            }
        })
}

Hope it solved your issue.


What statistical test to use?

Question: I would like to ask your advice regarding the statistical tools that can be used in analyzing two different kinds of data where  I have to determine if there is an association between them.
For example:
My first type of data is a Likert scale (1-5) to determine the level of participation of the respondents.
My second type of data is a YES or NO data which asks the respondents about their purchasing behavior.
Is there a statistical tool that can be used to determine if there is an association between respondents level of participation and their purchasing behavior given that these are two different kinds of data?
Also, can difference in consumer behavior (like purchasing behavior plus repurchase behavior) be measured between two companies considering that behavior is measured only using YES or NO questions?
Comment: What does your last paragraph mean? Can you clarify your situation?
Answer: You might try odds ratio or logistic regression:
http://en.wikipedia.org/wiki/Logistic_regression
This type of regression deals with categorical data types and could tell you the log odds of your Likert scale (1-5) being returned based on being in the YES or NO response category....

What statistical test to use?


Should I lag the independent variable or dependent variable to get delayed effects of the IV on DV?

Question: I'm doing research where I am getting the delayed effects of my Xs on my Y using a 2-way fixed effects approach. Since all of my Xs will end up being delayed, should I lag my Y by -1 or should I lag all of my Xs by +1? Or does it not matter? Since I'm getting different coefficients from doing both approaches, I am also wondering what the difference is between those two theoretically. If someone could explain to me how they would be different, I would really appreciate it.
Answer: In the simple example below using R we get the exact same coefficients whether we lag the RHS or reverse lag the LHS so more details are needed to understand why you are getting different results.  Note that the base R lag function does not work on plain vectors so we used flag from the collapse package.  Also BOD is a data frame that comes with R (shown in the Note at the end.)
library(collapse)

lm(demand ~ flag(Time), BOD)
## Call:
## lm(formula = demand ~ flag(Time), data = BOD)
##
## Coefficients:
## (Intercept)   flag(Time)
##       11.46         1.56

lm(flag(demand, -1) ~ Time, BOD)
## Call:
## lm(formula = flag(demand, -1) ~ Time, data = BOD)
##
## Coefficients:
## (Intercept)         Time
##       11.46         1.56

Note
> BOD
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8


How to avoid being pianocentric in my compositions?

Question: I have heard of 1 thing to do to make your music less pianocentric. That is to play other instruments. Thing is my commitment to guitar has always been on and off and while with an acoustic I don't really have to worry about sore fingers, with an electric guitar(which I most often play as I would an acoustic(so no amps, just strumming and plucking with my fingers)) I often don't know until the next day that I played for too long.
And it takes weeks for me to really develop the guitarist callous and be able to play guitar for longer. Also, I find writing for violin to be easier than writing for guitar. Maybe it is because like all my piano practice was classical music.
Yeah, I bet that is at least part of why I find writing for violin easier. I am planning on composing a country song for a trio of piano, guitar, and violin. And like I said the one thing I keep hearing is "Play more instruments. It will get easier as you get more advanced in more instruments."
But if it took me like 6-7 years to be super advanced at the piano and almost another 3 years to be comfortable playing super fast and not hit a tempo wall, I can't imagine how long it would take for me to get to advanced level guitar, especially with my on and off commitment to the guitar and almost constant commitment to the piano. 1 up side of having played the piano first is I can have a wide span between frets which is why I am able to play an open position Bb major chord with ease.
But I don't want to wait until I am better at guitar to compose music involving the guitar. So if I am only beginner level at guitar and thus can't really get into the guitarist mindset, how can I avoid writing music for the guitar that would really be more suited to the piano than anything else(such as close position 7th chords just as an example)?
Comment: Did you not read most of the question? I'm only a beginner guitarist and I am super advanced at the piano. This being super advanced at the piano is most likely why my music turns out pianocentric.
Comment: How the heck does a guitarist become piano centric in the first place?
Comment: "Super advanced".  What does that mean?  Are you driven by technique or sound?  Do you think you would be "pianocentric" on the sax or violin?
Comment: Why would close position 7th chords not be suitable on guitar?  Unless I misunderstood your last comment.
Comment: @ggcg - Close position 7th chords with the lowest E as the root are unplayable with standard tuning.
Comment: So what, F, F#, G, etc.
Answer: Look up the scores of idiomatic guitar pieces (Tárrega's a good composer for this--he incorporates advanced guitar-specific techniques into his pieces). Listen to them, too. Do this for several, if not 100+, such pieces. Find trends between them.
Failing that, listen to pieces written for ensembles that include a guitar, and pay specific attention to the guitar part. If you've got the chops and you don't have the sheet music, transcribe the guitar part.
Failing that, listen to guitar solos in arrangements of other pieces. Chances are, the guitar solo was one of the only sections that the arranger made up instead of extracted from music more suited for other instruments, and the solo will be written so it's playable on guitar in a spur-of-the-moment style (i.e. it's more idiomatic for guitar). (This happens to me fairly often for remixes of video game themes.)
Solo guitar transcriptions of other pieces are OK resources to listen to and/or read if you can catch the differences between them and the original pieces. The differences can highlight the limitations of the guitar.
Comment: I basically haven't done my above tips often enough, which is why I'm currently afraid to write a piece for solo guitar.
Answer: as you want to compose a country song it will be sufficient to note the chords for the guitar and if there's a solo you should have trust to the guitarist and give him the liberty to improvise a solo.
on the other hand as you are a good pianist you can write a counterpoint with a second tune for the guitar imitating or responding to the motifs of the piano voicing and fill-ins where the piano is resting or holding long notes.
here you will find a collection of piano riffs
https://www.8notes.com/school/riffs/piano/adele_someone_like_you.asp
you don't need to be a guitar player you can just look for guitar riffs and licks:

https://www.guitarhabits.com/top-25-easy-guitar-riffs-and-intros/
https://ch.images.search.yahoo.com/search/images;?p=guitar%20riffs%20for%20beginners
Answer: If all else fails (previous answers) listen to an orchestral arrangement or even a band one, then try to create your piece for an orchestra or band (one note per instrument). Then, try to combine the parts, making sure you don't make it impossible to play. If it turns out that way, try to invert the chord (better to have to shift/move a lot than to not be able to play at all).


Return to a Previous Dialog Within a Dialog List Tree

Question: I've been looking over AppleScript: How to return to previous dialog/list? and it gave me a good jumping off point, however the solution only goes one dialog list deep. How would I go about having multiple Lists in a tree, where a Back button only sends you back one level, instead of all the way to the top level.
I've been reading over AppleScript Handlers, but I can't figure out how to have more than one.
Additionally, I am receiving an error in my code. If I cancel out of the first List, the dialog box closes as expected. But if I navigate into a one of the next dialog Lists then press Back and then press Cancel I receive error "Can't get item 1 of false." number -1728 from item 1 of false
on run
    chooseLetter()
end run

on chooseLetter()

    set preparedResponse to "" -- initialize the variable
    set prList to choose from list {"Alpha", "Beta", "Gamma", "Delta"} with title "Greek Alphabet" with prompt "Alphabet Characters:" default items {""}
    if prList is false then return
    set preparedResponse to item 1 of prList

    set currentPR to "" -- initialize the variable
    if preparedResponse is "Alpha" then
        set articleList to choose from list {"Alpha One", "Alpha Two", "Alpha Three", "Alpha Four"} with title "Alpha Title" with prompt "Alpha Choices:" OK button name "Next" cancel button name "Back"
        if articleList is false then chooseLetter()
        set currentPR to item 1 of articleList

    else if preparedResponse is "Beta" then
        set articleList to choose from list {"Beta One", "Beta Two", "Beta Three", "Beta Four", "Beta Five"} with title "Beta Title" with prompt "Beta Choices:" default items {"Beta One"} OK button name "Next" cancel button name "Back"

        if articleList is false then chooseLetter()
        set currentPR to item 1 of articleList

    else if preparedResponse is "Gamma" then
        set articleList to choose from list {"Epsilon", "Zeta"} with title "Gamma Title" with prompt "Gamma Choices:" default items {"Epsilon"} OK button name "Next" cancel button name "Back"

        if articleList is false then chooseLetter()
        set currentPR to item 1 of articleList

    else if preparedResponse is "Delta" then
        set articleList to choose from list {"Delta One", "Delta Two", "Delta Three"} with title "Delta Title" with prompt "Delta Choices:" default items {"Delta Three"} OK button name "Next" cancel button name "Back"

        if articleList is false then chooseLetter()
        set currentPR to item 1 of articleList

    end if

    set letterGroup to preparedResponse
    set prChoice to currentPR
    set prResponseCode to "" -- initialize the variable

    #Alpha

    if letterGroup is "Alpha" and prChoice is "Alpha One" then
        set prResponseCode to "α 1000"

    else if letterGroup is "Alpha" and prChoice is "Alpha Two" then
        set prResponseCode to "α 1001"

    else if letterGroup is "Alpha" and prChoice is "Alpha Three" then
        set categoryList to choose from list {"Eta", "Theta"} with title "Alpha Three Title" with prompt "Alpha Three Choices:" OK button name "Next" cancel button name "Back"

        if categoryList is false then chooseLetter()
        set categoryError to item 1 of categoryList

        if categoryError is "Eta" then
            set the clipboard to "Eta is the seventh letter of the Greek alphabet. Originally denoting a consonant /h/, its sound value in the classical Attic dialect of Ancient Greek was a long vowel, raised to [i] in hellenistic Greek, a process known as iotacism."
        else if categoryError is "Theta" then
            set the clipboard to "Theta is the eighth letter of the Greek alphabet, derived from the Phoenician letter Teth. In the system of Greek numerals it has the value 9."
        end if
        set prResponseCode to "α 1002"

    else if letterGroup is "Alpha" and prChoice is "Alpha Four" then
        set prResponseCode to "α 1003"

        # Beta

    else if letterGroup is "Beta" and prChoice is "Beta One" then
        set prResponseCode to "β 2000"

    else if letterGroup is "Beta" and prChoice is "Beta Two" then
        set prResponseCode to "β 2001"

    else if letterGroup is "Beta" and prChoice is "Beta Three" then
        set prResponseCode to "β 2002"

    else if letterGroup is "Beta" and prChoice is "Beta Four" then
        set prResponseCode to "β 2003"

    else if letterGroup is "Beta" and prChoice is "Beta Five" then
        set prResponseCode to "β 2004"

        # Gamma

    else if letterGroup is "Gamma" then

        set misrouteGroup to "" -- initialize the variable
        if prChoice is "Epsilon" then
            set misrouteList to choose from list {"Epsilon One", "Epsilon Two", "Epsilon Three", "Epsilon Four"} with title "Epsilon Title" with prompt "Epsilon Choices:" OK button name "Next" cancel button name "Back"

            if misrouteList is false then chooseLetter()
            set misrouteGroup to item 1 of misrouteList
        else if prChoice is "Zeta" then
            set misrouteList to choose from list {"Zeta One", "Zeta Two", "Zeta Three", "Zeta Four", "Zeta Five", "Zeta Six"} with title "Zeta Title" with prompt "Zeta Choices:" OK button name "Next" cancel button name "Back"

            if misrouteList is false then chooseLetter()
            set misrouteGroup to item 1 of misrouteList
        end if
        if prChoice is "Epsilon" and misrouteGroup is "Epsilon One" then
            set prResponseCode to "ε 5000"

        else if prChoice is "Epsilon" and misrouteGroup is "Epsilon Two" then
            set prResponseCode to "ε 5001"

        else if prChoice is "Epsilon" and misrouteGroup is "Epsilon Three" then
            set prResponseCode to "ε 5002"

        else if prChoice is "Epsilon" and misrouteGroup is "Epsilon Four" then
            set prResponseCode to "ε 5003"

        else if prChoice is "Zeta" and misrouteGroup is "Zeta One" then
            set prResponseCode to "ζ 6000"

        else if prChoice is "Zeta" and misrouteGroup is "Zeta Two" then
            set prResponseCode to "ζ 6001"

        else if prChoice is "Zeta" and misrouteGroup is "Zeta Three" then
            set prResponseCode to "ζ 6002"

        else if prChoice is "Zeta" and misrouteGroup is "Zeta Four" then
            set prResponseCode to "ζ 6003"

        else if prChoice is "Zeta" and misrouteGroup is "Zeta Five" then
            set prResponseCode to "ζ 6004"

        else if prChoice is "Zeta" and misrouteGroup is "Zeta Six" then
            set prResponseCode to "ζ 6005"

        end if

        # Delta

    else if letterGroup is "Delta" and prChoice is "Delta One" then
        set prResponseCode to "δ 4000"

    else if letterGroup is "Delta" and prChoice is "Delta Two" then
        set prResponseCode to "δ 4001"

    else if letterGroup is "Delta" and prChoice is "Delta Three" then
        set prResponseCode to "δ 4002"

    end if

    set prResponseCode to "Classic " & prResponseCode

    set textToType to prResponseCode

end chooseLetter

From the Dialog List "Alpha Three Choices:" I want to be able to return to the List "Alpha Choices:" and "Epsilon Choices" should go back to "Gamma Choices:" Right now everything goes back to the top level "Alphabet Characters:"
Answer: The error Can't get item 1 of false." number -1728 from item 1 of false is pretty clear.
First of all the rule is: A return statement exits the current scope. In the on run handler it aborts the script because it's on the top level.
So far so good.
However you recursively call chooseLetter() so pressing the Cancel button (or whatever its name is) continues after the line chooseLetter() was called.
I recommend to work with handlers. A handler represents a single scope.
Answer: I was able to figure out how to make it work. I'm not excited about having to use error number -128 but other than that, the whole thing is working great.
There's probably more elegant ways to write this, but it's a good start for me.
on run
    global preparedResponse, prResponseCode, articleList
    set prResponseFinal to "" -- intialize the variable
    set textToType to "" -- intialize the variable
    chooseLetter()
    activate application "TextEdit"
    tell application "System Events" to tell process "TextEdit"
        keystroke textToType
    end tell
end run

on chooseLetter()
    set prList to "" -- intialize the variable
    set prList to choose from list {"Alpha", "Beta", "Gamma", "Delta"} with title "Greek Alphabet" with prompt "Alphabet Characters:" default items {""}
    if prList is false then
        error number -128
    else
        set preparedResponse to item 1 of prList
    end if
    set letterGroup to preparedResponse
    set prResponseCode to "" -- initialize the variable
    if preparedResponse is "Alpha" then chooseAlpha()
    if preparedResponse is "Beta" then chooseBeta()
    if preparedResponse is "Gamma" then chooseGamma()
    if preparedResponse is "Delta" then chooseDelta()
end chooseLetter

# Alpha

on chooseAlpha()
    global preparedResponse, prResponseCode, articleList, textToType
    set preparedResponse to "" -- intialize the variable
    set prResponseCode to "" -- intialize the variable
    set articleList to "" -- initialize the variable
    set articleList to choose from list {"Alpha One", "Alpha Two", "Alpha Three", "Alpha Four"} with title "Alpha Title" with prompt "Alpha Choices:" OK button name "Next" cancel button name "Back"
    if articleList is false then
        chooseLetter()
    else
        set preparedResponse to item 1 of articleList
    end if
    if preparedResponse is "Alpha One" then set prResponseCode to "α 1000"
    if preparedResponse is "Alpha Two" then set prResponseCode to "α 1001"
    if preparedResponse is "Alpha Three" then chooseAlpha2()
    if preparedResponse is "Alpha Four" then set prResponseCode to "α 1003"
    set prResponseFinal to "Classic " & prResponseCode
    set textToType to prResponseFinal
end chooseAlpha

# Alpha2

on chooseAlpha2()
    global preparedResponse, prResponseCode, articleList
    set preparedResponse to "" -- intialize the variable
    set prResponseCode to "" -- initialize the variable
    set categoryList to "" -- initialize the variable
    set categoryList to choose from list {"Eta", "Theta"} with title "Alpha Three Title" with prompt "Alpha Three Choices:" OK button name "Next" cancel button name "Back"
    if categoryList is false then
        chooseAlpha()
    else
        set preparedResponse to item 1 of categoryList
    end if
    if preparedResponse is "Eta" then
        set the clipboard to "Eta is the seventh letter of the Greek alphabet. Originally denoting a consonant /h/, its sound value in the classical Attic dialect of Ancient Greek was a long vowel, raised to [i] in hellenistic Greek, a process known as iotacism."
        set prResponseCode to "η 7000"
    end if
    if preparedResponse is "Theta" then
        set the clipboard to "Theta is the eighth letter of the Greek alphabet, derived from the Phoenician letter Teth. In the system of Greek numerals it has the value 9."
        set prResponseCode to "θ 8000"
    end if
end chooseAlpha2

# Beta

on chooseBeta()
    global preparedResponse, prResponseCode, articleList, textToType
    set preparedResponse to "" -- intialize the variable
    set prResponseCode to "" -- intialize the variable
    set articleList to "" -- initialize the variable
    set articleList to choose from list {"Beta One", "Beta Two", "Beta Three", "Beta Four", "Beta Five"} with title "Beta Title" with prompt "Beta Choices:" default items {"Beta One"} OK button name "Next" cancel button name "Back"
    if articleList is false then
        chooseLetter()
    else
        set preparedResponse to item 1 of articleList
    end if
    if preparedResponse is "Beta One" then set prResponseCode to "β 2000"
    if preparedResponse is "Beta Two" then set prResponseCode to "β 2001"
    if preparedResponse is "Beta Three" then set prResponseCode to "β 2002"
    if preparedResponse is "Beta Four" then set prResponseCode to "β 2003"
    if preparedResponse is "Beta Five" then set prResponseCode to "β 2004"
    set prResponseFinal to "Classic " & prResponseCode
    set textToType to prResponseFinal
end chooseBeta

# Gamma

on chooseGamma()
    global preparedResponse, prResponseCode, articleList
    set preparedResponse to "" -- intialize the variable
    set prResponseCode to "" -- intialize the variable
    set articleList to "" -- initialize the variable
    set articleList to choose from list {"Epsilon", "Zeta"} with title "Gamma Title" with prompt "Gamma Choices:" default items {"Epsilon"} OK button name "Next" cancel button name "Back"
    if articleList is false then
        chooseLetter()
    else
        set preparedResponse to item 1 of articleList
    end if
    if preparedResponse is "Epsilon" then chooseGamma2()
    if preparedResponse is "Zeta" then chooseGamma3()
end chooseGamma

# Gamma2

on chooseGamma2()
    global preparedResponse, prResponseCode, articleList, textToType
    set preparedResponse to "" -- intialize the variable
    set prResponseCode to "" -- intialize the variable
    set articleList to "" -- initialize the variable
    set misrouteList to choose from list {"Epsilon One", "Epsilon Two", "Epsilon Three", "Epsilon Four"} with title "Epsilon Title" with prompt "Epsilon Choices:" OK button name "Next" cancel button name "Back"
    if misrouteList is false then
        chooseGamma()
    else
        set preparedResponse to item 1 of misrouteList
    end if
    if preparedResponse is "Epsilon One" then set prResponseCode to "ε 5000"
    if preparedResponse is "Epsilon Two" then set prResponseCode to "ε 5001"
    if preparedResponse is "Epsilon Three" then set prResponseCode to "ε 5002"
    if preparedResponse is "Epsilon Four" then set prResponseCode to "ε 5003"
    set prResponseFinal to "Classic " & prResponseCode
    set textToType to prResponseFinal
end chooseGamma2

# Gamma3

on chooseGamma3()
    global preparedResponse, prResponseCode, articleList, textToType
    set preparedResponse to "" -- intialize the variable
    set prResponseCode to "" -- intialize the variable
    set articleList to "" -- initialize the variable
    set misrouteList to choose from list {"Zeta One", "Zeta Two", "Zeta Three", "Zeta Four", "Zeta Five", "Zeta Six"} with title "Zeta Title" with prompt "Zeta Choices:" OK button name "Next" cancel button name "Back"
    if misrouteList is false then
        chooseGamma()
    else
        set preparedResponse to item 1 of misrouteList
    end if
    if preparedResponse is "Zeta One" then set prResponseCode to "ζ 6000"
    if preparedResponse is "Zeta Two" then set prResponseCode to "ζ 6001"
    if preparedResponse is "Zeta Three" then set prResponseCode to "ζ 6002"
    if preparedResponse is "Zeta Four" then set prResponseCode to "ζ 6003"
    if preparedResponse is "Zeta Five" then set prResponseCode to "ζ 6004"
    if preparedResponse is "Zeta Six" then set prResponseCode to "ζ 6005"
    set prResponseFinal to "Classic " & prResponseCode
    set textToType to prResponseFinal
end chooseGamma3

# Delta

on chooseDelta()
    global preparedResponse, prResponseCode, articleList, textToType
    set preparedResponse to "" -- intialize the variable
    set prResponseCode to "" -- intialize the variable
    set articleList to "" -- initialize the variable
    set articleList to choose from list {"Delta One", "Delta Two", "Delta Three"} with title "Delta Title" with prompt "Delta Choices:" default items {"Delta Three"} OK button name "Next" cancel button name "Back"
    if articleList is false then
        chooseLetter()
    else
        set preparedResponse to item 1 of articleList
    end if
    if preparedResponse is "Delta One" then set prResponseCode to "δ 4000"
    if preparedResponse is "Delta Two" then set prResponseCode to "δ 4001"
    if preparedResponse is "Delta Three" then set prResponseCode to "δ 4002"
    set prResponseFinal to "Classic " & prResponseCode
    set textToType to prResponseFinal
end chooseDelta


Let $m(x)= (1+|x|^2)^{s/2}.$ Can we find constant and $f$ so $m(x+y) \leq C f(x) m(y) $

Question: Define $m(x)= (1+|x|^2)^{s/2}, \ x \in \mathbb R^d, s\in \mathbb R.$
Can we expect to find function $f$ on $\mathbb R^d$ so that
$$m(x_1+x_2) \leq C f(x_1) m(x_2) $$ for all $x_1, x_2 \in \mathbb R^d.$
Answer: Let $\langle x \rangle=(1+\vert x \vert^2)^{1/2}$ (often called Japanese bracket) and $w\in \mathbb{R}$, then a simple application of the Cauchy-Schwarz inequality yields
$$
\langle x+y\rangle^w \le 2^{\vert w \vert /2 }\langle x\rangle^w\langle y\rangle^{\vert w\vert},\quad x,y\in\mathbb{R}^d.
$$
Try to prove it yourself, or otherwise look up Lemma 4.3 in Peter Hintz' (excellent) lecture notes on microlocal analysis.
Comment: Thanks. But how does this help to solve the problem?
Comment: Sorry, I submitted prematurely.
Comment: The question contains a power two that your expressions don't contain


If - Else statement using the drawable of ImageView

Question: Am trying to get the ImageView drawable and use it to create an if else statement, i have tried many solutions including the one below, all are not working they always give me the wrong Toast
if(holder.likeImage.getDrawable()==context.getResources().getDrawable(R.drawable.ic_action_like)){
                Toast.makeText(context, "LIKED ALREADY", Toast.LENGTH_SHORT).show();
            }

            else if(holder.likeImage.getDrawable()!=context.getResources().getDrawable(R.drawable.ic_action_like)){
                Toast.makeText(context, "YOU HAVNT LIKED", Toast.LENGTH_SHORT).show();

            }

Comment: Don't use Drawable object equality to represent state -- the objects returned from getDrawable() are unique and can't be used for equality comparison. Store your state information some other way (ex. a boolean value on your holder).
Comment: look at this answer here on how to compare two drawables http://stackoverflow.com/questions/9125229/comparing-two-drawables-in-android
Answer: try this.
holder.likeImage.setImageResource(R.drawable.ic_action_like);
holder.likeImage.setTag(R.drawable.ic_action_like);
if(holder.likeImage.getTag().equals(R.drawable.ic_action_like)){

}else{

}

Comment: i tried adding the above code but am getting the wrong toast
Comment: I did holder.likeImage.setImageResource(R.drawable.ic_action_like);
holder.likeImage.setTag(R.drawable.ic_action_like); then i used the above if statement
Comment: i need your adapter class.


Como somar um campo de objetos retornados do firebase ( vuejs + firebase )

Question: Ola , estou tentando desenvolver uma plataforma ERP com vuejs utilizando o firebase como solução de armazenamento , estou tentando somar todos os campos 'valor' dos documentos da coleção 'despesa' que carrega os campos 'Nome' 'Valor' 'Data' 'Descrição' para apresentar um total
esse é meu codigo para pegar os dados do firebase:

ReceberDados:function(){
            fb.DesRef.get().then((querySnapshot)=> {
                querySnapshot.forEach((doc) => {
                   var result = doc.data();
                            console.log(result)

                })
            })
        }

como resultado o console eu tenho

Como eu posso somar todos os campos 'Valor' ?
( dicas para o projeto tbm são bem vindas )
Answer: Utilizando javascript você pode fazer um map para retornar apenas o valor e depois fazer um reduce para somá-los
Veja esse exemplo:
let usuarios = [
    { nome: 'Diego', Valor: 23, empresa: 'Rocketseat' },
    { nome: 'Gabriel', Valor: 15, empresa: 'Rocketseat' },
    { nome: 'Lucas', Valor: 30, empresa: 'Facebook' },
];
const valorTotal = usuarios.map(u => u.Valor).reduce((total, valor) => total + valor);
     console.log(valorTotal);


Services attempt to bind to IPv6 address before it comes up

Question: I have a couple of services on Ubuntu 23.04, BIND and Nginx, which are configured to bind to specific IPv6 addresses. However, they fail to start because systemd attempts to start them before the IPv6 addresses come up via DHCPv6. From my logs I believe the DHCPv6 addresses come up two seconds after DHCPv4.
I can manually restart the services after boot to get them to bind to the IPv6 addresses, but what is the best way to halt their start until IPv6 comes up?
Answer: Linux supports an IP_FREEBIND socket option that programs can enable before trying to bind to a specific address. Neither nginx nor BIND support this natively, but net.ipv6.ip_nonlocal_bind sysctl can enable this system-wide (which may be slightly risky as it means bind() will never fail even when it should).
If you're using systemd-networkd (even if indirectly via netplan), there is a service that you can have in a unit's After= whose only purpose is to wait for all network interfaces to be configured. (NetworkManager has a similar one.) Normally you use it through network-online.target but it can also be used directly:

a) Indirectly (the usual way):
# systemctl enable systemd-networkd-wait-online
# systemctl edit named
[Unit]
Wants=network-online.target
After=network-online.target

b) Directly:
# systemctl edit named
[Unit]
Wants=systemd-networkd-wait-online.service
After=systemd-networkd-wait-online.service

Generally though, I'd prefer binding to the wildcard address and using the firewall (nftables) to limit access to the service. (I've already seen – and abused – a system that bound its services to addresses of interface A, but did nothing in its firewall to prevent packets from interface B to be routed to those addresses.)
Comment: Thanks, looks like systemd-networkd-wait-online will do the job.
Comment: Incidentally, Nginx and BIND both listen on IPv6 port 443 (HTTPS and DNS-over-HTTPS) so I cant wildcard the address.
Comment: @triatic And while it's fine for TCP, on a multi-homed system UDP + wildcard requires additional features (such as IP_PKTINFO or IP_RECVDSTADDR): nginx (and the DNS server unbound) has IP_PKTINFO support, bind9 doesn't.


mysql search string similar to in_array in pjhp

Question: I have a string @x='2,12,13,1' and now i have to find out whether 2 is exists in the string @x. I have tried using of length function as below.
<code>@st=2;
if((LENGTH(@x) - LENGTH(REPLACE(@x, @st, '')))/LENGTH(@st)=1)
    return 1;
else return 0;
</code>
if it returns 1 then string exists but it is not working as expected. pls let me know is their any other method implement this feature.
Thanks.
Comment: http://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad/3653574
Comment: Can you use LOCATE? http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_locate
Answer: We can use FIND_IN_SET function.
FIND_IN_SET(@st,@x); This function will return the position of the needle string. If it is >0 then string exists else it's not.


Numerically find amplitude and phase in R

Question: I need to ask a follow-up question to this post:
https://stackoverflow.com/questions/1449290/algorithmically-get-amplitude-and-phase-of-sine-wave
My objective is to find the amplitude and phase of some signal. For a better understanding I now want to assume that this signal is a simple sine wave.
The code that I currently have is:
t <- seq(0, 100, length.out = 1000)
s <- sin(t)
qplot(t, s, geom = "line")

f <- fft(s)
a2 <- Mod(f/length(s))
qplot(t, a2, geom = "line")

As far as I understood it, the second plot now visualises the double-sided Fourier transform, right? So, what do I have to do to end up with amplitude = 1? From looking at the second plot I would need to add the two peaks...?
And, regarding the phase. I know that I would have to use something like p2 = Arg(f), but how do I end up with phase = 0?
Thanks a lot!
Answer: Correct formula for sine wave is
$$
A\cdot \sin(2\pi\cdot f\cdot t + \phi)
$$
where $A$ is amplitude, $f$ is frequency and $\phi$ is phase.
In this answer on stackoverflow I showed a function, that can help you to understand fft() better.
Comment: yes...which is exactly what I used for $A=1$, $f=1/2\pi$ and $\phi=0$.
Comment: Looking at your function, I would need to `max(Mod(fk))` to get my amplitude and the last value of `Arg(fk)` to get my phase, right? But apart from that, could you explain what you did to `fk` after the `fft` and why?
Comment: Discrete Fourier transform gives you a vector f. First element is so called zero-frequency, should be a sum of a signal. The first half of f ( f[2:(n/2)], where n us length(f) ) contains positive-frequency terms, second half - negative ones. So for ease of interpretation I take only first half. You should plot Mod(fur) ~ freq from my function, you will get a value ~1 near frequency 1/2*pi. It would be a amplitude spectrum. Same for Arg(fur) for phase - it should be zero on whole interval.


$\epsilon$ - $\delta$ proof for continuity of $ \lim_{x \to a} \sqrt{x}$ for $ a > 0 $

Question: I am currently undergoing a Calculus I course as an undergraduate. I was hoping to gain some guidance into whether the proof I have worked out for the continuity of a function $ f(x) = \sqrt{x} $ is robust enough or is missing out on certain details.
Aim: Prove that the function $f(x) = \sqrt{x}$ is continuous at $a > 0$.
(1) Finding the value of f(a) for which f is defined
The function $f(x) = \sqrt{x}$ is defined for values of $x \ge 0$. Given $a > 0$,
$$
f(a) = \sqrt{a} \\
\lim_{x \to a} \sqrt{x} = \sqrt{a}
$$
(2) Showing that $\lim\limits_{x \to a} \sqrt{x}$ exists for every $a > 0$.
Hence, given $\epsilon > 0$, we aim to find a proper $\delta > 0$ such that:
$$0 < |x - a| < \delta \Rightarrow |\sqrt{x} - \sqrt{a}| < \epsilon$$
Factorizing $|x-a|$,
$$
|x-a| = |\sqrt{x} - \sqrt{a}||\sqrt{x} + \sqrt{a}| < \delta \\
|\sqrt{x} - \sqrt{a}| < \frac{\delta}{|\sqrt{x} + \sqrt{a}|}
$$
Since $\sqrt{x} + \sqrt{a}\ge 0$, it follows that $\frac{1}{|\sqrt{x} + \sqrt{a}|} < 1$. Hence,
$$
|\sqrt{x} - \sqrt{a}| < \frac{\delta}{|\sqrt{x} + \sqrt{a}|} < \delta
$$
Therefore, we take $\delta = \epsilon$.
Proof:
$$
0 < |x - a| < \delta \Rightarrow |\sqrt{x} - \sqrt{a}| < \delta = \epsilon.
$$
Since $f(a) = \sqrt{a}$ and $\lim\limits_{x \to a} \sqrt{x} = \sqrt{a}$ for $a > 0$,
$$
\lim_{x \to a} \sqrt{x} = f(a)
$$
and thus the function $f(x) = \sqrt{x}$ is continuous at every a > 0.
Any feedback on gaps or loopholes in this proof would be greatly appreciated!
Edit:
There was a flaw in my logic, as kindly pointed out below. Since $\sqrt{x} + \sqrt{a}$ may fall in the range of values $0 \le \sqrt{x} + \sqrt{a} \le 1$ the assertion that $\frac{1}{|\sqrt{x} + \sqrt{a}|}$ does not hold.
The appropriate logic should be:
$$
\frac{\delta}{|\sqrt{x} + \sqrt{a}|} < \frac{\delta}{|\sqrt{a}|}
$$
for x > 0.
Hence,
$$
|\sqrt{x} - \sqrt{a}| < \frac{\delta}{|\sqrt{a}|}
$$
We choose $\delta = \epsilon\sqrt{a}$.
Revised proof:
$$
0 < |x - a| < \delta \Rightarrow |\sqrt{x} - \sqrt{a}| < \epsilon\sqrt{a}(\sqrt{a}) = \epsilon
$$
Comment: Close. But $\sqrt{x} + \sqrt{a} \geq 0$ does not imply $1/|\sqrt{x} + \sqrt{a}| < 1$.
Comment: RIGHT! Thank you! Must have messed up it up by assuming that $a \ge 1$.
Answer: There is no reason why $\frac  {\delta} {\sqrt x+\sqrt a}$ should be less than $\delta$ so your proof is not valid.
Note that $\frac  {\delta} {\sqrt x+\sqrt a} < \frac {\delta} {\sqrt a}$ (for $x>0$) so it is enough to choose $\delta =\epsilon \sqrt a $
Comment: I realize my mistake. Thank you for the correction!
Answer: Let $\varepsilon>0$ be defined. We want to find such $\delta>0$ that suffices $\forall x\in (a-\delta,a+\delta), |f(x)-f(a)|<\varepsilon$.
So, we're looking for such $\delta$ that: $|\sqrt x-\sqrt a|<\varepsilon$.
Notice: $|\sqrt x-\sqrt a|=\frac{|x-a|}{\sqrt x + \sqrt a}<\frac{|x-a|}{\sqrt a}<\frac{\delta}{\sqrt a}$.
Now let's define $\delta = \varepsilon \sqrt a$.
Therefore: $|\sqrt x-\sqrt a|=\frac{|x-a|}{\sqrt x + \sqrt a}<\frac{|x-a|}{\sqrt a}<\frac{\delta}{\sqrt a}=\frac{\varepsilon \sqrt a}{\sqrt a}=\varepsilon$.
** Notice that $\sqrt x, \sqrt a>0$ so the expression $\sqrt x + \sqrt a $ doesn't need absolute value.


Laravel 5 / Forge and nginx, trying to set site-wide HTTPS

Question: I'm having issues getting nginx to rewrite http:// traffic to https://. I'm getting a nginx 404 error page on any http:// traffic.
I'm new to nginx, but I believe I should be editing the 'default' file under the sites-available folder?
On further inspection, it looks like the 404 is loading from the catch-all file
server {
listen 80;
listen [::]:80;
listen 443 default ssl;

server_name default;
root /home/forge/default/public;

# FORGE SSL (DO NOT REMOVE!)
ssl_certificate /etc/nginx/ssl/default/12979/server.crt;
ssl_certificate_key /etc/nginx/ssl/default/12979/server.key;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
if ($ssl_protocol = "") {
    rewrite ^       https://oakjar.com/$request_uri? permanent;
}

index index.html index.htm index.php;

charset utf-8;

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

access_log off;
error_log  /var/log/nginx/default-error.log error;

error_page 404 /index.php;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

location ~ /\.ht {
    deny all;
}

Comment: Don't edit the `default` file; create a new file for your vhost configuration.
Answer: Create a new file for your vhost.
Create 2 server block - 1 block to handle port 80 to redirect to 443, and 1 block for your usual configurations under port 443.
server {
    listen       80;
    server_name  _;
    return       301 http://$host$request_uri;
}
server {
    listen       443;
    server_name  _;

    # the usual ...
    ...
}

Comment: I had a combination of errors, port 443 wasn't open, etc. But in the end, this was the correct answer. I ended up deleting the 'default' vhost and creating a whole new domain through Laravel Forge. -Thanks


why we need different types of base chain in nftables?

Question: I know how hooks work in netfilter but I can't understand why there are different types of chains as  described here: base chain types  I have two questions
first : why there are different types of chains? why not to use only "filter" type?
second : why "route" chain type has only one hook? it was supposed to be "mangle" equivalent in iptables but according to this Hooks by family and chain type it has only output hook. (why?)
Thank you
Comment: [My related question on unix.SE](https://unix.stackexchange.com/q/762402), with an (excellent) answer.
Answer: The chain type is part of the design of netfilter.  They made different types for a the type of rule organization they thought people would like to use.  this design forces people to separate chains by the three functions they create.   On a technical level each chain operates different inside the kernel.  For example for the route type it triggers a routing evaluation after the chain is run, this is not the case for filter or nat types.
route has only one hook, because it only needs one hook to serve its function.  if the mangling that you are doing is not related to routing decisions, put it in filter and attach it to whatever you need.
To better grasp the concepts, I find the nftables code in the kernel to be quite easy to follow.  Here are links to the chain type definitions inside the kernel:
https://github.com/torvalds/linux/blob/master/net/netfilter/nft_chain_filter.c#L195
https://github.com/torvalds/linux/blob/master/net/netfilter/nft_chain_nat.c#L88
https://github.com/torvalds/linux/blob/master/net/netfilter/nft_chain_route.c#L134
Comment: if you look at nf_route_table_hook4 inside nft_chain_route you will see for example a call to ip_route_me_harder.  which does not exist in the filter chain.
Comment: so in this way I can always set any chain as "filter" type to have more control and more hooks! is it right?
Comment: that is not correct.  while commonly most things should be in filter,  you must still use nat and route when and if you have rules that belong there.   the limitations of route and nat types in terms of hooks are only done because it is not needed.  here is a good manual for nftables  https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/configuring_and_managing_networking/getting-started-with-nftables_configuring-and-managing-networking
Comment: you are correct and I understand the design discipline, but I just wanna know if there is technical difference between these types. I checked the github links you send (tnx a lot) but it seems there is no difference, only a naming convention to have more clear design, am I right??? (about RH link: tnx, but I already read that many times before asking Q here)
Answer:
Adding a NAT rule to a filter type chain will result in an error.

https://wiki.nftables.org/wiki-nftables/index.php/Performing_Network_Address_Translation_(NAT)
I tried to add a masquerade rule to a filter chain, and confirmed that the above sentence is true. The chain type limits what action can be performed on a rule.


Perguntas javascript

Question: Eu estou com dificuldades em resolver estes exercícios,se pudessem ajudar...
Este é o código :
<form name="myForm">
    Radio station name
        <input type="text" name="name" />

    <select name="music_type">
        <option value="rock" selected>Rock</option>
        <option value="pop">Pop</option>
        <option value="jazz">Jazz</option>
    </select>
    <button onclick="saveForm()">Submit</button>
</form>

E as perguntas são:

Como escrever uma função Javascript que guarda os valores de input da form em session storage, quando o utilizador clica no botão Submit?
O que devo alterar na função anterior, usando jQuery, para que quando o botão for clicado, o background da form seja alterado para a cor cinza?
Comment: Olá John, bemvindo ao Stackoverflow! Nós nõ vamos resolver o problema para tí. Ajudamos com gosto mas tens de ser mais específico em que parte do código tens dificuldades. Falta ainda algum código, podes [edit] a pergunta e juntar o resto, juntamente com explicação do que conseguiste fazer e onde não consegues mais.
Comment: @johnmiras, o que você já tentou fazer? Qual a sua dúvida em relação ao que você tentou fazer?
Comment: form name="myForm"
  Radio station name
 select name="music_type"
 option value="rock" selected>Rock
Pop
Jazz

Submit
Comment: é apenas isto que tenho de código,a minha dificuldade são em relação a essas questões não conseguindo realiza-las
Answer: Não vou resolver o teu exercício, mas posso explicar no que precisas pensar para resolveres.
Quando tens uma <form> com um button (e repara que quando o button não tem o atributo type="" ele toma por defeito type="submit"), ao carregar no botão ele vai enviar os dados da form e atualizar à página.
Como tens onclick="saveForm()" isso vai fazer correr uma função chamada saveForm que tem de estar no escopo global. Podes ler aqui sobre o que isso quer dizer..
Dentro dessa função deves gravar para o localStorage. Há muitas perguntas aqui no SOpt sobre localStorage, para saberes mais se não fôr claro.
Tens de ter em conta que o localStorage guarda strings. Ou seja tens de serializar os dados antes de os inserir. Podes fazer isso com o JSON.stringify(teusDados);
Como ir buscar os dados?
Os teus elementos têm um atributo name certo? então podes usar var select = document.querySelector('[name="music_type"]'); no caso do select, e o mesmo para o input. Para guardar o seu valor basta depois fazer var valorSelect = select.value;.
Como montar os dados?
Podes fazer um objeto por exemplo assim:
var teusDados = {
    select: select.value,
    input: input.value
};

e depois usares isso no JSON.stringify como referí em cima.
Em relação à segunda pergunta acho que é avançada para os conhecimentos que tens hoje. Precisas saber o que é jQuery e como ele recebe argumentos e os transforma em objetos com métodos jQuery. Isso é muita coisa para referir aqui. Mas os passos que tens de fazer usam estes métodos:
$(botão) // tens de passar o elemento <button> para o jQuery, provavelmente vais queres usar um seletor CSS: 'button'
    .closest('form') // para selecionares o ancestral/pai mais próximo que seja uma <form>
    .css(attributo, valor)

A sintaxe do .css() é (atributo, valor). Vais querer usar background-color e côr cinzenta aí.
Boa sorte!

Perguntas javascript


how to get information about discounts on product?

Question: Short: I have commerce product and commerce discount that affects this product's price. I want to presents details of this discount to users in shop.
Long story: I use Drupal Commerce with Drupal Commerce Discount which is based on Rules. Discount module is used for configuring promotions on products. Some of promotion (configured discounts) are time-limited ie. they ends on 11.11.2015.
I would like to get information about discounts that affect product when displaying details. First of all I need to display information how much time is left before discount ends.
Is there any way to get information about active rules on product level?
Answer: On the line item, you have the field_unit_price field. Inside of that field's data attribute, you'll find information about the discounts that are applied to that product:
array(1) {
  ["components"]=>
  array(2) {
    ...
    [1]=>
    array(3) {
      ["name"]=>
      string(22) "discount|discount_test"
      ["price"]=>
      array(3) {
        ["amount"]=>
        float(-240)
        ["currency_code"]=>
        string(3) "USD"
        ["data"]=>
        array(2) {
          ["discount_name"]=>
          string(13) "discount_test"
          ["discount_component_title"]=>
          string(5) "Test"
        }
      }
      ["included"]=>
      bool(true)
    }
  }
}

Iterate over the components. If there is a discount applied to one of the items, you'll find one with a name that begins with discount|.  Then you can then load that discount and grab more information about it:
$discount = entity_load('commerce_discount', array('discount_test'));

From here, if you've added dates, the date fields will be accessible on the field commerce_discount_date.


Is there any notation software that supports unconvential notation like Schenker graphs?

Question: What is the best free or cheap music editing software available? I am looking for something to write and edit scores with. I know that Finale and Sibelius are the best on the market, but I wouldn't use them enough to justify the price.
I don't need many features, though here are a few that I could really use:

Audio play back
Ability to write without a time signature
Able to draw non-conventional notation (i.e. Schenker graphs)

Here's an example of what I'd like to draw:
Comment: I'm not sure if it supports free-form notation, but Finale Notepad used to be free.  Not sure when it stopped but I believe 2007 was what I used, I'm sure you could find it with a web search.
Answer: Check out Lilypond: http://lilypond.org/  It's free and powerful, and although it won't do audio playback, I believe it can do the rest of what you ask.  It's text-based, and if you are at all familiar with TeX or LaTeX, Lilypond will feel similar.  It has a somewhat steep learning curve, but there are some GUIs in active development that make things easier, and there's also some software that allows for input via MIDI keyboard.
Edit: Seems Lilypond can output MIDI files, so presumably you could get audio playback that way.
Comment: Ease is.....relative.  While lilypond does give you a great amount of control over the output, it is fairly time-consuming to make the source file that gets interpreted.
Comment: It's a matter of preference. Some people prefer the source code / compiled output model.
Comment: Thanks Alex. After asking this question, I did a google search and came upon lilypond. Seems like it will be the perfect combination of ease of use and control of output. I like the text-based input too. Gets to my nerdy side :)
Comment: @Babu, I spent about 2 hours last night trying to draw a simple Schenker graph. I love the complete control over the output, but I agree it is very time consuming. I had to give up and just do it by hand.
Answer: With Lilypond, the example of the OP could be drawn like follows:
<code>\score {
  \relative c {
    \time 2/4
    \clef bass
    \key f \major
    << { \override NoteColumn.ignore-collision = ##t \stemDown
         \phrasingSlurDown \phrasingSlurDashed
         \once \override NoteHead.duration-log = #1
         \once \override Beam.positions = #'(-6.47 . -6.47)
         \once \override PhrasingSlur.control-points = #'((1 . -.5) (3 . -5) (22 . -5) (24 . -3))
         f8*4[\( ~ \hide Stem f8*4] ~ f4*2(
         \newSpacingSection g4 a)(
         \phrasingSlurSolid \undo \hide Stem f,\)\()(
         \once \hide Stem c') d\)\(( \once \hide Stem a')
         \once \override Stem.length = #9.27
         \newSpacingSection \time 4/4
         bes8*8/3\)\( \once \hide Stem e,4*4/3( f)
         \newSpacingSection \time 8/2
         \once \hide Stem d4*2
         \once \override Beam.positions = #'(-5.97 . -5.97)
         \once \override Beam.transparent = ##f
         \once \hide Stem e8*4[\)
         \once \override NoteHead.duration-log = #1
         f8*16] } \\
       { \hide NoteHead \hide Stem \slurUp s2*6
         \once \override Slur.control-points = #'((1 . 3.5) (3 . 5) (11 . 4) (13.5 . 1))
         bes2( bes,4*4)
         \undo \hide Stem e4*2 } \\
       { \hide NoteHead \hide Stem s2*6
         \once \override Slur.control-points = #'((1 . -7) (10 . -10) (17 . 7.5) (20 . -.5))
         bes'2( s4 e,4) } >> \bar "|."
  }

  \layout {
    \omit Score.TimeSignature
  }
}
</code>
Comment: This is impressive. Maybe add a brief introduction paragraph about lilypond to make the answer perfect.
Answer: I agree with everyone else that is suggesting Lilypond. Here is a Linux Journal article on creating Schenker Graphs with Lilypond.
Answer: MuseScore
is getting some attention. It's free, cross-platform, and imports and exports MusicXML. I have not tried it.
Answer: As little addon to the Lillypond suggestion:
Check out this snippet from the Lilypond Snippet Repository

I also found the channel #lilypond on Freenode being quite a good resource when getting stuck with something.
Answer: rosegarden is another option.  It's mostly meant to be used as a MIDI sequencer/DAW, but has a score facility which I believe will let you edit scores directly.  It's only available for linux.
Comment: Rosegarden uses lilypond as a backend for generating scores, which is nice.  I'm unsure as to whether or not it supports everything that lilypond supports in terms of that......uh.....whatever you're doing in that picture is called! :P
Answer: Denemo is an open source tool for writing scores. It appears to be quite powerful (and has a lilypond interface as well as playback), but the documentation is weak. I couldn't even figure out how to do score writing with bass-line and melody in the same staff, although I know it's possible.


Find most frequent group of 3 words in a sentence

Question: Suppose I have a text like
text="I came from the moon. He went to the other room. She went to the drawing room."

Most Frequent group of 3 words here is  "went to the"
I know how to find most frequent bigram or trigram but I am stuck in this.I want to find this solution without using NLTK library.
Comment: Why is this question put on hold? Three people provided suitable answers so they obviously understood what was asked for.
Comment: Is there any reason you don't want to use NLTK?
Comment: jst trying without nltk bro..
Answer: nltk makes this problem trivial, but seeing as you don't want such a dependency, I have included a simple implementation using only core libraries. The code works on python2.7 and python3.x, and uses collections.Counter to count frequencies of n-grams. Computationally, it is O(NM) where N is the number of words in the text and M is the number of n-grams being counted (so if one were to count uni and bigrams, M = 2).
import collections
import re
import sys
import time

# Convert a string to lowercase and split into words (w/o punctuation)
def tokenize(string):
    return re.findall(r'\w+', string.lower())

def count_ngrams(lines, min_length=2, max_length=4):
    lengths = range(min_length, max_length + 1)
    ngrams = {length: collections.Counter() for length in lengths}
    queue = collections.deque(maxlen=max_length)

    # Helper function to add n-grams at start of current queue to dict
    def add_queue():
        current = tuple(queue)
        for length in lengths:
            if len(current) >= length:
                ngrams[length][current[:length]] += 1

    # Loop through all lines and words and add n-grams to dict
    for line in lines:
        for word in tokenize(line):
            queue.append(word)
            if len(queue) >= max_length:
                add_queue()

    # Make sure we get the n-grams at the tail end of the queue
    while len(queue) > min_length:
        queue.popleft()
        add_queue()

    return ngrams

def print_most_frequent(ngrams, num=10):
    for n in sorted(ngrams):
        print('----- {} most common {}-grams -----'.format(num, n))
        for gram, count in ngrams[n].most_common(num):
            print('{0}: {1}'.format(' '.join(gram), count))
        print('')

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Usage: python ngrams.py filename')
        sys.exit(1)

    start_time = time.time()
    with open(sys.argv[1]) as f:
        ngrams = count_ngrams(f)
    print_most_frequent(ngrams)
    elapsed_time = time.time() - start_time
    print('Took {:.03f} seconds'.format(elapsed_time))

Answer: text="I came from the moon. He went to the other room. She went to the drawing room."
fixed_text = re.sub("[^a-zA-Z ]"," ",text)
text_list = fixed_text.split()
print Counter(" ".join(text_list[i:i+3]) for i in range(len(text_list)-3)).most_common(1)

I guess ... maybe?
>>> text="I came from the moon. He went to the other room. She went to the drawi
ng room."
>>> fixed_text = re.sub("[^a-zA-Z ]"," ",text)
>>> text_list = fixed_text.split()
>>> print Counter(" ".join(text_list[i:i+3]) for i in range(len(text_list)-3)).most_common(1)
[('went to the', 2)]
>>>

Comment: This is not working in python 2.7
Comment: i had a couple of typos ...
Comment: well you can lead a horse to water, but you cannot make him drink I guess... are you also hoping someone can just do your interviews for you? or perhaps your school tests?
Answer: import string

text="I came from the moon. He went to the other room. She went to the drawing room."

for character in string.punctuation:
    text = text.replace(character, " ")

while text != text.replace("  ", " "):
    text = text.replace("  ", " ")

text = text.split(" ")

wordlist = []
frequency_dict = dict()

for i in range(len(text)-3):
    wordlist.append([text[i], text[i+1], text[i+2]])

for three_words in wordlist:
    frequency= wordlist.count(three_words)
    frequency_dict[", ".join(three_words)] = frequency

print max(frequency_dict, key=frequency_dict.get), frequency_dict[max(frequency_dict, key=frequency_dict.get)]

Output: went, to, the 2
Unfortunately lists are not hashable. Otherwise it would help to create a set of the three_words items.


Combinatorial proof of $\sum_{k=0}^n k \cdot k! = (n+1)! -1$

Question: Is there a nice combinatorial proof of the following identity?  (That is, by showing that both sides count the same thing.)
$$\sum_{k=0}^n k \cdot k! = (n+1)! -1 $$
I was searching Wikipedia for nice identities to assign to my students for a homework on combinatorial proof, and thought this one looked innocent enough, but then realized I couldn't solve it myself.
Perhaps we should take the set of permutations of $n+1$ letters and partition it in some clever way (maybe the $-1$ suggests that the identity should be set aside), but I can't see what that might be.
Of course it is very easy to prove by induction; that's not what I'm looking for.
Answer: $k\cdot k!$ is the number of permutations of the $(n+1)$ symbols $0,\,1,\,\dotsc,\, n$ such that $k$ is the largest symbol that is not kept fixed. (Symbol $k$ can be mapped to the $k$ places $0,\,\dotsc,\,k-1$, the $k$ smaller symbols then can be placed arbitrarily in the $k$ left free places.) So
$$\sum_{k=0}^n k\cdot k!$$
is the number of non-identity permutations of the $(n+1)$ symbols. On the other hand, that number is of course the total number of permutations of $(n+1)$ symbols minus one.
Not the best combinatorial proof ever, but meh.
Comment: Ah, very nice.  I was thinking about partitioning based on some set of elements being fixes, but couldn't come up with the right way to do it.
Answer: I'm not sure this constitutes a 'combinatorial proof', but have you tried proof by induction?
We hope to find that if the statement is true for some n, then it will also be true for n+1.
S[k=0 to n+1] k.k! = S[k=0 to n]k.k!  +  (n+1)(n+1)! = (n+1)! - 1 + (n+1)(n+1)! = (n+2)! - 1
and this is indeed what you get if you replace n with n+1  on the RHS of your original equaton.
It is trivial to see that the statement is true for n=0, therefore it is true for all the natural numbers.
The above is only an outline proof, but do you get the idea?
p.s. sorry I don't know how do do the equations nicely!
Comment: Sorry - I just re-read the original post and realise that this is not what you were looking for.


If the $p$-core of a finite group $G$ is trivial, what can be deduced from that about $G$

Question: I am looking for (textbook) references for the following situation:

If $G$ is a finite group and its $p$-core $\mathcal{O}_p(G)$ is trivial, what can be deduced from this about $G$?

(Do groups with this property have a special name?)
Thanks.
Answer: Very little, I'm afraid. For example, $G$ could be a $q$-group for some prime $q\neq p$. Or it could be a simple group, or a symmetric group. Notice that the group $G/O_p(G)$ always has your property.
Do you have it in any specific context? For example, a group with no $p$-core as the centralizer of a $q$-element in a simple group?
Comment: Oh ok, that's a pitty. I don't have any specific context, but I would be particularly interested in the case $p=2$. Is the situation any better then? Thanks a lot.
Comment: Not particularly. The main use for the $p$-core was in fact for all primes other than $2$. Define $O(G)$ to be the product of the $p$-cores for $p\neq 2$, called the *core* of $G$. If $t$ is an element of order $2$ in a simple group $G$, then one is interested in the structure of $H=C_G(t)$, and in particular $H/O(H)$. Part of the big issue in the classification of finite simple groups was the fact that $O(H)$ can be non-trivial. If it were not then lots of knotty problems go away.
Comment: Ok, thank you very much.