How authentic is the sound if I use a real effect pedal before GarageBand?

Question: If I consider this setup :
Electric guitar -> (real) distortion effect pedal -> audio interface -> garageband -> maybe no need to use virtual pedals from garageband
How authentic will the (real pedal) sound be?
Comment: Can you explain more about what "authentic" means to you here? The post-pedal sound is what it is. Any further change would come from the audio interface.
Comment: Real distortion effect pedals are designed to work well with the characteristics of a real amplifier's circuitry and loudspeaker.  You will likely get a very harsh tone.  I don't use GarageBand, so I don't know what amplifier simulations are available.
Comment: What effects chain are you trying to "authentically" emulate? I assume you either don't know the effects chain details or don't have all the exact equipment of some particular set up.
Answer: I'm gonna promote this highly opinionated comment to an actual answer…
If you don't already own the pedal… then don't bother buying one. "Authentic" is in the ear of the beholder - if the beholder doesn't know you used a software pedal, they will never, never, ever, be any the wiser.
I've been using software amps & pedals for 20 years, & even though all the online blogs are still arguing over 'which is best', no-one has ever asked me if my guitars & amps are 'real'. They're not, even my guitars are software-driven. Variax, 50 guitars in one guitar.
No-one can actually tell, unless they have a camera & mic pointed at them, then suddenly they think they can… because 'likes/subscribes'.
Garage Band has the usual assortment of modelling amps & pedals, cabs & mic setups, same as most DAWs these days. I don't use GB myself, so I don't know the 'quality' of these [though bear in mind GB is the little brother of Logic, which is no slouch], but honestly, this is mature technology these days, and has been for the best part of 20 years. I very much doubt anyone would be able to tell the difference once it's in a mix. Intro to amps and pedals in GarageBand on Mac
You could run a real pedal directly into GB if you have an appropriate audio interface, then route it straight through a software amp/cab/mic… I just don't really see the point.
Comment: I have a hunch that the OP may think that a typical rock/blues electric guitar sound comes from a (real or virtual) _distortion pedal_, and is unaware of what (real or virtual) guitar _amps_ and _cabinets_ do...
Comment: @Tetsujin A book, a book!    (Wait, what do you mean by "déjà-vu"?)
Comment: And if the sound is a little harsh entering the system, that's what an EQ VST plugin is for. For what its worth, I use an audio interface for some effects (with a line2amp box) and have reverted to using amp and pedals mostly for the wave of chest punching audio I can get without investing in newer expensive monitors. There is very little (no) difference between the audio interface "inserted" (bypassed or not) and only "real" pedals. IMO Real blues/rock sound comes from wah, aggressive compression with level cranked and a gain pedal (tube screamer). Gain. Lots of gain.
Answer: Unless your pedal has a "mixer" output or "amp simulated" output, you will still need to use a guitar cabinet simulation in garageband to get a realistic guitar sound.
The direct output from these pedals is usually overly bright and harsh, as they are designed with the understanding that the sound will be muffled by the guitar cabinet at the end of the signal chain.  Luckily, there is no shortage of cabinet simulations, and your pedal will change the guitar's sound in the same way as if you were using a real amp.
As far as "authentic", "real" distortion pedals were originally just an imitation of the real distortion that comes from overdriving an amplifier.  So, to that effect, it's not really more authentic than a virtual distortion plugin on your PC.  There are some great distortion plugins available as well- look for amp sims, not just pedal sims.  I think you can find something you like.
Comment: Overdriven amps are where "overdrive" comes from, and for some really crunchy distortion, that was an accidental invention. Guitarist would accidentally break their amps, (torn speakers, busted tubes, loose wiring) and play on it anyways.  Distortion is just a sound wave getting muddled. How ot happens doesn't matter much, so long as you like the sound.
Comment: If the pedal is actually overdriving the amp input, overdriving an audio interface input is not going to sound the same even if there is a full amp simulation running behind it. But many overdrives are more distortion pedals that are inspired by overdriven tube amp than boosts that overdrive the amp vehind them.
Comment: I think you need to watch for bit clipping a little more when injecting into the virtual environment, but as long as the OP watches the levels
Answer: It will sound authentically like the sound of 'Electric guitar -> (real) distortion effect pedal -> audio interface -> garageband'. Which you may be able to replicate with 'virtual pedals' in Garageband. Or maybe to you 'authentic' means the sound of an over-driven tube amplifier into a Marshall stack?  Does the pedal reproduce that for you in a way that makes you happy?
How many of these three methods are available to you?   Try them all!


How do I draw the graph for y = $\frac{KQx}{[R^2+x^2]^{3/2}}$

Question: How do I draw the graph for y = $\frac{KQx}{[R^2+x^2]^{3/2}}$.
Actually this is from a physics question which requires me to draw the graph of electric field (E or y) caused by uniformly charged ring against distance x from ring. Here k,Q and R are constants. The graph given in my book is similar to this : I understand that maxima are at x= plus or minus R/√2, when dy/dx = 0. Also when x = 0 or infinity y will be zero. However why is the graph curved? Isn't it possible for it to be composed of straight lines? Am I missing out some major concept here? Please help me.
Comment: Of course you can approximate any function with linear partitions.
Comment: Analyze the second derivative; it will be very helpful to understand the behavior of the function.
Comment: *No* algebraic function, other than the trivial cases $ax+b$, has any straight line segment in its graph. So you don't need to worry on that account.
Comment: @ClaudeLeibovici is there an easier way to do it? These questions are JEE pattern and must be done in a few minutes at the most. Is there an intuitive way of knowing if the graph is curved?
Answer: Here is a quick way to get a feel for the graph:

Note the antisymmetry: If you replace $x$ by $-x$, $y$ changes sign but keeps its magnitude. So you only need to understand the part where $x>0$, say, and then reflect that through the origin.
When $x$ is small compared to $R$, then $x^2$ in the denominator is small compared to $R^2$, so you get an approximation by throwing away the $x^2$ term. Then the curve is simplified to $y \approx KQx/R^3$ (a straight line through the origin).
Similarly, when $x$ is large compared to $R$, you can throw away $R^2$ instead, leading to $y\approx KQ/x^2$. I am sure you know what its graph looks like.

Below is a figure showing the original function, in red, and the two approximations in blue. Note that the red curve lies below the blue curves. This should not be surprising, given the terms thrown away. Note how the red curve starts close to one blue curve, then it has to bend somehow to start matching the other one.
To get further, you'd have to do the second derivative song and dance, but this simple reasoning gets you a good idea what to expect.


Using expand in pipe replaces values

Question: I currently have a service where i fetch some templates with help of expand to display them in the view. The idea is to keep fetching untill i have everything.
However, when i pipe the expand it replaces the values instead of adding them, how do i solve this?
Example:
templates$: Observable<Template[]>;
let count = 0;

this.templates$ = this.templateService.getTemplates(0, 5).pipe(
      expand(result => {
        count += result.length;
        if (result.length === 5) {
          return this.templateService.getTemplates(count, 5);
        } else {
          return empty();
        }
      })
    );

Comment: I'm pretty sure you need to add a `reduce` operator after the `expand`.
Comment: Which version of RxJs ?
Answer: expand does not replace value, it rather emits each time you receive the templates in groups of five. In your view, if you use template$ | async, you'll only see the last result.
To collect all templates, you can use scan operator.
templates$: Observable<Template[]>;
let count = 0;

this.templates$ = this.templateService.getTemplates(0, 5).pipe(
      expand(result => {
        count += result.length;
        if (result.length === 5) {
          return this.templateService.getTemplates(count, 5);
        } else {
          return empty();
        }
      }),
      scan((acc, curr) => acc.concat(curr))
    );

You could also use reduce operator the same way, if you don't want to show intermediate results.
Comment: Thank you, this is exactly what i was looking for.

Using expand in pipe replaces values


Textbox multiline imprimindo apenas ultimo item

Question: Eu estou usando TextBoxt Multiline para fazer a "emissão" do relatório no próprio sistema.
Ta imprimindo, porém, aparece a seguinte mensagem: "System.Windows.Forms.TextBox" e em seguida, o dado.
public Formulário()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    using (StreamReader ler = new StreamReader(@"escrevesaida.txt"))
    {
        string leitor;

        while ((leitor = ler.ReadLine()) != null)
        {
            textBox1.AppendText($"{leitor}{Environment.NewLine}");
        }
    }
}

Answer: O problema é que no Text do textBox, para cada linha que ele lê você está atribuindo o valor, substituindo o valor que tinha anteriormente.
textBox1.Text = leitor;

O correto seria concatenar, ou seja, juntar os resultados de cada linha. Da seguinte forma:
textBox1.Text += leitor;

Comment: Correto, Resolvemos um problema. Só que ta aparecendo o resultado precedido de
System.Windows.Forms.TextBox, Text: 123
Comment: Está aparecendo: `System.Windows.Forms.TextBox, Text: 123` no campo?
Comment: Sim Sim, o dado correto é 123, porém aparece essas coisas antes ai.
Comment: em algum lugar do seu código, você deve estar fazendo: `textBox1.Text += textBox1;`
Comment: Não, porque é uma tela nova, e, a função é privada.
Comment: Dê uma olhada se você realmente não está fazendo isso por acidente...
Comment: Eu até olhei, mas não tem nada. Inclusive, aí está 90% do código. Anterior à isso tem as partes padrões do Visual ... As funções padrões..
Answer: Se o objetivo é separar linha a linha, a melhor forma será:
string leitor;

while ((leitor = ler.ReadLine()) != null)
{
    textBox1.AppendText($"{leitor}{Environment.NewLine}");
}

Colocando o seguinte código antes do while:
leitor = ler.ReadLine();
textBox1.Text = leitor;

Estava a "apanhar" a 1ª linha e só depois as restantes. Pode colocar tudo dentro do ciclo.

Em relação ao texto System.Windows.Forms.TextBox, Text: 123, realmente, como o @ThiagoMagalhães referiu, parece ter origem em textBox1.Text += textBox1; ou algo do género. A não ser que isso já venha do ficheiro...
Comment: O Código todo da função ficou assim... E ainda da aquela mensagem "System..."

        private void button1_Click(object sender, EventArgs e)
        {
            using (StreamReader ler = new StreamReader(@"escrevesaida.txt"))
            {

                string leitor;

                while ((leitor = ler.ReadLine()) != null)
                {
                    textBox1.AppendText($"{leitor}{Environment.NewLine}");
                }

            }
        }
Comment: Poste o código da classe toda na sua questão, pode ser que encontremos algo.
Comment: Como é que foi criado o ficheiro "**escrevesaida.txt**"? Numa outra aplicação? Manualmente?
Comment: Foi criado no sistema. Eu uso o bloco de notas para inserir dados de saída numa outra tela. Porém abro e fecho o StreamWrite na tela em questão.
Comment: Pode colocar o conteúdo do ficheiro na sua questão? Assim conseguiríamos validar a solução do nosso lado.
Comment: São dados inseridos através do programa, de forma manual. Coloquei dados aleatórios. São dados aleatórios, números inteiros.
Comment: Como está a utilizar o `StreamWriter`? Por acaso não está a fazer o seguinte: `sw.WriteLine(textBox1);` ao invés de `sw.WriteLine(textBox1.Text);`?
Comment: string valor = txtvalor.ToString();
Comment: Estou usando assim.
Comment: Aí é que está o erro :). Tem que fazer `string valor = txtValor.Text;`, caso contrário está a atribuir uma representação em texto do tipo do controlo.
Comment: Ainda assim da o mesmo erro. ;/
Comment: Acho que deu certo agora.
Comment: Ainda bem! Marque a resposta como útil e/ou correta, se o ajudou :)
Comment: Essa é minha quarta pergunta aqui, eu não sei como faz isso. MUITO OBRIGADO PELA AJUDA.. Foi de grande valia.
Comment: Se puder me orientar, agradeço, e já faço aqui .


"sql: no rows in result set"

Question: I am handling user auth data posted to my Go backend through an HTML form. I am building on some boilerplate to learn Go better.
My problem is what the following func returns:
func (ctrl UserController) Signin(c *gin.Context) {

  var signinForm forms.SigninForm
  user, err := userModel.Signin(signinForm)

  if err := c.ShouldBindWith(&signinForm, binding.Form); err != nil {
      c.JSON(406, gin.H{"message": "Invalid signin form", "form": signinForm})
      c.Abort()
      return
  }

    if err == nil {
        session := sessions.Default(c)
        session.Set("user_id", user.ID)
        session.Set("user_email", user.Email)
        session.Set("user_name", user.Name)
        session.Save()

        c.JSON(200, gin.H{"message": "User signed in", "user": user})
    } else {
        c.JSON(406, gin.H{"message": "Invalid signin details", "error": err.Error()})
    }

}

The first if statement validates the input, and that works fine (error if the email isn't in proper email format, no error if it is). However, if input is properly validated, the else clause of the second statement is triggered, and the following JSON is returned:
{
error: "sql: no rows in result set",
message: "Invalid signin details"
}

It is probably useful to also post the relevant code in my User model:
//User ...
type User struct {
    ID        int    `db:"id, primarykey, autoincrement" json:"id"`
    Email     string `db:"email" json:"email"`
    Password  string `db:"password" json:"-"`
    Name      string `db:"name" json:"name"`
    UpdatedAt int64  `db:"updated_at" json:"updated_at"`
    CreatedAt int64  `db:"created_at" json:"created_at"`
}

//UserModel ...
type UserModel struct{}

//Signin ...
func (m UserModel) Signin(form forms.SigninForm) (user User, err error) {

    err = db.GetDB().SelectOne(&user, "SELECT id, email, password, name, updated_at, created_at FROM public.user WHERE email=LOWER($1) LIMIT 1", form.Email)

    if err != nil {
        return user, err
    }

    bytePassword := []byte(form.Password)
    byteHashedPassword := []byte(user.Password)

    err = bcrypt.CompareHashAndPassword(byteHashedPassword, bytePassword)

    if err != nil {
        return user, errors.New("Invalid password")
    }

    return user, nil
}

How do I resolve the sql: no rows in result set error?
Answer: You should change the order of operations in your code.
At first you need to get data from request with if err := c.ShouldBindWith(&signinForm, binding.Form); err != nil { and after that you need to try get data from database with user, err := userModel.Signin(signinForm)
Comment: Good point. I'm super new to Go so I'm likely to miss such subtleties in the drive to simply get my code working.
Comment: I still get the same error. `f err := c.ShouldBindWith(&signinForm, binding.Form); err != nil {` shouldn't effect this issue, as it is merely validating the form.

I haven't written the user signup route yet, so there is currently nothing in the database. Would that be causing this error, perhaps?
Comment: @223seneca Pavlo's answer is correct, your ordering is just wrong, it would never work even if you had rows in your database because without setting the request's data to the `singinForm` value, which is done by the binding mechanism, you would always be passing an empty `form.Email` to the query and an empty `form.Password` to the bcrypt's compare function.
Comment: @mkopriva Regarding your comment about the error `sql: no rows in result set`, I was unsure given the fact that I find that behavior strange (it's odd that it throws an error, as the possibility that there just aren't any users yet doesn't seem error-worthy). I can do without the condescension though, thanks.
Comment: @223seneca and regardless of whether your order would work or not you should be very careful about passing unvalidated data to your database.
Comment: @223seneca the db and the db driver doesn't know or care what the tables represent in your app, whether no-row is ok or not that's not their business. If your signin functionality should continue working if no user with given email exists, then your `UserModel.Signin` should check specifically for the `sql.ErrNoRows` value and return nil or whatever you want.
Answer: There are good reasons for this. Ideally it tries to read paths by the separator, meaning /path/abcd/ and /path/abcd are different. abcd IS the resource in the latter while the resource lies somewhere within abcd in the former. With that in mind, then it will not be able to route properly to /path/abcd if you also have a path /path as well. In order to remove that ambiguity as to which handler to use, you need to mention the handler for the more specific path ie, /path/abcd before the more generic one /path.

"sql: no rows in result set"


Selenium Webdriver python headless não identifica elementos

Question: Boa tarde, estou a programar um arquivo python utilizando selenium. Alcançei meu objetivo e o arquivo rodou direitinho. Eu fui além e decidi usar o headless, já no início da execução do arquivo recebo um erro:

in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".whsOnd zHQkBf"}
(Session info: headless chrome=86.0.4240.198)**

Indicando que ele não foi capaz de identificar o elemento na página, só que esse erro persiste também ao tentar usar o selector de xpath, class, full xpath e id.
Meu código:
from time import sleep
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=options, executable_path='C:/Users/Thunder/drivers/chromedriver.exe')
driver.get('https://classroom.google.com/u/1/c/MTIzNzc4MTM2NjY5')
sleep(8)
logan = driver.find_element_by_id('identifierId')
logan.send_keys('e-mail')
logan.send_keys(u'\ue007')

Comment: Já tentou usar o option = Options() | option.headless = True?
Comment: Pode especificar melhor?
Answer: Olá! Pra especificar melhor meu comentario vou postar o que imagino ser a resposta, pelo que vi no teu código tu não importou o chrome options, imagino que só isso resolve teu problema:
from selenium.webdriver.chrome.options import Options

Se isso não resolver tenta colocar essa linha de código no lugar da tua 4° linha:
option = Options()
option.headless = True

Se o problema for o headless vai rodar certinho, porque pelo que entendi o código funcionou só que quando tu foi usar o headless não funcionou mais
Comment: Não funcionou amigo. DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path='C:/Users/Thunder/drivers/chromedriver.exe', chrome_options=option)
Answer: Opa, tenho um modelo aqui que uso nos codigos para executar tanto no modo background quanto no modo normal:
-----------------------------------------------------
Modo Chrome Explicito (Para ativar descomente a linha abaixo e comente o 'Modo Chrome Background')
n = webdriver.Chrome()
-----------------------------------------------------
Modo Chrome Background (Para ativar descomente as linhas abaixo e comente o 'Modo Chrome Explicito')
options = webdriver.ChromeOptions()
options.add_argument("--headless")
n = webdriver.Chrome(options=options)
-----------------------------------------------------
Veja se isso te ajuda.


Cumulative distribution function of mixed variables

Question: Given the probability density function:
$
\begin{equation}
  f_{X, Y}(x, y)=\begin{cases}
    \frac{xy}{3}, & \text{if } x=1,2,3 \text{ and } 0 < y < 1.\\\\
    0, & \text{otherwise}.
  \end{cases}
\end{equation}
$
What is the c.d.f. of $(X, Y)$?
Ok, so cheking the marginals we see that X and Y are independent:
$P(X=x)=(x/3)\int_0^1 y dy \\\\ =\frac{x}{6},\:x=1, 2, 3.$
$f_Y(y)=(y/3)\sum_{x=1}^3x \\\\ = 2y,\:0 < y < 1.$
$f_{XY}(x, y)=P(X=x)f_Y(y)$
The joint cdf has a analog propertie of independence:
$F_{XY}(x, y)=F_X(x)F_Y(y)$
My question is, in this case, the required cdf is simply
$F_{XY}(a, b) = \frac{1}{3} \sum_{x=1}^{a}x\int_0^{b}y\;dy$
Comment: @Zhanxiong That appears to be what was intended, but I am reluctant to read that much into the question.  It's always better when the OP tells us what they mean.
Comment: Note that cdf stands for cumulative distribution function, not cumulative density function. Please correct the title of the question.
Comment: This is not a PDF: it integrates to $0,$ not $1.$  Could you please clarify what you mean?
Comment: @whuber I think the measure with respect to which is not Lebesgue measure on $\mathbb{R}^2$, it is a product measure of a (scaled) counting measure and a Lebesgue measure on $\mathbb{R}^1$.  In this way the density still integrates to $1$.
Comment: @whuber, Zhanxiong is correct. I apologize if the question wasn't clear, I'm not familiarized with Measure Theory definitions.
Answer: Yes, your CDF expression is correct for $a \in \{1,2,3\}$ and $b \in [0,1]$.
In general, for discrete $X$ and continuous $Y$ you have
$$
F_{X,Y}(a,b)= \sum_{x\leq a}\int_{-\infty}^b f_{X,Y}(x,y)dy
$$
As you pointed out, when the random variables are independent this factorises into
$$
\left(\sum_{x\leq a}f_{X}(x)\right) \left(\int_{-\infty}^b f_{Y}(y)dy\right)=F_X(a)F_Y(b)
$$


Change domain based on location

Question: I want to create one website for multi-countries and each country's website content should be different according to the selection. But the file and database should be single.
For example,
For Singapore version: example.com/sg/
For Honk kong version: example.com/hk/
The website is redirected based on the user location and can also be switched manually. When a user from Singapore enters the url it first redirects to the example.com/sg/. There should also be an option to switch the domain manually by the user. If user selects Honk Kong manually the website is redirected to example.com/hk/. How is this possible?
Answer: U can take client ip and then use some library like Geocoder to create redirection based on country.

Change domain based on location


OpenLDAP replication error

Question: I have 2 OpenLDAP servers with replication activated and everything used to work fine.
A few days ago, the "replica" account's password expired. And since then I was unable to make replication work again. I tried changing password, deleting/recreating the account, unsuccessfully.
I noticed a strange thing, I use a software to read my LDAP data and, when I change the password of the "replica" account, it's different on my 2 servers. (see screenshot)
replica_passwords_screenshot
Any ideas ?
Thanks in advance !
Edit :
slapd.log shows these two errors (alternatively)
ldap_sasl_bind_s failed (49) or ldap_sasl_bind_s failed (-1)
EDIT2 :
ldapsearch from replica to main works
ldapsearch from main to replica throws this error : ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)
Answer: I deleted everything from replica and made a clean install.
Works fine now.
More details here : https://www.reddit.com/r/sysadmin/comments/nqgsp0/openldap_replication_error/

OpenLDAP replication error


How to generally characterize $\operatorname{Ext}^n$?

Question: There's this well known characterization of the first $\operatorname{Ext}$ group of two objects in a abelian category:

There is an isomorphism between $\operatorname{Ext}^1(B,A)$ and the group of equivalence classes of short exact sequences of the form $A \hookrightarrow \_\_ \twoheadrightarrow B$. If $A$ and $B$ are abelian groups, these are called the group extensions of $B$ by $A$.

Can we say anything crisp like this to characterize $\operatorname{Ext}^2$? Or $\operatorname{Ext}^n$ in general? It looks like we can, but I am unfamiliar with $n$-extensions and the construction of the Baer sum of two chains.
Comment: I don't understand your question. You have an answer in the link. What is it you don't understand?
Comment: @PedroTamaroff After staring at that section on Wikipedia for a bit, it does look a bit more straightforward than I thought. Initially the Baer sum looked scary, but that's fine, and just serves to put a group structure on $\operatorname{Ext}^n$.
Answer: There is this description in terms of extensions of length $n$, but as far as I know it's not useful for anything; in any case I've never used it for anything. Here are three descriptions that are actually useful:

$\text{Ext}^n(A, B)$ is the set of maps from $A$ to $B[n]$ (the chain complex which is $B$ concentrated in degree $n$) in the derived category. This is maybe the easiest way to see that for all $A, B, C$ there are natural maps $\text{Ext}^n(A, B) \otimes \text{Ext}^m(B, C) \to \text{Ext}^{n+m}(A, C)$ (it's just given by composition in the derived category); I think thinking about this map in terms of extensions is a pointless headache.
$\text{Ext}^n(A, B)$ classifies extensions of $A$ by $B[n-1]$; one way to say this is that it classifies chain complexes $C$ fitting into a short exact sequence $0 \to B[n-1] \to C \to A \to 0$, up to a suitable equivalence relation.
$\text{Ext}^n(A, B)$ is the $n^{th}$ homology of a chain complex $\text{RHom}(A, B)$ called the derived hom. In many situations it's not enough to consider the Ext groups and one must consider this entire chain complex, for example if $A = B$ derived endomorphisms have a dg algebra structure containing more information than just the corresponding graded algebra given by taking homology.
Comment: I would disgree with your comment in the first sentence. The exterior product in Ext is not hard to understand either in terms of resolutions, or of concatenation of extensions, or of total complexes of tensor products of extensions. All of these do have uses, for example in spectral sequences of change of rings. Your statements in the derived category have to be proved *somehow*, and I cannot see how there is any loss of difficulty here. I would say it is a nice way to see it, but I would be reluctant to say its the easiest way!
Comment: It would be interesting to note that in your last example, one can transfer the DG-algebra structure in the derived Hom to an $A_\infty$-structure on Ext, like in the case of the Yoneda algebra of a ring, which one can compute as the cohomology of $\text{End}(P)$ where $P$ resolves the trivial module. This is even more information than an algebra structure!
Answer: You already found a description via equivalence classes of $n$-extensions in the link. This is described in more detail in some homological algebra books like those of Weibel and Hilton and Stammbach. In case the abelian category has some more properties, for example it is a module category, one can define the syzygy $\Omega^n(M)$ of a module $M$ as the $n^\text{th}$ kernel in a projective resolution of $M$. In this case one has $\operatorname{Ext}^n(B,A)=\operatorname{Ext}^1(\Omega^{n-1}(B),A)$ and one has a nice description of $\operatorname{Ext}^n$ via the description of $\operatorname{Ext}^1$ using short exact sequences. Another nice description is possible using derived categories and their $\operatorname{Hom}$, see for example the last chapter of the book by Weibel, or the book by Gelfand and Manin.
Comment: I'll also add that a clear explanation is given in MacLane's book Homology.
Answer: For the sake of keeping this post self-contained, I should include a description of how to characterize $\operatorname{Ext}^n$ as $n$-extensions as outlined in this section on Wikipedia.

For two objects $A$ and $B$ in an abelian category, define an $n$-extension of $B$ by $A$, as an exact sequence
$$
  0
  \to A
  \to X_1
  \to \dotsb
  \to X_n
  \to B
  \to 0
\,.
$$
Then we want to say two $n$-extensions are equivalent if there are maps $\{f_1, \dotsc,f_n\}$ such that every square in this diagram commutes:
$$
  \require{AMScd}
  \begin{CD}
     0 @>>> A @>>> X_1 @>>> \dotsb @>>> X_n @>>> B @>>> 0\\
     @.@V{\mathrm{id}}VV @V{f_1}VV @. @V{f_n}VV @V{\mathrm{id}}VV \\
     0 @>>> A @>>> Y_1 @>>> \dotsb @>>> Y_n @>>> B @>>> 0\\
  \end{CD}
$$
This relation is clearly reflexive and transitive. Showing that it is symmetric, and can indeed be regarded as an honest equivalence relation takes some work (look for a proof of the short-five lemma to help). Under this relation, there is a set bijection between equivalence classes of $n$-extensions and $\operatorname{Ext}^n(B,A)$.
We can strengthen this result by imposing a group structure on this set of equivalence classes and saying that it and $\operatorname{Ext}^n(B,A)$ are isomorphic as groups. Let $X_n \times_B Y_n$ be the pullback of $X_n$ and $Y_n$ over $B$, and let $X_1 +_A Y_1$ be the pushout of $X_1$ and $Y_1$ over $A$. Define the Baer sum of the two $n$-extensions above as
$$
  0
  \to A
  \to X_1 +_A Y_1
  \to X_2 \oplus Y_2
  \to \dotsb
  \to X_{n-1} \oplus Y_{n-1}
  \to X_n \times_B Y_n
  \to B
  \to 0
\,.
$$
This is another $n$-extension of $B$ by $A$. The Baer sum imposes a group structure on the set of equivalence classes of $n$-extensions, the identity element being the class of split $n$-extensions with a canonical representative
$$
X_i =
\underbrace{A \oplus \dotsb \oplus A}_{\binom n i \text{ copies}}
\oplus
\underbrace{B \oplus \dotsb \oplus B}_{\binom n {n-i+1} \text{ copies}}
\;,
$$
making it isomorphic to the group $\operatorname{Ext}^n(B,A)$.
Comment: Doesn't your definition (equivalent=connected w chain morphism) imply symmetry? It looks to me like the problem is transitivity because another n-extension can be connected to one of these with arrows pointing in the opposite direction. Or do you mean that it's possible to reverse given arrows somehow? Could you elaborate, please? Sorry for necroposting.


How to define the termination condition for gradient descent?

Question: Actually, I wanted to ask you how can I define the terminating condition for gradient descent.
Can I stop it based upon the number of iterations, i.e. considering parameter values for, say, 100 iterations?
Or should I wait such that the different in the two parameters values 'new' and 'old' is very small to the order of lets say $10^{-6}$? This will definitely take much time.
What is the best way? In my case even one iteration takes significant time. In this situation if I wait for the 2nd condition it might even take weeks I guess.
So which approach should I use. How to tackle this scenario?
Comment: It isn't explicitly stated, but I assume that you are trying to find an MLE.

Your result really depends entirely on your parameter space, your likelihood function and your needs (aka, best isn't well defined).

If you are just looking for theoretical justification such as asymptotic efficiency; under Le'Cam conditions you can just use the one-step MLE (Under the further assumption is that you are using Newton's Method and the score function for your gradient descent).  This requires that your initial value is such that $n^{1/2}\hat{\theta}_0 \rightarrow \theta$ in probability.
Comment: One could stop when any one of:
function values $f_i$, or gradients $\nabla f_i$, or parameters $x_i$,
seem to stop moving, either relative or absolute.
But in practice $3 \times 2$ parameters `ftolabs` `ftolrel` .. `xtolabs` is way too many
so they're folded, but every program does that differently.
See
[Mathworks tolerances and stopping                                                                  criteria](https://nl.mathworks.com/help/optim/ug/tolerances-and-stopping-criteria.html)
for a picture.
Comment: so wait, when you said "new" - "old" is suffitiently small, is that an incorrect termination condition for gradient descent? (if fixed point like theorems apply, that condition should be ok?)
Answer: Nice question.  I've seen lots of stopping rules in the literature, and there are advantages and disadvantages to each, depending on context. The optim function in R, for example, has at least three different stopping rules:

maxit, i.e. a predetermined maximum number of iterations. Another similar alternative I've seen in the literature is a maximum number of seconds before timing out.  If all you need is an approximate solution, this can be a very reasonable.  In fact, there are classes of models (especially linear models) for which early stopping is similar to putting a Gaussian prior on your parameter values. A frequentist would say you have an "L2 norm" rather than a prior, but they would also think of it as a reasonable thing to do.  I've only skimmed this paper, but it talks about the relationship between early stopping and regularization and might help point you toward more information.  But the short version is, yes, early stopping can be a perfectly respectable thing to do, depending on what you're interested in.
abstol, i.e., stop when the function gets "close enough" to zero.  This may not be relevant for you (it doesn't sound like you're expecting a zero), so I'll skip it.
reltol, which is like your second suggestion--stop when the improvement drops below a threshold.  I don't actually know how much theory there is on this, but you'll probably tend to get lower minima this way than with a small maximum number of iterations.  If that's important to you, then it might be worth running the code for more iterations.

Another family of stopping rules has to do with optimizing a cost function on a validation data set (or with cross-validation) rather than on the training data.  Depending on what you want to use your model for, you might want to stop well before you get to the local minimum on your training data, since that could involve overfitting. I'm pretty sure Trevor Hastie has written about good ways of doing this, but I can't remember the citation.
Other possible options for finding lower minima in a reasonable amount of time could include:

Stochastic gradient descent, which only requires estimating the gradients for a small portion of your data at a time (e.g. one data point for "pure" SGD, or small mini-batches).
More advanced optimization functions (e.g. Newton-type methods or Conjugate Gradient), which use information about the curvature of your objective function to help you point in better directions and take better step sizes as you move downhill.
A "momentum" term in your update rule, so that your optimizer does a better job of rolling downhill rather than bounding off canyon walls in your objective function.

These approaches are all discussed in these lecture notes I found online.
Hope this helps!
Edit oh, and you can also try to get better starting values (e.g. by solving a simpler version of the problem) so that it takes fewer iterations to get close to the optimum from your "warm start".
Comment: The `abstol` parameter only makes sense if you're taking the tolerance of the gradient of the cost function, not the cost function itself. In a local optimizer, the value of the gradient is zero; but not the value of the function.
Comment: the issue with choosing a fixed number of iterations, is that unless you can clearly plot your cost curve (and it has small noise), then its hard to know how many iterations is too many, specially if the optimization function is complicated and who knows how many local minimums it has and if you have randomized initialization, this further worsen the issue, since it makes it even harder to guess what is a good "small" number of iterations. How do you address this issues in reality if you want to actually use early stopping? How do you make sure you dont over shoot nor undershoot too much?
Comment: I'd like to clarify what `reltol` (i.e. when there stops being an "improvement") means. First improvement means decreasing cost function. So I will assume that what you mean is that, when the cost function stops decreasing enough (or starts increasing) one halts, right? One does not actually do "|old - new|" type of update rule, right?
Comment: "warm start" is a very clever trick ! thanks


How do you save an entity reference value programmatically?

Question: I am using organic groups, which creates an entity reference field on a content type. Now i have a custom module that is supposed to create a node programatically and i am having trouble with saving the entity reference field.
Error message i get:Notice: Undefined property: DatabaseStatementBase::$nid
Here is what i have tried:
$qry= db_select('node', 'n')
           ->condition('type', 'some_og_content_type', '=')
           ->condition('title', 'some_title', '=')
           ->fields('n', array('nid'));
$ogRef= $qry->execute();

$ogNid = $ogRef->nid;

$node->og_group_ref['und'][0] = array('target_id'=>$ogNid);

//i also tried this
$node->og_group_ref['und'][0]['target_id']=$ogNid;

Answer: You need to get the results of your query after $query->execute() by for example calling $query->fetchAssoc() or $query->fetchAllAssoc(..).
Using $node->og_group_ref[LANGUAGE_NONE][0]['target_id'] is correct.
Be aware of the fact that your query might have multiple results. Do something like this to traverse them all:
$result = $query->execute();
while($entry = $result->fetchAssoc()) {
  $node = node_load($entry['nid']);
  // set the field and save the node
}

Depending on the number of expected entries you could also use EntityFieldQuery explained here https://www.drupal.org/node/1343708.
Another edit: When you want to set a field on a newly created node better use hook_node_presave or hook_node_insert then you do not need to care about searching for your node.
Comment: thank you! after doing the fetchAssoc(), i was able to get it to work!


Barnard and Child inequality exercise

Question: Prove that,
$$3(a^2b+b^2c+c^2a)(ab^2+bc^2+ca^2)≥abc(a+b+c)^3$$
For positive $a,b,c$
The exercises in this book are making me crazy.
Any help would be appreciated.
My attempts:
I opened the LHS brackets and used the cube identity on RHS
I get expressions which are somewhat similar but no idea how to proceed furthermore:
$$3\sum_{cyc}(a^3b^3+a^4bc+a^2b^2c^2)\geq abc\sum_{cyc}(a^3+3a^2b+3a^2c+2abc).$$
Comment: I solved your problem. If you want to see my solution, show please your attempts.
Comment: I opened the LHS brackets and used the cube identity on RHS,
Answer: Another way.
By your work, AM-GM and Muirhead we obtain:
$$3\prod_{cyc}a^2b\prod_{cyc}a^2c-abc(a+b+c)^3=\frac{1}{2}\sum_{sym}(3a^3b^3+2a^4bc+a^2b^2c^2-6a^3b^2c)\geq$$
$$\geq \frac{1}{2}\sum_{sym}\left(6\sqrt[6]{(a^3b^3)^3(a^4bc)^2a^2b^2c^2}-6a^3b^2c\right)=3\sum_{sym}\left(a^{\frac{19}{6}}b^{\frac{13}{6}}c^{\frac{2}{3}}-a^3b^2c\right)\ge0.$$
The last inequality is true because
$$\left(\frac{19}{6},\frac{13}{6},\frac{2}{3}\right)\succ(3,2,1).$$
Comment: What does that modified $>$ symbol mean?
Comment: $a\succ b$ says $a$ is a majoranta of $b$. Try to check it in google. I can not explain more because I am driving now. In evening, OK?
Answer: By Holder $$3\prod_{cyc}a^2b\prod_{cyc}a^2c=\prod_{cyc}1\prod_{cyc}a^2b\prod_{cyc}a^2c\geq$$
$$\geq\left(\sum_{cyc}\sqrt[3]{1\cdot a^2b\cdot a^2c}\right)^3= \left(\sum_{cyc}\sqrt[3]{a^4bc}\right)^3=abc(a+b+c)^3.$$
Comment: Shouldn't all the $\prod$ be replaced with $\sum$?

Barnard and Child inequality exercise


If I make a transferred DNS zone a standard primary, does that affect anything other than making it static?

Question: I do not want to break anything, but if I have a currently transferred zone, and I want to make it static, do I not just make it a Standard Primary?  I have several zones, but this is not one that is in my domain/forest.  I do not want to break the existing zones.
I am having difficulty with the one what is being transferred, and since the information doesn't change much, I wanted to make it static.
Thanks.
Answer: If you don't have administrative access to the server holding the Primary zone and don't have administrative access to that Primary zone, then nothing you do to the Secondary zone can have any affect on the Primary zone.
You would need to administratively access the server holding the Primary zone and make changes to that Primary zone in order to affect the Primary zone.
Comment: I am on the server.  I am an administrator.  I have my main zone that I put in there for my forest.  I have an outside forest that I was transferring because I need to resolve some of their names.  But, they change it very little, and I wanted to make their there transfer static with Standard Primary (not AD.)
Comment: You're not on the server that holds the Primary zone, you're on your server that holds the Secondary zone, right? If so, then nothing you can do to the Secondary zone or server will have any affect on the Primary zone or server. Now that you've given a little more info on the scenario, why don't you just set up a conditional forwarder on your server for the external zone?


Matchingproblems when using OpenCVs matchShapes function

Question: I´m trying to find a objekt in a larger Picture with the findContour/matchShape functions (the object can vary so it´s not possible to look after the color or something similar, Featuredetectors like SIFT also doesn´t work because the object could be symetric)

I have written following code:
Mat scene = imread...
Mat Template = imread...
Mat imagegray1, imagegray2, imageresult1, imageresult2;
int thresh=80;
double ans=0, result=0;

// Preprocess pictures
cvtColor(scene, imagegray1,CV_BGR2GRAY);
cvtColor(Template,imagegray2,CV_BGR2GRAY);

GaussianBlur(imagegray1,imagegray1, Size(5,5),2);
GaussianBlur(imagegray2,imagegray2, Size(5,5),2);

Canny(imagegray1, imageresult1,thresh, thresh*2);
Canny(imagegray2, imageresult2,thresh, thresh*2);

vector<vector <Point> > contours1;
vector<vector <Point> >  contours2;
vector<Vec4i>hierarchy1, hierarchy2;
// Template
findContours(imageresult2,contours2,hierarchy2,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0));
// Szene
findContours(imageresult1,contours1,hierarchy1,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0));

imshow("template", Template);
double helper = INT_MAX;
int idx_i = 0, idx_j = 0;
// Match all contours with eachother
for(int i = 0; i < contours1.size(); i++)
{
    for(int j = 0; j < contours2.size(); j++)
    {
        ans=matchShapes(contours1[i],contours2[j],CV_CONTOURS_MATCH_I1 ,0);
        // find the best matching contour
        if((ans < helper) )
        {
            idx_i = i;
            helper =  ans;
        }
    }
}
  // draw the best contour

 drawContours(scene, contours1, idx_i,
 Scalar(255,255,0),3,8,hierarchy1,0,Point());

When I'm using a scene where only the Template is located in, i get a good matching result:

But when there are more objects in the pictures i have trouble detecting the object:

Hope someone can tell me whats the problem with the code i´m using. Thanks
Answer: You have a huge amount of contours in the second image (almost each letter).

As the matchShape checks for scale-invariant Hu-moments (http://docs.opencv.org/3.1.0/d3/dc0/group__imgproc__shape.html#gab001db45c1f1af6cbdbe64df04c4e944) also a very small contours may fit the shape you are looking for.
Furthermore, the original shape is not distinguished properly like can be seen when excluding all contours with an area smaller 50.
if(contourArea(contours1[i]) > 50)
  drawContours(scene, contours1, i, Scalar(255, 255, 0), 1);

To say it with other words, there is no problem with your code. The contour can simply not be detected very well. I would suggest to have a look at approxCurve and convexHull and try to close the contour this way. Or improve the use of Canny in some way.
Then you could use a priori knowledge to restrict the size (and maybe rotation?) of the contour you are looking for.
Comment: Thanks for the answer and the explanation on what went "wrong".  I´m currently trying to follow your suggestions


Generalization of the group scheme $\textrm{Spec}(A(T))$

Question: Let $A$ be a ring, and let $S$ be the scheme $\textrm{Spec }A$.  Then the $S$-scheme $G = \textrm{Spec }A[T]$ has the structure of a group scheme over $S$, via the morphisms of $S$-schemes $$m: G \times_S G \rightarrow G, \iota: G \rightarrow G, e: S \rightarrow G$$
whose corresponding $A$-algebra homomorphisms are given respectively by
$$m^{\ast}: A[T] \rightarrow A[X,Y], \space \space f(T) \mapsto f(X+Y)$$
$$\iota^{\ast}: A[T] \rightarrow A[T], \space \space f(T) \mapsto f(-T)$$
$$e^{\ast}: A[T] \rightarrow A, \space \space f(T) \mapsto f(0)$$
If $X$ is any scheme over $S$, then we can identify $$G(X) = \textrm{Hom}_{S-\textrm{sch}}(X,G) = \textrm{Hom}_{A-\textrm{alg}}(A[T], \mathcal O_X(X)) = \mathcal O_X(X)$$
and the morphisms endow $G(X) = \mathcal O_X(X)$ with a group structure identical to the existing additive group structure on $\mathcal O_X(X)$.
Now, what if we replace the affine scheme $S$ with an arbitrary scheme?  Does there exist an $S$-group scheme $G$ such that $G(X) = (\mathcal O_X(X),+)$ for all $S$-schemes $X$?  The first thing I thought to try was $\textrm{Spec } \mathcal O_S(S)[T]$, but this probably isn't the correct object.
Comment: Don't know why this was downvoted, +1
Answer: As I typed my question, I realized the correct object to look at was
$$G = S \times \textrm{Spec } \mathbb{Z}[T]$$
(product in the category of schemes).  For an $S$-scheme $X$, to give a morphism of $S$-schemes $X \rightarrow G$ is the same as giving a morphism of schemes $X \rightarrow \textrm{Spec } \mathbb{Z}[T]$, so we can identify
$$G(X) = \textrm{Hom}_{\textrm{Sch}}(X, \textrm{Spec } \mathbb{Z}[T]) = \textrm{Hom}_{\textrm{Ring}}(\mathbb{Z}[T], \mathcal O_X(X)) = \mathcal O_X(X)$$
The group operations on $G$ are obtained by taking the obvious group operations on $\textrm{Spec } \mathbb{Z}[T]$, and tensoring with $1_S$.
Comment: Another way to think about this is to use the general fact that if $H$ is a group scheme over $S_0$, and $S \rightarrow S_0$ is a morphism of schemes, then $H \times_{S_0} S$ is a group scheme over $S$.  Now take $H = \textrm{Spec } \mathbb{Z}[T], S_0 = \textrm{Spec } \mathbb{Z}$.


SSIS /C# Variables value contants backslashes how to escaping

Question: I have a ssis package, it will auto read the free text file by delimiter(\t).
Due the delimiter(\t) get from the database table, after passed to SSIS variable. the c# will auto add one more backslash. value = (\\t)
so if i convert variable to ToCharArray(),it will have 2 chars items.[0]="\\", 1="t".This makes me unable to accurately split the file.
This is the effect I want, it can be automatically escaped to tab when it becomes char type
result = char(9) value = '\t'
"\t".ToCharArray();

2 items have been split and cannot be escaped as tab
Result:
[0] = char(92) value = '\\'
1 = char(116) value = 't'
Dts.Variables["User::ls_RepDelimiter"].Value.ToString().ToCharArray();

Does anyone have a good solution for this problem?
Comment: The problem is the starting point Dts.Variables["User::ls_RepDelimiter"].Value.ToString() = "\\t". That is wrong, but you can create an if or case to manage it.
var delim = Dts.Variables["User::ls_RepDelimiter"].Value.ToString() == "\\t" ? '\t' : Dts.Variables["User::ls_RepDelimiter"].Value.ToString().ToCharArray()[0];
Answer: Easiest option is to change what you have stored in the database. You have stored two characters \ and t. Instead, you want to store the non-printable character tab, ASCII value 9. CHAR is the function that allows you to input a numeric value and get the actual character associated to it.
SELECT char(9) AS ActualTab, '\t' AS EncodedTab

Using that as the source for an Execute SQL Task and stuffing the values into Variables, I see the value shows as \t for my real tab and \\t for the encoded tab.

And it makes sense, in C-like languages, non-printable characters are displayed with a backslash before the character thus \t is tab, \n is newline and \\ is the backslash character.
Otherwise, as @KeithL shows, a script task with a read/write variable parameter can convert the two character \t into a single character \t
Dts.Variables["User::ls_RepDelimiter"].Value = Dts.Variables["User::ls_RepDelimiter"].Value.ToString() == "\\t" ? '\t' : Dts.Variables["User::ls_RepDelimiter"].Value.ToString().ToCharArray()[0];

That's a one liner that evaluates whether the SSIS variable ls_RepDelimiter is equal to the two characters \t. If it is, it will use the single character \t, otherwise, it will strip out the first character of the string, hoping that represents what you intended to use as your delimiter within the file.
If you need to debug that, a multi-line version would be
string tab = "\t";
string encodedTab = "\\t";
string currentValue = Dts.Variables["User::ls_RepDelimiter"].Value.ToString();
// I am consciously using string here even though it will be a single char as I don't know what the casting rules will be for a char to string within SSIS scripting
string outValue = "";
outValue = (currentValue == encodedTab) ? tab : currentValue.ToCharArray()[0];

Dts.Variables["User::ls_RepDelimiter"].Value = currentValue;


PaperTrail retrieve has_many association

Question: I am using PaperTrail to version models. For a single model this works pretty well. However I cannot manage to restore a simple has_many relation, although the docs state that this should work.
I have two simple models:

class Template < ActiveRecord::Base
  has_many :assets, dependent: :destroy
  has_paper_trail
  #also has a title
end

class Asset < ActiveRecord::Base
  belongs_to :template
  has_paper_trail
  has_attached_file :file, :path => ':class/:id/:filename.:extension'
  do_not_validate_attachment_file_type :file
end

This is the procedure I use to test the versioning.
template = Template.create

template.title = 'initial'
template.assets.create()
template.save

title1 = template.title  #initial
count1 = template.assets.count #1

template.title = 'v2'
template.assets.create()
template.save

title2 = template.title #v2
count2 = template.assets.count #2

template_old = template.versions.last.reify(:has_many => true)

title3 = template_old.title #initial
count3 = template_old.assets.count #2, should be 1

template.title = 'v3'
template.assets.last.destroy()
template.save

title4 = template.title #v3
count4 = template.assets.count #1

template_old = template.versions.last.reify(:has_many => true)

title5 = template_old.title #v2
count5 = template_old.assets.count #1, should be 2

I have tracked this to the version_concern.rb reify_has_many_directly method. But to me it seems like it is always just restoring the relations from the current live version.
Any ideas?
Answer: When you call template_old.assets.count you cause a database query against the live database. Instead, use template_old.assets.length.


Trying to compile x86 assembly with GCC but getting errors about missing parenthesis and "junk after expression"

Question: Full disclosure the following code is for a homework, but I wrote the code I just need help figuring out why I'm getting several errors when trying to compile it (My professor never talked about GCC errors).
I wrote a function that returns the sum of the two largest members of an array of size 10. I've marked the lines 70 and 74:
function1:
    pushl   %ebp
    pushl   %ebx
    movl    $2, %ebx #ebx will be counter
    movl    %esp, %ebp #first will be %edx and second will be %eax
    movl    8(%ebp), %edx #first = arr[0]
    movl    (%edx,1,4), %eax #second = arr[1] **LINE 70**
    cmpl    %eax, %edx #if(arr[0] > arr[1]) don't jump
    jle .L6
.L7:
    movl    (8(%ebp),%ebx,4), %ecx #%ecx = next value to compare **LINE 74**
    cmpl    %ecx, %edx #if first > next don't jump
    jle .L8
    cmpl    %ecx, %eax #if second > next don't jump
    jle .L9
    cmpl    $9, %ebx #check if counter = 9
    je  .L10
    addl    $1, %ebx #counter++
    jmp .L7
.L6:
    movl %edx, %ecx #move arr[0] into %ecx
    movl %eax, %edx #first = arr[1]
    movl %ecx, %eax #second = arr[0]
    jmp .L7
.L8:
    movl %edx, %eax #move previous first into second
    movl %ecx, %edx #move new first into first
    addl $1, %ebx   #counter++
    jmp .L7
.L9:
    movl %ecx, %eax #move new second into second
    addl $1, %ebx   #counter++
    jmp .L7
.L10:
    addl %edx, %eax
    popl    %ebx
    popl    %ebp
    ret

I am getting the following error messages:
assign3.s:70: Error: expecting `)' after scale factor in `(%edx,1,4)'
assign3.s:74: Error: missing ')'
assign3.s:74: Error: missing ')'
assign3.s:74: Error: junk `(%ebp),%ebx,4))' after expression

I appreciate the help and let me know how I can improve my questions in the future
Comment: What is `(%edx,1,4)` supposed to mean? What is `(8(%ebp,%ebx,4))` supposed to mean?  You made some syntax errors and only you (as the author of the code) can tell what you meant to write instead.
Comment: Well, neither are valid addressing modes.  A scale/index/base operand has the form `displacement(base, index, scale)` where `displacement` is a constant or symbol, `base` and `index` are registers, and `scale` is 1, 2, 4, or 8.  `1` is not a register and `8(%ebp)` is not a register, so your syntax is incorrect.  Perhaps you meant `4(%edx)` for the first one and `8(%ebp, %ebx, 4)` in the second one, but I'm not quite sure.  It could be that you first need to load the value at `8(%ebp)` into a register so you can use it as a base register.
Comment: My suggestion to you is to always try to assemble and run your program while you write it so you catch errors as soon as you make them.  You spent a lot of time writing a long program without having ever tested it and now you might have made some systematic errors that might be rather annoying to fix.  If you assemble and run your code all the time during development, you catch such issues much quicker.
Comment: @fuz Another suggestion is to follow the language rules rather than just making up stuff. After all, this is computer programming, not poetry.
Comment: @Mobyh The creativity is in your data structures and algorithm. Syntax does not admit creativity. Parsers are very specific about what they accept.
Comment: `(%edx,1,4)` is the location of the first element in the array. `(8(%ebp),%ebx,4) `is a way of accessing the array at index %ebx
Comment: I will try your suggestions thanks! This is our first actual assignment in the semester where we have to compile code, and for the most part we have to learn outside of class for this course.
Comment: You are right @fuz and that really helped me when I deleted it all and started over I was testing it instead of fully writing the function blindly. And that is true @Raymond! There are rules that must be followed, but there's a creative aspect to solving problems with computer programming
Comment: @RaymondChen see what you meant now. You are right
Answer: I had to rework my code completely but thanks to @fuz I was able to find the proper solution. My problem was both in syntax and in understanding of registers and pointers. Here's the correct code:
function1:
    #FIRST %edx
    #SECOND %eax
    #THIRD  %ebx
    #LOCATION OF ARRAY %esi
    #COUNTER %edi
    pushl   %ebp
    pushl   %ebx
    pushl   %esi
    pushl   %edi
    movl    %esp, %ebp
    movl    $1, %edi
    movl    %eax, %esi
    movl    (%esi), %edx
    movl    (%esi, %edi, 4), %eax
    addl    $1, %edi
    cmpl    %eax, %edx
    jle     .L6
.L7:
    movl    (%esi, %edi, 4), %ebx
    cmpl    %ebx, %edx
    jle     .L8
    cmpl    %ebx, %eax
    jle     .L9
.L11:
    addl    $1, %edi
    cmpl    $10, %edi
    jne     .L7
    jmp     .L10
.L6: #Switch FIRST and SECOND
    movl %edx, %ebx
    movl %eax, %edx
    movl %ebx, %eax
.L8: #THIRD is bigger than FIRST
    movl %edx, %eax
    movl %ebx, %edx
    jmp .L11
.L9: #THIRD is bigger than SECOND
    movl %ebx, %eax
    jmp .L11
.L10: #Add and return
    addl %edx, %eax
    popl    %edi
    popl    %esi
    popl    %ebx
    popl    %ebp
    ret


Inequality Involving Supremum of Expectation

Question: Let $X, Y$ be two random variables and $f$ be a continuous function. If for any realization $X=x$, we have
$$
\mathbb{E}[f(x,Y)] \leq \sup_{x} \mathbb{E}[f(x,Y)]
$$
I was wondering if we can conclude that $\mathbb{E}[f(X,Y)] \leq \sup_x \mathbb{E}[f(x,Y)]?$
I guess it is fine, by something like substitution law for conditional expectation, but not pretty sure...Any comment is appreciated. Thank you.
Comment: What should $\sup_X$ mean for a r.v. $X$?
Comment: @Gono, My bad. I mean $\sup_x \mathbb{E}[f(x,Y)]$. I have edited it.
Answer: First of all, note that the assumption about particular realisations is vacuously true ($\mathbb{E}[f(X(\omega_0), Y)] \leq \sup_{\omega \in \Omega} \mathbb{E}[f(X(\omega), Y)]$ trivially- I have assumed $X$ and $Y$ are defined on a probability space $(\Omega, \mathcal{B}, \mathbb{P})$).
We will choose $X = Y$ to be Rademacher variables, i.e. $\mathbb{P}(X = 1) = \mathbb{P}(X = -1) = \frac{1}{2},$ supported on exactly these two points and $f: \mathbb{R}^2 \rightarrow \mathbb{R},$ $f(x, y) := xy,$ which is clearly continuous. Note that $\mathbb{E}[f(X, Y)] = \mathbb{E}[X^2] = 1.$ However, all the possible realisations for $X$ are $1$ and $-1$ and we have that $\mathbb{E}[f(1, Y)] = \mathbb{E}[f(-1, Y)] = \mathbb{E}[X] = 0,$ so it is not true that $\mathbb{E}[f(X, Y)] \leq \sup_{\omega \in \Omega} \mathbb{E}[f(X(\omega), Y)].$
Comment: Very nice! I see it totally. Thanks a lot! @Actually Fritz. Then I am wondering when can make the inequality true? Perhaps, if $X,Y$ be nonnegative might work?


Fatal error on content save

Question: I recently set up a local version of a remote site. The remote site is allowing me to create content fine, but for some reason the local version is throwing the following error upon save:
Drupal\Core\Entity\EntityStorageException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) ORDER BY users_field_data_2.name ASC' at line 4: SELECT base_table.uid AS uid, base_table.uid AS base_table_uid, users_field_data_2.name AS name FROM {users} base_table INNER JOIN {users_field_data} users_field_data ON users_field_data.uid = base_table.uid INNER JOIN {user__roles} user__roles ON user__roles.entity_id = base_table.uid LEFT JOIN {users_field_data} users_field_data_2 ON users_field_data_2.uid = base_table.uid WHERE (users_field_data.status = :db_condition_placeholder_0) AND (user__roles.roles_target_id IN ()) ORDER BY users_field_data_2.name ASC; Array ( [:db_condition_placeholder_0] => 1 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
This error also crops up on some admin pages, which seems to be related: Warning: Invalid argument supplied for foreach() in Drupal\Core\Database\Query\Condition->compile() (line 227 of core/lib/Drupal/Core/Database/Query/Condition.php).
I've done a handful of updates to the site since creating the local version but haven't tried creating new content until now, so it's hard to tell what started causing the error. Any suggestions on how to move forward with diagnosing this?
Comment: The best (only?) way to proceed is download a fresh copy of the remote site, apply they updates again, and this time check it still works after each until you find the culprit. Other than that, check the code for each of the updates you've already made and see if it could've been responsible. Then backtrack/fix as appropriate. The first approach seems like it would be more reliable
Answer: I realized that it must have been a database issue since the live and local sites were in sync except for some module installs -- same with the code. I pulled the live database and imported it into local and re-installed the modules one at a time. Everything is now working fine. All that I can figure is that there was an installation error somewhere along the way that didn't want to show itself.
Answer: This is a database issue and one method is to replace the settings.php file for d8 .

Update your changes on the new file with local database details.
Clear cache using drush.
drush cr

Fatal error on content save


Showing $4-\csc^2\left( \frac{n \pi}{6(n-2)} \right)$ is on the order of $1/n$

Question: The expression I have here is part of the upper bound given to the minimum distance of any 2 points out of $n$ points embedded in the unit sphere $\mathbb{S}^2$ in $\mathbb{R}^3$. If you have $n$ points on this unit sphere then we must have 2 points with a distance $d$ such that
$$d \le \sqrt{4-\csc^2\left( \frac{n \pi}{6(n-2)} \right)}$$
This result was proven by Fejes Tóth. What I wish to show is that $4-\csc^2\left( \frac{n \pi}{6(n-2)} \right)$ is on the order of $1/n$.
We can see in the limit as $n \to \infty$, $4-\csc^2\left( \frac{n \pi}{6(n-2)} \right) \to 0^+$. Also using basic numerical simulation for many and large $n$ I can visually verify that this statement seems to be true. The point now would be to show that for any $n$, then there exists some constant $k$ such that
$$4-\csc^2\left( \frac{n \pi}{6(n-2)} \right) \le \frac{k}{n}$$
This would be good enough. I'll be working on it here just thought the community may have some ideas :-)
Comment: Can you use the Taylor expansion of $\csc(x)$ about $x=\frac{\pi}{6}$?
Comment: @Dzoooks that sounds like a good idea, I will look into it. Not super comfortable with it but yes that's why I should try!
Answer: We wish to show that $$f(x)=\left(4-\frac kx\right)\sin^2\frac{\pi x}{6(x-2)}\le1$$ for all positive real $x$. This is evidently the case when $4-k/x\le0$ so we consider $x>k/4$ with $$f'(x)=\frac k{x^2}\sin^2\frac{\pi x}{6(x-2)}-\left(4-\frac kx\right)\frac{24\pi}{(6x-12)^2}\sin\frac{\pi x}{6(x-2)}\cos\frac{\pi x}{6(x-2)}.$$ We claim that $f'(x)>0$ for all $x>k/4$. This is equivalent to showing that $$\tan\frac{\pi x}{6(x-2)}-\frac{2\pi x(4x-k)}{3k(x-2)^2}>0.$$ The second term is at most $8\pi/3k$ so the inequality holds whenever $$\frac x{x-2}>\frac6\pi\arctan\frac{8\pi}{3k}\implies x>2+\frac2{\frac6\pi\arctan\frac{8\pi}{3k}-1}.$$ This is true whenever $k>8\pi/\sqrt3$ so $$4-\csc^2\left( \frac{n \pi}{6(n-2)} \right) \le \frac{\frac{8\pi}{\sqrt3}+\epsilon}{n}$$ for any $\epsilon>0$. It follows that $d<3.81n^{-1/2}$.
Answer: One approach is to use L'hopital's rule. For your purposes, it suffices to show that the following limit exists.
$$\lim_{n \rightarrow \infty} {4-\csc^2\left( \frac{n \pi}{6(n-2)} \right) \over {1 \over n}}$$
This is a ${0 \over 0}$ limit, for which L'hopital applies. But it would be complicated to check in this form. Instead, you can let $x = {n \over n - 2}$, making ${1 \over n} = {1 \over 2} - {1 \over 2x}$, and the limit becomes
$$\lim_{x \rightarrow 1} {4-\csc^2\left( \frac{\pi x}{6} \right) \over {1 \over 2} - {1 \over 2x} }$$
This is again a ${0 \over 0}$ limit, but it's easier to use L'hopital, and you get that the limit equals ${f'(1) \over g'(1)}$, where $f(x) = 4-\csc^2\left( \frac{\pi x}{6} \right)$ and $g(x) = {1 \over 2} - {1 \over 2x}$. Since $g'(1) = {1 \over 2} \neq 0$, you don't even have to calculate $f'(1)$ since any value will give that the limit exists.
Answer: By Taylor, we have
$$\csc \left(\frac{\pi  n}{6 (n-2)}\right)=2-\frac{2 \pi }{\sqrt{3} n}+\frac{\frac{7 \pi ^2}{9}-\frac{4 \pi
   }{\sqrt{3}}}{n^2}+O\left(\frac{1}{n^3}\right)$$
$$\csc^2 \left(\frac{\pi  n}{6 (n-2)}\right)=4-\frac{8 \pi }{\sqrt{3} n}+\frac{8 \pi  \left(5 \pi -6 \sqrt{3}\right)}{9
   n^2}+O\left(\frac{1}{n^3}\right)$$
$$4-\csc^2 \left(\frac{\pi  n}{6 (n-2)}\right)=\frac{8 \pi }{\sqrt{3} n}-\frac{8 \left(\pi  \left(5 \pi -6
   \sqrt{3}\right)\right)}{9 n^2}+O\left(\frac{1}{n^3}\right)$$
$$4-\csc^2 \left(\frac{\pi  n}{6 (n-2)}\right)=\frac{8 \pi }{\sqrt{3} n}+O\left(\frac{1}{n^2}\right)$$
Edit
Another way to do it using @Dzoooks' hint.
$$\frac{\pi  n}{6 (n-2)}=\frac{\pi (n-2)+2\pi}{6 (n-2)}=\frac \pi 6+\frac{\pi }{3 (n-2)}=\frac \pi 6+a$$
$$\csc \left(a+\frac{\pi }{6}\right)=2-2 \sqrt{3} a+7 a^2-\frac{23 a^3}{\sqrt{3}}+O\left(a^4\right)$$
$$\csc^2\left(a+\frac{\pi }{6}\right)=4-8 \sqrt{3} a+40 a^2+\left(-\frac{92}{\sqrt{3}}-28 \sqrt{3}\right)
   a^3+O\left(a^4\right)$$
$$4-\csc^2\left(a+\frac{\pi }{6}\right)=8 \sqrt{3} a-40 a^2+\left(\frac{92}{\sqrt{3}}+28 \sqrt{3}\right)
   a^3+O\left(a^4\right)$$ Now, let $a=\frac{\pi }{3 (n-2)}$ and, continuing with Taylor series, the same result.


want to display values of content type Article in a page

Question: I have following fields in my content type Article:
Year: [have values - 2011,2012,2013,2014,2014,2016]
Volume: [have values - 01,02,03,04,05]
Issue: [have values - 1,2,3,4,5]
Title: [some value]
Description: [some text]
Now I want to display fields values like order below in views-view--archives--page.tpl.php
2013: [Volume3: Issue1, Issue 2, Issue 3] 2012: [Volume2: Issue1, Issue 2]
Comment: You set-up a view for this? You can rearrange the order, and opt to display the fields in-line within the Views UI. Or maybe I'm mis-understanding the question.
Answer: Maybe you can write a custom template or a custom theme function to output the fields, you will have to play with delta. You can also create multiple content types and link them with a relation field to create the hierarchy. You can also use a specific module that handles this kind of dimensional representation like tablefield or sheetnode.
Comment: could you please suggest any tutorial. I am new to Drupal. I know the basic but never done custom pages.
Comment: You can find here how to override a view template: http://drupal.stackexchange.com/a/51710/17992


Acessar servidor php embutido do docker no Host

Question: Bom pessoal to estudando docker aqui e junto com isso quero criar um servidor php (pelo seu servidor embutido) e ai então acessar esse servidor de minha máquina HOST.
Executei o seguinte comando:
<code>docker run -it -p 8080:8080 -v "D:\git\slim-saa:/home" -w "/home" my_opensuse_slim php -S localhost:8080 -t public public/index.php
</code>
Apos executar esse comando o servidor roda normalmente:

As portas e os volumes são mapeados normalmente (eu acho kk):

Mas quando vou na minha maquina e acesso o localhost:8080, não acesso nada:

Vocês tem ideia sobre o que de fiz errado?
Comment: Jhonatan, o [pt.so] possui uma estrutura de perguntas e respostas, que difere de um fórum. Na nossa estrutura, a solução do problema deve estar sempre presente na área de respostas e nunca na pergunta. Se encontrou por si só a solução, sinta-se a vontade para responder a própria pergunta. Isso não só é permitido como é altamente incentivado na nossa comunidade. Recomendo que leia o [tour] para entender melhor o funcionamento do site.
Comment: Feito @AndersonCarlosWoss Obrigado pelas dicas.
Answer: encontrei o problema mas não a solução definitiva. Ocorreu que meu mapeamento contêiner-host estava certo, problemático mesmo estava a maneira que eu estava/estou utilizando o servidor web embutido do php. Instalei o php+apache normalmente na imagem e ao levantar o servidor web tudo funcionou.


Insert DateTime into SQL DateTime

Question: I am trying to insert a DateTime into my SQL Server table column of type DateTime2(7) using the INSERT INTO syntax.
The error I receive is:

An unhandled exception of type 'System.Data.SqlClient.SqlException'
  occurred in System.Data.dll
Additional information: Conversion failed when converting date and/or
  time from character string.

I initialize the DateTime variable with:
DateTime TaskCreatedDate = DateTime.Now;

and use it here:
insertTaskCmd.Parameters.AddWithValue("@TaskCreatedDate", TaskCreatedDate);

Any thoughts?
Update:
I have tried:
insertTaskCmd.Parameters.Add("@TaskCreatedDate", SqlDbType.DateTime2).Value = TaskCreatedDate;

with the same error being produced.
Full query:
            string insertTask = String.Format("INSERT INTO [Tasks] VALUES (@TaskNumber, '@TaskCreatedDate', '', '', '', @Status, '3', '')");
            SqlCommand insertTaskCmd = new SqlCommand(insertTask, conn);
            insertTaskCmd.Parameters.AddWithValue("@TaskNumber", newTaskNumbers[i]);

            insertTaskCmd.Parameters.Add("@TaskCreatedDate", SqlDbType.DateTime2).Value = TaskCreatedDate.ToString("yyyy-MM-dd HH:mm:ss");

            insertTaskCmd.Parameters.AddWithValue("@Status", 0); // 0 is Active
            insertTaskCmd.ExecuteNonQuery();

Comment: You should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results...
Comment: a handy replacement for `AddWithValue` is  `Parameters.Add(new SqlParameter("@paramName", SqlDbType.WhatEver, columnSize) { Value = valueVariable };`. When you always specify the same size for character columns, you will produce only one execution plan. When you leave it out, you end with one plan for each parameter value length combination you are using in the query.
Comment: you should tell us what the actual datatype of the `TaskCreatedDate` is it a DateTime or a TimeStamp
Comment: And if it's not a Datetime, try making it one.
Comment: also is this a typo `insertTaskCmd.Parameters.Add("@TaskCreatedDate", SqlDbType.DateTime2).Value` the `DateTime2`...?? @Lighty please show what the stored proc or query looks like as well as the Table Schema in regards to the dataype of the field. it will help in eliminating any and all guess work from us
Comment: possible duplicate of [Conversion failed when converting date and/or time from character string while inserting datetime](http://stackoverflow.com/questions/14119133/conversion-failed-when-converting-date-and-or-time-from-character-string-while-i)
Comment: I'm extremely glad I've read that, but in this case, it didn't solve the issue.  Thanks
Comment: Great tip by @eFloh. Could you maybe also specify what you are doing? Are you called a Stored Procedure or using default INSERT INTO syntax? Either way, could you perhaps include the query you are using?
Comment: I tried it with DateTime and DateTime2, both are valid SQL types
Comment: @jean the easiest thing to do is to not change it to a varchar(30) the simplest thing to do for the OP is to tell us what the actual datatype is for that column as well as the query
Comment: first problem I see is in the query.. why are you not defining the exact fields that you want to insert into.. try changing the query and I bet it will work.. also if you are going to post code..please show how all relevant values in regards to your issue are used, populated and or defined `newTaskNumbers` ...?? refactor your query to use `Parameterized query` wrap all the Sql objects around a using. as well, wrap all Executing attempts around a `try{}catch{}` you are assuming that your query will always run without failure
Comment: Is there a **trigger** on that table?
Answer: I think your insert query is just wrong - you have the @TaskCreatedDate in single quotes - that shouldn't be .....
Try this:
string insertTask = "INSERT INTO [Tasks] VALUES (@TaskNumber, @TaskCreatedDate, '', '', '', @Status, '3', '')";

SqlCommand insertTaskCmd = new SqlCommand(insertTask, conn);
insertTaskCmd.Parameters.Add("@TaskNumber", SqlDbType.Int).Value =  newTaskNumbers[i];
insertTaskCmd.Parameters.Add("@TaskCreatedDate", SqlDbType.DateTime2).Value = TaskCreatedDate;
insertTaskCmd.Parameters.Add("@Status", SqlDbType.Int).Value = 0; // 0 is Active

insertTaskCmd.ExecuteNonQuery();

Note: I would also recommend to always explicitly specify the columns you want to insert into:
string insertTask = @"INSERT INTO [Tasks](TaskNumber, TaskCreatedDate, .., .., .., Status, .. ..)
                      VALUES (@TaskNumber, @TaskCreatedDate, '', '', '', @Status, '3', '')");

Answer: Fixed.
Note around the @TaskCreatedDate there are single quotation marks (').  Remove these and it's solved.
Comment: you need to remove all quoted text and start using / learning how to use parameters.. as well as the debugger.. respectfully speaking
Comment: @MethodMan: That seems uncalled for. The OP does use parameters. Some of the inserted values happen to be constants, hence the need to use quotes.
Comment: @AndriyM perhaps you missed this part in the OP's original question `'@TaskCreatedDate'`

Insert DateTime into SQL DateTime


How to automate sending warning email if USB backup drives are not rotated frequently enough?

Question: Our off-site backup system relies on a staff member alternating which USB drive is connected to the file server each week.
Whichever drive is connected then synchronizes with the data partition on the server (nightly at 10pm) using a scheduled batch file, which runs Robocopy. The USB drives themselves are both encrypted using Truecrypt to protect our organization in the event of either of them being lost or stolen.
The weak (human dependent) link in our backup system is the staff member responsible for rotating the drives each week. Sometimes, he not only forgets to do this on the required weekly basis but for well over a month.
I already have logging set up which allows me to track when the drives are rotated thanks to the answer from my earlier question here. So we already have a log file which tracks which drive is connected for any given day.
What I now want to do is to have an automatic email sent from the server (SBS 2003) to the user responsible for rotating the drives, the user's boss and myself (sysadmin) if the backup schedule is being missed for two or more weeks. Outlook 2010 is not currently installed on the server but could be if necessary.
Data in the log which tracks which backup drive is connected is in the following format:
<code>Volume in drive V is BACKUP 1
Sat 05/10/2014
22:00:00.77

Volume in drive V is BACKUP 1
Sun 05/11/2014
22:00:00.44

Volume in drive V is BACKUP 1
Mon 05/12/2014
22:00:00.39

Volume in drive V is BACKUP 1
Tue 05/13/2014
22:00:01.50
</code>
Does anyone have any ideas how I could automate sending a warning email if the same backup USB drive number appears for a certain number of consecutive times at the bottom of the log file? For example, 14 or more (as this would indicate the weekly drive rotation the user should have performed is now a full week overdue).
Any ideas would be much appreciated!
Comment: I notice three people voted to close this - without stating the reasons why. Does anyone have any ideas why people are voting to close this? None of the close voters were SMART enough to leave any feedback, so I'm just left trying to guess what their problem is.
Comment: Isn't this just trying to solve the wrong problem?
Comment: I can see why you could argue that, but I want this to automatically react on my behalf if there is a problem to save me having to intervene myself. Rotating the drives is already a part of someone's job description but unexpected things happen and things can get forgotten.
Answer: This would work. You have to add the code for sending the email inside the if condition and change LOGFILE to whatever you logfile path is:
<code>#!/bin/bash

LOGFILE="logtest"
COUNT=`tail -n16 $LOGFILE | grep "Volume in" | uniq -c | cut -c0-7 | tail -n1`

echo "Last tape repeated $((COUNT)) times"

if [ $COUNT -gt 3 ]; then
  echo "Sending email..."
  mutt -s"FATAL: Missing tape rotation" email@example.com < /dev/null
fi
</code>
Comment: I use **mutt** for that. I've added the line in the reply now.
Comment: Thanks! Do you have any particular recommendations as far as code for sending email is concerned?


Pegar um item de uma lista

Question: Bom dia, eu venho tentando fazer um mini jogo, onde eu insiro as palavras na variável WORDS e o mesmo digita o nome de forma aleatória, até aqui Ok.
Mas eu queria mudar e não estou conseguindo fazer o que eu quero, pois não encontro uma forma de fazer o mesmo.(Comecei a estudar programação no fim de semana passada).
Segue o código:
import random

WORDS = ("palavra1", "palavra2", "palavra3")
word = random.choice(WORDS)
correct = word
champions = ""
while word:
    position = random.randrange(len(word))
    champions += word[position]
    word = word[:position] + word[(position + 1):]
print("")
print("A palavra é:", champions)
guess = input("Nome: ")
while guess != correct and guess != "":
    print("Essa não é a palavra")
    guess = input("A palavra é: ")
if guess == correct:
print("Você acertou\n")

input("\n\nPressione Enter para sair. Versão 1.0")

O que eu queria mudar, eu tentei fazer que o resultado da variável "word" puxasse uma dica de uma lista e inserir essa dica depois que a pessoa errar.
palavra1 = ["dica1","dica2","dica3"]
palavra2 = ["dica1","dica2","dica3"]
palavra3 = ["dica1","dica2","dica3"]

Exemplo:
    print("Essa não é a palavra")
    print("Dica:", dica1,".")
Imagino que ficou confuso, mas acho que da pra entender.
Comment: `WORDS` define uma lista de palavras que serão sorteadas. `word` é a palavra sorteada. `champions` é um anagrama de `word`. É exibido o valor `champions`, de forma que o usuário tente acertar a palavra correta, `correct`. O programa fica requisitando uma nova palavra até que o usuário acerte. Agora você deseja que uma dica seja exibida quando o usuário errar. Pergunta: Cada diva deve ser exibida apenas uma vez ou podem se repetir e sempre mostrar uma dica quando o usuário errar a palavra?
Comment: Sempre mostrar uma nova dica quando ele errar, coloquei uma repetição, mas não coloquei aqui no código do site, a pessoa vai ter cinco chances, se errar as cinco, perde.
Comment: E serão cinco dicas?
Comment: Sim, serão cinco dicas, coloquei somente três como exemplo, mas serão cinco.
Answer: Descreverei o programa por partes, pois acredito que alguns detalhes possam ser melhorados. Primeiro, vamos criar uma lista de palavras que farão parte do jogo de adivinhação. Para cada palavra, haverão cinco dicas.
WORDS = [
    ("palavra1", ["dica1", "dica2", "dica3", "dica4", "dica5"]),
    ("palavra2", ["dica1", "dica2", "dica3", "dica4", "dica5"]),
    ("palavra3", ["dica1", "dica2", "dica3", "dica4", "dica5"])
]

Para sortear uma palavra, junto com suas dicas, basta utilizar random.choice:
word = random.choice(WORDS)

Para criar um anagrama, isto é, embaralhar as letras da palavra, você pode converter a palavra para uma lista, utilizar o método sort e retornar para uma string:
anagram = list(word[0])
anagram.sort()
anagram = "".join(anagram)

print("Tente adivinhar:", anagram)

Para fazer a leitura das tentativas do usuário, considerando um máximo de 5 chances, basta utilizar um for:
# Cinco tentativas:
for i in range(5):

  # Lê a tentativa do usuário:
  guess = input("Tentativa #{}: ".format(i+1))

  # Varifica se o usuário acertou:
  if guess == word[0]:

    # Sim, exime a mensagem e encerra o loop:
    print("Parabens! Você acertou.")
    break

  # Não, exibe uma dica:
  print("Dica:", word[1].pop(0))

else:
  # O usuário não acertou a palavra:
  print("Ihh, não foi dessa vez.")

Para exibir a dica, utilizei o método pop, retirando sempre a primeira dica da lista referente à palavra. Desta forma, as dicas serão dadas em ordem: dica 1, dica 2, dica 3, etc. Considerando que na primeira tentativa não haverá uma dica, para 5 chances são necessárias somente 4 dicas.
O programa completo ficaria:
import random

# Lista de palavras e as respectivas dicas:
WORDS = [
    ("palavra1", ["dica1", "dica2", "dica3", "dica4"]),
    ("palavra2", ["dica1", "dica2", "dica3", "dica4"]),
    ("palavra3", ["dica1", "dica2", "dica3", "dica4"])
]

# Sorteia uma palavra:
word = random.choice(WORDS)

# Gera o anagrama da palavra:
anagram = list(word[0])
anagram.sort()
anagram = "".join(anagram)

# Exibe o anagrama:
print("Tente adivinhar:", anagram)

# Cinco tentativas:
for i in range(5):

  # Lê a tentativa do usuário:
  guess = input("Tentativa #{}: ".format(i+1))

  # Varifica se o usuário acertou:
  if guess == word[0]:

    # Sim, exime a mensagem e encerra o loop:
    print("Parabens! Você acertou.")
    break

  # Não, exibe uma dica:
  print("Dica:", word[1].pop(0))

else:
  # O usuário não acertou a palavra:
  print("Ihh, não foi dessa vez.")

Veja funcionando no Repli.it ou no Ideone.
Comment: Obrigado Anderson, vou utilizar suas dicas. :)

Pegar um item de uma lista


How Do I improve the performance of my Drupal7 Site?

Question: For somebody who is new to Drupal,  I see that there are many resources available on Drupal Caching but I am not sure which of them to use.
Comment: We can discuss whether we want a canonical question for this on meta, but I still think it is too broad.  And performance improvements can be very context sensitive and not done in a vacuum.
Answer: These are notes from my experiences and might vary from what others experience. I predominantly use LAMP stack and have considered the same in my suggestions.
Thumb rules for caching that I generally follow.

Process Once Use Multiple Times.
Live with stale data when possible
Clear Caches infrequently and keep it very specific.
When possible do the changes at the lowest level in the stack.
LAMP - DCCc : Linux,    Apache, Mysql, PHP, Drupal Core, Contrib and custom module.

Improve Performance of a Drupal Site (In the increasing order of complexity)

Keep the core updated, contrib module and themes updated. Yes it
matters.
Install APC on your server. (Moved to top based on suggestion from
Letharion)
Page Caching : admin/config/development/performance Difference between Minimum cache lifetime and Expiration of cached pages
Block Caching https://drupal.org/project/blockcache_alter Caching options for all the blocks.
Aggregate javascript and css files - Front End Improvements
https://www.drupal.org/project/advagg
Disable Unnecessary modules. Every module adds to the amount of code
that needs to be available for a page load. And it also increases
the number of lookups. Wherver possible use a generic module in
place of multiple module that does specific functionalities.
Cache Views content - Content aware caching for Views
https://www.drupal.org/project/views_content_cache
Disable DB logging - Use https://drupal.org/project/syslog_ng
Reduce 404 Errors -  http://www.brokenlinkcheck.com/
Fast 404 Responses  - https://drupal.org/project/fast_404 - Try
handling at server level.
Client Side Validations -
 https://www.drupal.org/project/clientside_validation
Compress Image - https://www.drupal.org/project/imageapi_optimize
Lazy Loading of Images - Don't load unnecessary images -
https://www.drupal.org/project/lazyloader
Use Sprite Sheets - https://www.drupal.org/project/spritesheets
Set Minimum Cache Life Time Value to a higher number and use cache clearing modules to clear the caches for specific pages - Whenever I edit/update a node all the page caches for anonymous user are lost
Use Devel Module to watch queries.
Rewrite Views Queries /  avoid Views if its a overkill.
XHProf - https://www.drupal.org/project/XHProf
FPM, HHVM.
DB Profiling and Tuning - https://www.drupal.org/project/dbtuner
Use Boost, don't Bootstrap DB if not required.
 https://drupal.org/project/boost For most of the small to medium sites Boost is good enough and you may not need Reverse Proxies or so.
Use CDNs - https://www.drupal.org/project/cdn Its easy to set up.
If your cache tables are huge use Memcached - If you can install
 memcached and set up RAM for it, it is not as complex as it sounds.
Etags - Configure Etags properly.
https://developer.yahoo.com/blogs/ydnfiveblog/high-performance-sites-rule-13-configure-etags-7211.html
Use Reverse Proxy Server - Varnish(at-least for assets). Helps a lot if most of your users are anonymous.
Compressed transfer - Enable gzip compression
Keep Alive - Use Persistent Connections where possible.
Progressive JPEGS -
CACHING IN CODE - Eaton's blog is awesome.
 http://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7
Implement Cache Warming - https://www.drupal.org/project/cache_warmer - Cache Warm the pages before the end user hits them.
Master Slave DB Config - https://www.drupal.org/project/autoslave makes it easier for you to set up one.
Database Clusters - https://stackoverflow.com/questions/1163216/database-cluster-and-load-balancing
Load Balancers -http://en.wikipedia.org/wiki/Load_balancing_(computing)
Use heuristic Cache Warming - https://www.drupal.org/project/cache_graceful
Authenticated User Caching - https://www.drupal.org/project/authcache
Comment: Excellent answer, but one things that strongly stands out to me, is that you don't have APC at the top. APC is trivially easy to get into place, there are no down-sides, and the gains can be really large. I think it should go to the top. (Maybe with a comment that it's not needed after PHP 5.5 as the optimization finally got integrated)
Comment: Maybe also mention something about the easiest gains for caching? If your site requires mostly static content (pages are same for all users, so no logins), then Varnish or Boost provides the largest gains.
Answer: The database layer is important. I cover some parts of it and the basics in this presentation http://goo.gl/30yi39
Comment: Awesome presentation MikeyTown. You are the performance pro :)
Answer: As a companion to Gokul's answer here's the way I would think about what you want to cache in Drupal (not ordered by complexity):
Caching means speeding up repeated activities.
The big repeat actions involved in a Drupal website are:

Calling a webpage
Running PHP code to build a webpage
PHP calling items from the database

Caching an entire webpage
The biggest caching gains are to be had from finding a way to cache an entire webpage without ever running the PHP code or calling the database.
You can do this with Varnish or Boost. When a user calls a page they return a copy of the page without ever doing a calculation.
However this won't work if parts of the page have to be different (i.e. users login and their name appears at the top).
In order to get that to work you need to look into Authcache.
PHP Caching
You can cache PHP with APC, or if you have version 5.5 or greater then a different cache is built in.
This is done server side and means chunks of your PHP code will be remembered. You're caching PHP for Drupal but you're not technically interacting with Drupal.
Database Caching
Calls to grab information from the database are expensive.
The commonest database caching mechanism is memcache.
This caches database objects in RAM, so instead of making a call to a database object on the harddrive, you just pull it from the RAM which is a lot faster.
Comment: Redis is also a great in-memory cache store, at least comparable with memcache in my experience (though memcache probably wins out with clustering)


How do I ignore the group in a regex split in python?

Question: I know this is probably really easy question, but i'm struggling to split a string in python. My regex has group separators like this:
myRegex = "(\W+)"

And I want to parse this string into words:
testString = "This is my test string, hopefully I can get the word i need"
testAgain = re.split("(\W+)", testString)

Here's the results:
['This', ' ', 'is', ' ', 'my', ' ', 'test', ' ', 'string', ', ', 'hopefully', ' ', 'I', ' ', 'can', ' ', 'get', ' ', 'the', ' ', 'word', ' ', 'i', ' ', 'need']

Which isn't what I expected. I am expecting the list to contain:
['This','is','my','test']......etc

Now I know it's something to do with the grouping in my regex, and I can fix the issue by removing the brackets. But how can I keep the brackets and get the result above?
Sorry about this question, I have read the official python documentation on regex spliting with groups, but I still don't understand why the empty spaces are in my list
Comment: Why would you want to keep those brackets (capturing group)?
Comment: Yiy mean you still want to use the capturing group? Try `myRegex = r"\s*([^\w\s])\s*"`
Answer: As described in this answer, How to split but ignore separators in quoted strings, in python?, you can simply slice the array once it's split. It's easy to do so because you want every other member, starting with the first one (so 1,3,5,7)
You can use the [start:end:step] notation as described below:
testString = "This is my test string, hopefully I can get the word i need"
testAgain = re.split("(\W+)", testString)
testAgain = testAgain[0::2]

Also, I must point out that \W matches any non-word characters, including punctuation. If you want to keep your punctuation, you'll need to change your regex.
Comment: Yes, this is what I was looking for. Thank you!
Answer: You can simly do:
testAgain = testString.split()  # built-in split with space

Different regex ways of doing this:
testAgain = re.split(r"\s+", testString)   # split with space
testAgain = re.findall(r"\w+", testString) # find all words
testAgain = re.findall(r"\S+", testString) # find all non space characters


jquery mobile collapsible widget styling not working

Question: I am trying to include a collapsible widget in jquery mobile. The content is dynamic so I am using a markup to do this, but just for illustration I have included default text. The following code just brings no widget but just the text appears, the styling of the widget doesn't appear. Here is my javascript
  description_markup += '
Description heading

'+description+'
';

   $('#Desc').empty().append(description_markup);

HTML

when I put the Desc div outside the content div, the text appears with a black background.
Please help
Comment: when you say collapsible widget, do you mean an accordion widget? http://jqueryui.com/accordion/
Comment: @cfs I mean the "collapsible widget" from jquery mobile http://api.jquerymobile.com/collapsible/
Answer: jQuery Mobile team is still working on creating methods for collapsible such as refresh. Unfortunately, collapsible doesn't accept any method now. Thus, replacing current collapsible with a new one is the only way.

Demo

var description_markup = '

Description heading

collapsible

';
$('#Desc').replaceWith(description_markup);
$('#Desc').collapsible();

If collapsible is enhanced and you don't want to replace it, you still can do modifications.
$('#Desc .ui-btn-text').text('new header');
$('#Desc .ui-collapsible-content').append('
new content
');

Inserting widgets inside collapsible requires .trigger('create') to enhance widget markup
$('#Desc .ui-collapsible-content').append('

link

link

').trigger('create');


Ajax submission not working for Webform within a node

Question: I am working with a feature where a newsletter subscription form (Webform with ajax submission and confirmation type is inline) should appear in a node. The node would be showing as a popup and the contents of popup is being loaded using ajax. When the node is tested in it's own node page the submission is working fine but not in the popup.It is redirecting to another page. Inspecting the two cases, i found that the webform while being loaded in popup, lacks event handler that should refer to form submission.
In the controller where webform being loaded into the popup block, something like this is tried:
  $webform = $this->entityTypeManager->getStorage('webform')->load($formId);
  $view_builder = $this->entityTypeManager->getViewBuilder('webform');
  $build = $view_builder->view($webform);

Where $formId is the id of the webform and entityTypeManager is an instance of Drupal\Core\Entity\EntityTypeManagerInterface.
Later this $build is being saved as the webform attribute of popup class and later being rendered. The fields of the webform appears to be loaded correctly but not the event of submission form.
Any suggestion for solving the issue?
Answer: This is a gotcha of AJAX forms.
When you load an AJAX form via AJAX it loses its AJAX functionality.
In order to keep it working, for the form that is getting loaded via ajax, you need to add a url and options keys to #ajax
/*
 * Implements hook_form_alter()
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // I created a webform called "test"
  if ($form_id == 'webform_submission_test_add_form') {
    $webform_id = 'test';
    $form['actions']['submit']['#ajax']['url'] = \Drupal\Core\Url::fromRoute('entity.webform.canonical', ['webform' => $webform_id]);
    $form['actions']['submit']['#ajax']['options'] = [
      'query' => [
        Drupal\Core\Form\FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
      ],
    ];
  }

}

Side note: this loss of AJAX issue doesn't occur with the HTML way of opening dialog boxes

   Should load Test webform in a Modal

because it has the URL of the form and knows its an AJAX request from the class name.


Apache Reverse Proxy Config?

Question: can someone tell me what is wrong with my reverse proxy setup? I can successfully auth with ldap but I just get the Apache2 Default Page
I tried putting the ProxyPass and ProxyPassReverse setting into the Location block but I get the following error on starting Apache

ProxyPass|ProxyPassMatch can not have a path when defined in a
location

I was following the Arkime guide https://arkime.com/faq#how-do-i-proxy-arkime-using-apache
<VirtualHost *:443>
  ServerName test-arkime.domain.com
  SSLEngine on
  SSLCertificateFile "/opt/arkime/etc/test-arkime.crt"
  SSLCertificateKeyFile "/opt/arkime/etc/test-arkime.key"
  ProxyPass        /arkime/ http://localhost:8005/ retry=0
  ProxyPassReverse /arkime/ http://localhost:8005/
  RequestHeader set ARKIME_USER %{REMOTE_USER}e
 <Directory />
  Order allow,deny
  Allow from all
  AuthType Basic
  AuthName "Enter account credentials"
  Require valid-user
  AuthBasicProvider ldap
  AuthLDAPGroupAttribute member
  AuthLDAPSubGroupClass group
  AuthLDAPGroupAttributeIsDN On
  AuthLDAPURL ldap://ldap.domain.com:389/OU=USERS,DC=domain,DC=com?sAMAccountName?sub?(objectClass=*)
  AuthLDAPBindDN email@example.com
  AuthLDAPBindPassword password123

  require ldap-group "CN=Users,OU=IT Users,OU=Security,OU=Groups,OU=CORP,DC=domain,DC=com"
 </Directory>
 ProxyPreserveHost On
</VirtualHost>

I just get the Apache2 Default Page
Apache2 Default Page
Answer: Figured it out for the most part, I can now hit Arkime, I now just need to figure out why it's not recognising or maybe not passing the arkime_user through
{"success":false,"text":"User not found"}
<VirtualHost *:443>
  ServerName test-arkime.domain.com
  SSLEngine on
  SSLCertificateFile "/opt/arkime/etc/test-arkime.crt"
  SSLCertificateKeyFile "/opt/arkime/etc/test-arkime.key"
  # redirect from root to subdirectory
  RedirectMatch ^/$ /arkime/
<Location /arkime/>
  Order allow,deny
  Allow from all
  AuthType Basic
  AuthName "Enter account credentials"
  Require valid-user
  ProxyPass        "http://localhost:8005/" retry=0
  ProxyPassReverse "http://localhost:8005/"
  RequestHeader set ARKIME_USER %{REMOTE_USER}e
  ProxyPreserveHost On
  AuthBasicProvider ldap
  AuthLDAPGroupAttribute member
  AuthLDAPSubGroupClass group
  AuthLDAPGroupAttributeIsDN On
  AuthLDAPURL ldap://ldap.domain.com:389/OU=com,DC=domain,DC=com?sAMAccountName?sub?(objectClass=*)
  AuthLDAPBindDN email@example.com
  AuthLDAPBindPassword Password123
  require ldap-group "CN=Users,OU=IT Users,OU=Security,OU=Groups,OU=com,DC=domain,DC=com"
</Location>
</VirtualHost>

Apache Reverse Proxy Config?


Nginx proxy_pass rewrite URL and Headers

Question: I want request to
http://localhost/app/httpbin.org/anything?test=data@cookieValue

forwarded into
Get https://httpbin.org/anything?test=data
Cookie: myCookies=cookieValue

I tried below but it return 404
location ~* ^/app/(.*?)@(.*){
        resolver 126.96.36.199;
        proxy_pass https://$1$is_args$args;
        proxy_set_header  Cookie myCookies=$2;
    }

Answer: Solved, the problem is nginx regex only match path or
/httpbin.org/anything

not parameter or query string
?test=data@cookieValue

to solve the problem I change the URL to
http://localhost/app/cookieValue/httpbin.org/anything?test=data

and here the config
location ~ ^/app/([^\/]+)/(.*){
    resolver 220.127.116.11;
    proxy_pass https://$2$is_args$args;
    proxy_set_header  Cookie myCookie=$1;
}